blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
721
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
5
91
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
321 values
visit_date
timestamp[ns]date
2016-08-12 09:31:09
2023-09-06 10:45:07
revision_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
committer_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
github_id
int64
426
681M
star_events_count
int64
101
243k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[ns]date
2012-06-28 18:51:49
2023-09-14 21:59:16
gha_created_at
timestamp[ns]date
2008-02-11 22:55:26
2023-08-10 11:14:58
gha_language
stringclasses
147 values
src_encoding
stringclasses
26 values
language
stringclasses
2 values
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
6
10.2M
extension
stringclasses
115 values
filename
stringlengths
3
113
content
stringlengths
6
10.2M
9bd24b77485c50b6796e4e1cc65e07a54c42d759
83b8b30ebb633eecd29ca0a7a20cc43a293c9333
/shared-bindings/_bleio/ScanEntry.c
83966d171944f80188f5ebe9300951c23a3cf434
[ "MIT", "GPL-1.0-or-later" ]
permissive
adafruit/circuitpython
430ec895149d1eb814b505db39b4977a35ee88a7
506dca71b0cbb7af749bb51f86b01021db5483b3
refs/heads/main
2023-08-21T16:30:46.781068
2023-08-20T00:39:44
2023-08-20T00:39:44
66,166,069
3,806
1,560
MIT
2023-09-14T19:23:51
2016-08-20T20:10:40
C
UTF-8
C
false
false
6,713
c
ScanEntry.c
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2019 Dan Halbert for Adafruit Industries * Copyright (c) 2018 Artur Pacholec * Copyright (c) 2017 Glenn Ruben Bakke * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <string.h> #include "py/objproperty.h" #include "py/runtime.h" #include "shared-bindings/_bleio/Address.h" #include "shared-bindings/_bleio/ScanEntry.h" #include "shared-bindings/_bleio/UUID.h" #include "shared-module/_bleio/ScanEntry.h" //| class ScanEntry: //| """Encapsulates information about a device that was received during scanning. It can be //| advertisement or scan response data. This object may only be created by a `_bleio.ScanResults`: //| it has no user-visible constructor.""" //| //| def __init__(self) -> None: //| """Cannot be instantiated directly. Use `_bleio.Adapter.start_scan`.""" //| ... //| def matches(self, prefixes: ScanEntry, *, match_all: bool = True) -> bool: //| """Returns True if the ScanEntry matches all prefixes when ``match_all`` is True. This is stricter //| than the scan filtering which accepts any advertisements that match any of the prefixes //| where ``match_all`` is False.""" //| ... STATIC mp_obj_t bleio_scanentry_matches(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { bleio_scanentry_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); enum { ARG_prefixes, ARG_match_all }; static const mp_arg_t allowed_args[] = { { MP_QSTR_prefixes, MP_ARG_OBJ | MP_ARG_REQUIRED }, { MP_QSTR_match_all, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); bool match_all = args[ARG_match_all].u_bool; mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[ARG_prefixes].u_obj, &bufinfo, MP_BUFFER_READ); return mp_obj_new_bool(common_hal_bleio_scanentry_matches(self, bufinfo.buf, bufinfo.len, match_all)); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(bleio_scanentry_matches_obj, 1, bleio_scanentry_matches); //| address: Address //| """The address of the device (read-only), of type `_bleio.Address`.""" STATIC mp_obj_t bleio_scanentry_get_address(mp_obj_t self_in) { bleio_scanentry_obj_t *self = MP_OBJ_TO_PTR(self_in); return common_hal_bleio_scanentry_get_address(self); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(bleio_scanentry_get_address_obj, bleio_scanentry_get_address); MP_PROPERTY_GETTER(bleio_scanentry_address_obj, (mp_obj_t)&bleio_scanentry_get_address_obj); //| advertisement_bytes: bytes //| """All the advertisement data present in the packet, returned as a ``bytes`` object. (read-only)""" STATIC mp_obj_t scanentry_get_advertisement_bytes(mp_obj_t self_in) { bleio_scanentry_obj_t *self = MP_OBJ_TO_PTR(self_in); return common_hal_bleio_scanentry_get_advertisement_bytes(self); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(bleio_scanentry_get_advertisement_bytes_obj, scanentry_get_advertisement_bytes); MP_PROPERTY_GETTER(bleio_scanentry_advertisement_bytes_obj, (mp_obj_t)&bleio_scanentry_get_advertisement_bytes_obj); //| rssi: int //| """The signal strength of the device at the time of the scan, in integer dBm. (read-only)""" STATIC mp_obj_t scanentry_get_rssi(mp_obj_t self_in) { bleio_scanentry_obj_t *self = MP_OBJ_TO_PTR(self_in); return mp_obj_new_int(common_hal_bleio_scanentry_get_rssi(self)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(bleio_scanentry_get_rssi_obj, scanentry_get_rssi); MP_PROPERTY_GETTER(bleio_scanentry_rssi_obj, (mp_obj_t)&bleio_scanentry_get_rssi_obj); //| connectable: bool //| """True if the device can be connected to. (read-only)""" STATIC mp_obj_t scanentry_get_connectable(mp_obj_t self_in) { bleio_scanentry_obj_t *self = MP_OBJ_TO_PTR(self_in); return mp_obj_new_bool(common_hal_bleio_scanentry_get_connectable(self)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(bleio_scanentry_get_connectable_obj, scanentry_get_connectable); MP_PROPERTY_GETTER(bleio_scanentry_connectable_obj, (mp_obj_t)&bleio_scanentry_get_connectable_obj); //| scan_response: bool //| """True if the entry was a scan response. (read-only)""" //| STATIC mp_obj_t scanentry_get_scan_response(mp_obj_t self_in) { bleio_scanentry_obj_t *self = MP_OBJ_TO_PTR(self_in); return mp_obj_new_bool(common_hal_bleio_scanentry_get_scan_response(self)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(bleio_scanentry_get_scan_response_obj, scanentry_get_scan_response); MP_PROPERTY_GETTER(bleio_scanentry_scan_response_obj, (mp_obj_t)&bleio_scanentry_get_scan_response_obj); STATIC const mp_rom_map_elem_t bleio_scanentry_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_address), MP_ROM_PTR(&bleio_scanentry_address_obj) }, { MP_ROM_QSTR(MP_QSTR_advertisement_bytes), MP_ROM_PTR(&bleio_scanentry_advertisement_bytes_obj) }, { MP_ROM_QSTR(MP_QSTR_rssi), MP_ROM_PTR(&bleio_scanentry_rssi_obj) }, { MP_ROM_QSTR(MP_QSTR_connectable), MP_ROM_PTR(&bleio_scanentry_connectable_obj) }, { MP_ROM_QSTR(MP_QSTR_scan_response), MP_ROM_PTR(&bleio_scanentry_scan_response_obj) }, { MP_ROM_QSTR(MP_QSTR_matches), MP_ROM_PTR(&bleio_scanentry_matches_obj) }, }; STATIC MP_DEFINE_CONST_DICT(bleio_scanentry_locals_dict, bleio_scanentry_locals_dict_table); const mp_obj_type_t bleio_scanentry_type = { { &mp_type_type }, .name = MP_QSTR_ScanEntry, .locals_dict = (mp_obj_dict_t *)&bleio_scanentry_locals_dict };
7d1b2adcef2b7009128ae91458009ec23d6f11d0
342983ac4a4ddc27ffa33d48eae37bdd6237c618
/sta/sync.c
862b87b2503c732f54f15173e431238ae62d1216
[ "MIT" ]
permissive
chenhaiq/mt7610u_wifi_sta_v3002_dpo_20130916
9bbba99ecc921ce54e79038495a79b2df848956b
092d218723b8d50816b3bfb377675f5658a8ac4a
refs/heads/master
2022-08-10T15:47:25.607687
2017-08-18T16:37:02
2021-01-05T05:29:30
30,166,779
156
87
MIT
2022-07-27T03:52:36
2015-02-02T01:50:46
C
UTF-8
C
false
false
99,751
c
sync.c
/* ************************************************************************* * Ralink Tech Inc. * 5F., No.36, Taiyuan St., Jhubei City, * Hsinchu County 302, * Taiwan, R.O.C. * * (c) Copyright 2002-2010, Ralink Technology, 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. * * * *************************************************************************/ #include "rt_config.h" #define ADHOC_ENTRY_BEACON_LOST_TIME (2*OS_HZ) /* 2 sec */ /* ========================================================================== Description: The sync state machine, Parameters: Sm - pointer to the state machine Note: the state machine looks like the following ========================================================================== */ VOID SyncStateMachineInit( IN PRTMP_ADAPTER pAd, IN STATE_MACHINE *Sm, OUT STATE_MACHINE_FUNC Trans[]) { StateMachineInit(Sm, Trans, MAX_SYNC_STATE, MAX_SYNC_MSG, (STATE_MACHINE_FUNC)Drop, SYNC_IDLE, SYNC_MACHINE_BASE); /* column 1 */ StateMachineSetAction(Sm, SYNC_IDLE, MT2_MLME_SCAN_REQ, (STATE_MACHINE_FUNC)MlmeScanReqAction); StateMachineSetAction(Sm, SYNC_IDLE, MT2_MLME_FORCE_SCAN_REQ, (STATE_MACHINE_FUNC)MlmeForceScanReqAction); StateMachineSetAction(Sm, SYNC_IDLE, MT2_MLME_JOIN_REQ, (STATE_MACHINE_FUNC)MlmeJoinReqAction); StateMachineSetAction(Sm, SYNC_IDLE, MT2_MLME_FORCE_JOIN_REQ, (STATE_MACHINE_FUNC)MlmeForceJoinReqAction); StateMachineSetAction(Sm, SYNC_IDLE, MT2_MLME_START_REQ, (STATE_MACHINE_FUNC)MlmeStartReqAction); StateMachineSetAction(Sm, SYNC_IDLE, MT2_PEER_BEACON, (STATE_MACHINE_FUNC)PeerBeacon); StateMachineSetAction(Sm, SYNC_IDLE, MT2_PEER_PROBE_REQ, (STATE_MACHINE_FUNC)PeerProbeReqAction); /* column 2 */ StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_MLME_JOIN_REQ, (STATE_MACHINE_FUNC)MlmeJoinReqAction); StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_MLME_START_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenStart); StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_PEER_BEACON, (STATE_MACHINE_FUNC)PeerBeaconAtJoinAction); StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_BEACON_TIMEOUT, (STATE_MACHINE_FUNC)BeaconTimeoutAtJoinAction); StateMachineSetAction(Sm, JOIN_WAIT_BEACON, MT2_PEER_PROBE_RSP, (STATE_MACHINE_FUNC)PeerBeaconAtScanAction); /* column 3 */ StateMachineSetAction(Sm, SCAN_LISTEN, MT2_MLME_JOIN_REQ, (STATE_MACHINE_FUNC)MlmeJoinReqAction); StateMachineSetAction(Sm, SCAN_LISTEN, MT2_MLME_START_REQ, (STATE_MACHINE_FUNC)InvalidStateWhenStart); StateMachineSetAction(Sm, SCAN_LISTEN, MT2_PEER_BEACON, (STATE_MACHINE_FUNC)PeerBeaconAtScanAction); StateMachineSetAction(Sm, SCAN_LISTEN, MT2_PEER_PROBE_RSP, (STATE_MACHINE_FUNC)PeerBeaconAtScanAction); StateMachineSetAction(Sm, SCAN_LISTEN, MT2_SCAN_TIMEOUT, (STATE_MACHINE_FUNC)ScanTimeoutAction); /* StateMachineSetAction(Sm, SCAN_LISTEN, MT2_MLME_SCAN_CNCL, (STATE_MACHINE_FUNC)ScanCnclAction); */ /* resume scanning for fast-roaming */ StateMachineSetAction(Sm, SCAN_PENDING, MT2_MLME_SCAN_REQ, (STATE_MACHINE_FUNC)MlmeScanReqAction); StateMachineSetAction(Sm, SCAN_PENDING, MT2_PEER_BEACON, (STATE_MACHINE_FUNC)PeerBeacon); /* timer init */ RTMPInitTimer(pAd, &pAd->MlmeAux.BeaconTimer, GET_TIMER_FUNCTION(BeaconTimeout), pAd, FALSE); RTMPInitTimer(pAd, &pAd->MlmeAux.ScanTimer, GET_TIMER_FUNCTION(ScanTimeout), pAd, FALSE); } /* ========================================================================== Description: Beacon timeout handler, executed in timer thread IRQL = DISPATCH_LEVEL ========================================================================== */ VOID BeaconTimeout( IN PVOID SystemSpecific1, IN PVOID FunctionContext, IN PVOID SystemSpecific2, IN PVOID SystemSpecific3) { RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext; DBGPRINT(RT_DEBUG_TRACE,("SYNC - BeaconTimeout\n")); /* Do nothing if the driver is starting halt state. This might happen when timer already been fired before cancel timer with mlmehalt */ if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) return; #ifdef DOT11_N_SUPPORT if ((pAd->CommonCfg.BBPCurrentBW == BW_40) ) { rtmp_bbp_set_bw(pAd, BW_40); AsicSwitchChannel(pAd, pAd->CommonCfg.CentralChannel, FALSE); AsicLockChannel(pAd, pAd->CommonCfg.CentralChannel); DBGPRINT(RT_DEBUG_TRACE, ("SYNC - End of SCAN, restore to 40MHz channel %d, Total BSS[%02d]\n", pAd->CommonCfg.CentralChannel, pAd->ScanTab.BssNr)); } #endif /* DOT11_N_SUPPORT */ MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_BEACON_TIMEOUT, 0, NULL, 0); RTMP_MLME_HANDLER(pAd); } /* ========================================================================== Description: Scan timeout handler, executed in timer thread IRQL = DISPATCH_LEVEL ========================================================================== */ VOID ScanTimeout( IN PVOID SystemSpecific1, IN PVOID FunctionContext, IN PVOID SystemSpecific2, IN PVOID SystemSpecific3) { RTMP_ADAPTER *pAd = (RTMP_ADAPTER *)FunctionContext; /* Do nothing if the driver is starting halt state. This might happen when timer already been fired before cancel timer with mlmehalt */ if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS)) return; if (MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_SCAN_TIMEOUT, 0, NULL, 0)) { RTMP_MLME_HANDLER(pAd); } else { /* To prevent SyncMachine.CurrState is SCAN_LISTEN forever. */ pAd->MlmeAux.Channel = 0; ScanNextChannel(pAd, OPMODE_STA); RTMPSendWirelessEvent(pAd, IW_SCAN_ENQUEUE_FAIL_EVENT_FLAG, NULL, BSS0, 0); } } VOID MlmeForceJoinReqAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { BOOLEAN TimerCancelled; HEADER_802_11 Hdr80211; NDIS_STATUS NStatus; ULONG FrameLen = 0; PUCHAR pOutBuffer = NULL; PUCHAR pSupRate = NULL; UCHAR SupRateLen; PUCHAR pExtRate = NULL; UCHAR ExtRateLen; UCHAR ASupRate[] = {0x8C, 0x12, 0x98, 0x24, 0xb0, 0x48, 0x60, 0x6C}; UCHAR ASupRateLen = sizeof(ASupRate)/sizeof(UCHAR); MLME_JOIN_REQ_STRUCT *pInfo = (MLME_JOIN_REQ_STRUCT *)(Elem->Msg); #ifdef CONFIG_PM #ifdef USB_SUPPORT_SELECTIVE_SUSPEND POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie; #endif /* USB_SUPPORT_SELECTIVE_SUSPEND */ #endif /* CONFIG_PM */ DBGPRINT(RT_DEBUG_TRACE, ("SYNC - MlmeForeJoinReqAction(BSS #%ld)\n", pInfo->BssIdx)); #ifdef CONFIG_PM #ifdef USB_SUPPORT_SELECTIVE_SUSPEND if ( (RTMP_Usb_AutoPM_Get_Interface(pObj->pUsb_Dev,pObj->intf)) == 1) { DBGPRINT(RT_DEBUG_TRACE, ("MlmeJoinReqAction: autopm_resume success\n")); RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_SUSPEND); } else if ((RTMP_Usb_AutoPM_Get_Interface(pObj->pUsb_Dev,pObj->intf)) == (-1)) { DBGPRINT(RT_DEBUG_ERROR, ("MlmeJoinReqAction autopm_resume fail ------\n")); RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_SUSPEND); return; } else DBGPRINT(RT_DEBUG_TRACE, ("MlmeJoinReqAction: autopm_resume do nothing \n")); #endif /* USB_SUPPORT_SELECTIVE_SUSPEND */ #endif /* CONFIG_PM */ #ifdef PCIE_PS_SUPPORT if ((OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE)) && (IDLE_ON(pAd)) && (pAd->StaCfg.bRadio == TRUE) && (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_IDLE_RADIO_OFF))) { RT28xxPciAsicRadioOn(pAd, GUI_IDLE_POWER_SAVE); } #endif /* PCIE_PS_SUPPORT */ /* reset all the timers */ RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &TimerCancelled); RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled); { RTMPZeroMemory(pAd->MlmeAux.Ssid, MAX_LEN_OF_SSID); NdisMoveMemory(pAd->MlmeAux.Ssid, pAd->StaCfg.ConnectinfoSsid, pAd->StaCfg.ConnectinfoSsidLen); pAd->MlmeAux.SsidLen = pAd->StaCfg.ConnectinfoSsidLen; } pAd->MlmeAux.BssType = pAd->StaCfg.ConnectinfoBssType; pAd->MlmeAux.Channel = pAd->StaCfg.ConnectinfoChannel; /* Let BBP register at 20MHz to do scan */ AsicSetChannel(pAd, pAd->MlmeAux.Channel, BW_20, EXTCHA_NONE, FALSE); DBGPRINT(RT_DEBUG_TRACE, ("SYNC - BBP R4 to 20MHz.l\n")); RTMPSetTimer(&pAd->MlmeAux.BeaconTimer, JOIN_TIMEOUT); do { /* send probe request */ NStatus = MlmeAllocateMemory(pAd, &pOutBuffer); if (NStatus == NDIS_STATUS_SUCCESS) { if (pAd->MlmeAux.Channel <= 14) { pSupRate = pAd->CommonCfg.SupRate; SupRateLen = pAd->CommonCfg.SupRateLen; pExtRate = pAd->CommonCfg.ExtRate; ExtRateLen = pAd->CommonCfg.ExtRateLen; } else { /* Overwrite Support Rate, CCK rate are not allowed */ pSupRate = ASupRate; SupRateLen = ASupRateLen; ExtRateLen = 0; } if ((pAd->MlmeAux.BssType == BSS_INFRA) && (!MAC_ADDR_EQUAL(ZERO_MAC_ADDR, pAd->StaCfg.ConnectinfoBssid))) { COPY_MAC_ADDR(pAd->MlmeAux.Bssid, pAd->StaCfg.ConnectinfoBssid); MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, pAd->MlmeAux.Bssid, pAd->MlmeAux.Bssid); } else MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, BROADCAST_ADDR, BROADCAST_ADDR); MakeOutgoingFrame(pOutBuffer, &FrameLen, sizeof(HEADER_802_11), &Hdr80211, 1, &SsidIe, 1, &pAd->MlmeAux.SsidLen, pAd->MlmeAux.SsidLen, pAd->MlmeAux.Ssid, 1, &SupRateIe, 1, &SupRateLen, SupRateLen, pSupRate, END_OF_ARGS); if (ExtRateLen) { ULONG Tmp; MakeOutgoingFrame(pOutBuffer + FrameLen, &Tmp, 1, &ExtRateIe, 1, &ExtRateLen, ExtRateLen, pExtRate, END_OF_ARGS); FrameLen += Tmp; } #ifdef WPA_SUPPLICANT_SUPPORT if ((pAd->OpMode == OPMODE_STA) && (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE) && (pAd->StaCfg.WpsProbeReqIeLen != 0)) { ULONG WpsTmpLen = 0; MakeOutgoingFrame(pOutBuffer + FrameLen, &WpsTmpLen, pAd->StaCfg.WpsProbeReqIeLen, pAd->StaCfg.pWpsProbeReqIe, END_OF_ARGS); FrameLen += WpsTmpLen; } #endif /* WPA_SUPPLICANT_SUPPORT */ #ifdef WFD_SUPPORT #ifdef RT_CFG80211_SUPPORT if (pAd->StaCfg.WfdCfg.bSuppInsertWfdIe) { ULONG WfdIeLen, WfdIeBitmap; PUCHAR ptr; ptr = pOutBuffer + FrameLen; WfdIeBitmap = (0x1 << SUBID_WFD_DEVICE_INFO) | (0x1 << SUBID_WFD_ASSOCIATED_BSSID) | (0x1 << SUBID_WFD_COUPLED_SINK_INFO); WfdMakeWfdIE(pAd, WfdIeBitmap, ptr, &WfdIeLen); FrameLen += WfdIeLen; } #endif /* RT_CFG80211_SUPPORT */ #endif /* WFD_SUPPORT */ MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen); MlmeFreeMemory(pAd, pOutBuffer); } } while (FALSE); DBGPRINT(0, ("FORCE JOIN SYNC - Switch to ch %d, Wait BEACON from %02x:%02x:%02x:%02x:%02x:%02x\n", pAd->StaCfg.ConnectinfoChannel, PRINT_MAC(pAd->StaCfg.ConnectinfoBssid))); pAd->Mlme.SyncMachine.CurrState = JOIN_WAIT_BEACON; } VOID MlmeForceScanReqAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { UCHAR Ssid[MAX_LEN_OF_SSID], SsidLen, ScanType, BssType; BOOLEAN TimerCancelled; ULONG Now; USHORT Status; #ifdef RTMP_MAC_USB if(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_IDLE_RADIO_OFF)) ASIC_RADIO_ON(pAd, MLME_RADIO_ON); #endif /* RTMP_MAC_USB */ /* Check the total scan tries for one single OID command If this is the CCX 2.0 Case, skip that! */ if ( !RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_START_UP)) { DBGPRINT(RT_DEBUG_TRACE, ("SYNC - MlmeForceScanReqAction before Startup\n")); return; } /* first check the parameter sanity */ if (MlmeScanReqSanity(pAd, Elem->Msg, Elem->MsgLen, &BssType, (PCHAR)Ssid, &SsidLen, &ScanType)) { /* Check for channel load and noise hist request Suspend MSDU only at scan request, not the last two mentioned Suspend MSDU transmission here */ RTMPSuspendMsduTransmission(pAd); /* To prevent data lost. Send an NULL data with turned PSM bit on to current associated AP before SCAN progress. And should send an NULL data with turned PSM bit off to AP, when scan progress done */ if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) && (INFRA_ON(pAd))) { RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) ? TRUE:FALSE), PWR_SAVE); DBGPRINT(RT_DEBUG_TRACE, ("MlmeForceScanReqAction -- Send PSM Data frame for off channel RM, SCAN_IN_PROGRESS=%d!\n", RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))); OS_WAIT(20); } RTMPSendWirelessEvent(pAd, IW_SCANNING_EVENT_FLAG, NULL, BSS0, 0); NdisGetSystemUpTime(&Now); pAd->StaCfg.LastScanTime = Now; /* reset all the timers */ RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled); RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &TimerCancelled); /* record desired BSS parameters */ pAd->MlmeAux.BssType = BssType; pAd->MlmeAux.ScanType = ScanType; pAd->MlmeAux.SsidLen = SsidLen; NdisZeroMemory(pAd->MlmeAux.Ssid, MAX_LEN_OF_SSID); NdisMoveMemory(pAd->MlmeAux.Ssid, Ssid, SsidLen); /* Scanning was pending (for fast scanning) */ if ((pAd->StaCfg.bImprovedScan) && (pAd->Mlme.SyncMachine.CurrState == SCAN_PENDING)) { pAd->MlmeAux.Channel = pAd->StaCfg.LastScanChannel; } else { if (pAd->StaCfg.bFastConnect && (pAd->CommonCfg.Channel != 0) && !pAd->StaCfg.bNotFirstScan) { pAd->MlmeAux.Channel = pAd->CommonCfg.Channel; } else /* start from the first channel */ pAd->MlmeAux.Channel = FirstChannel(pAd); } /* Let BBP register at 20MHz to do scan */ rtmp_bbp_set_bw(pAd, BW_20); DBGPRINT(RT_DEBUG_TRACE, ("SYNC - BBP R4 to 20MHz.l\n")); #ifdef DOT11_N_SUPPORT #ifdef DOT11N_DRAFT3 /* Before scan, reset trigger event table. */ TriEventInit(pAd); #endif /* DOT11N_DRAFT3 */ #endif /* DOT11_N_SUPPORT */ ScanNextChannel(pAd, OPMODE_STA); if(pAd->StaCfg.ConnectinfoChannel != 0) pAd->MlmeAux.Channel = 0; pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_SCAN_FOR_CONNECT; } else { DBGPRINT_ERR(("SYNC - MlmeForceScanReqAction() sanity check fail\n")); pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE; Status = MLME_INVALID_FORMAT; MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status, 0); } } /* ========================================================================== Description: MLME SCAN req state machine procedure ========================================================================== */ VOID MlmeScanReqAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { UCHAR Ssid[MAX_LEN_OF_SSID], SsidLen, ScanType, BssType; BOOLEAN TimerCancelled; ULONG Now; USHORT Status; #ifdef RTMP_MAC_USB if(RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_IDLE_RADIO_OFF)) ASIC_RADIO_ON(pAd, MLME_RADIO_ON); #endif /* RTMP_MAC_USB */ /* Check the total scan tries for one single OID command If this is the CCX 2.0 Case, skip that! */ if ( !RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_START_UP)) { DBGPRINT(RT_DEBUG_TRACE, ("SYNC - MlmeScanReqAction before Startup\n")); return; } #ifdef PCIE_PS_SUPPORT if ((OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE)) && (IDLE_ON(pAd)) && (pAd->StaCfg.bRadio == TRUE) && (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_IDLE_RADIO_OFF))) { if (pAd->StaCfg.PSControl.field.EnableNewPS == FALSE) { AsicSendCommandToMcu(pAd, 0x31, PowerWakeCID, 0x00, 0x02, FALSE); AsicCheckCommanOk(pAd, PowerWakeCID); RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_IDLE_RADIO_OFF); DBGPRINT(RT_DEBUG_TRACE, ("PSM - Issue Wake up command \n")); } else { RT28xxPciAsicRadioOn(pAd, GUI_IDLE_POWER_SAVE); } } #endif /* PCIE_PS_SUPPORT */ /* first check the parameter sanity */ if (MlmeScanReqSanity(pAd, Elem->Msg, Elem->MsgLen, &BssType, (PCHAR)Ssid, &SsidLen, &ScanType)) { /* Check for channel load and noise hist request Suspend MSDU only at scan request, not the last two mentioned Suspend MSDU transmission here */ RTMPSuspendMsduTransmission(pAd); /* To prevent data lost. Send an NULL data with turned PSM bit on to current associated AP before SCAN progress. And should send an NULL data with turned PSM bit off to AP, when scan progress done */ if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) && (INFRA_ON(pAd))) { RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) ? TRUE:FALSE), PWR_SAVE); DBGPRINT(RT_DEBUG_TRACE, ("MlmeScanReqAction -- Send PSM Data frame for off channel RM, SCAN_IN_PROGRESS=%d!\n", RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS))); OS_WAIT(20); } RTMPSendWirelessEvent(pAd, IW_SCANNING_EVENT_FLAG, NULL, BSS0, 0); NdisGetSystemUpTime(&Now); pAd->StaCfg.LastScanTime = Now; /* reset all the timers */ RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled); RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &TimerCancelled); /* record desired BSS parameters */ pAd->MlmeAux.BssType = BssType; pAd->MlmeAux.ScanType = ScanType; pAd->MlmeAux.SsidLen = SsidLen; NdisZeroMemory(pAd->MlmeAux.Ssid, MAX_LEN_OF_SSID); NdisMoveMemory(pAd->MlmeAux.Ssid, Ssid, SsidLen); /* Scanning was pending (for fast scanning) */ if ((pAd->StaCfg.bImprovedScan) && (pAd->Mlme.SyncMachine.CurrState == SCAN_PENDING)) { pAd->MlmeAux.Channel = pAd->StaCfg.LastScanChannel; } else { if (pAd->StaCfg.bFastConnect && (pAd->CommonCfg.Channel != 0) && !pAd->StaCfg.bNotFirstScan) { pAd->MlmeAux.Channel = pAd->CommonCfg.Channel; } else { { /* start from the first channel */ pAd->MlmeAux.Channel = FirstChannel(pAd); } } } /* Let BBP register at 20MHz to do scan */ rtmp_bbp_set_bw(pAd, BW_20); DBGPRINT(RT_DEBUG_TRACE, ("SYNC - BBP R4 to 20MHz.l\n")); #ifdef DOT11_N_SUPPORT #ifdef DOT11N_DRAFT3 /* Before scan, reset trigger event table. */ TriEventInit(pAd); #endif /* DOT11N_DRAFT3 */ #endif /* DOT11_N_SUPPORT */ ScanNextChannel(pAd, OPMODE_STA); } else { DBGPRINT_ERR(("SYNC - MlmeScanReqAction() sanity check fail\n")); pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE; Status = MLME_INVALID_FORMAT; MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status, 0); } } /* ========================================================================== Description: MLME JOIN req state machine procedure ========================================================================== */ VOID MlmeJoinReqAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { BSS_ENTRY *pBss; BOOLEAN TimerCancelled; HEADER_802_11 Hdr80211; NDIS_STATUS NStatus; ULONG FrameLen = 0; PUCHAR pOutBuffer = NULL; PUCHAR pSupRate = NULL; UCHAR SupRateLen; PUCHAR pExtRate = NULL; UCHAR ExtRateLen; UCHAR ASupRate[] = {0x8C, 0x12, 0x98, 0x24, 0xb0, 0x48, 0x60, 0x6C}; UCHAR ASupRateLen = sizeof(ASupRate)/sizeof(UCHAR); MLME_JOIN_REQ_STRUCT *pInfo = (MLME_JOIN_REQ_STRUCT *)(Elem->Msg); #ifdef CONFIG_PM #ifdef USB_SUPPORT_SELECTIVE_SUSPEND POS_COOKIE pObj = (POS_COOKIE) pAd->OS_Cookie; #endif /* USB_SUPPORT_SELECTIVE_SUSPEND */ #endif /* CONFIG_PM */ BOOLEAN bChangeInitBW = FALSE; DBGPRINT(RT_DEBUG_TRACE, ("SYNC - MlmeJoinReqAction(BSS #%ld)\n", pInfo->BssIdx)); #ifdef CONFIG_PM #ifdef USB_SUPPORT_SELECTIVE_SUSPEND if ( (RTMP_Usb_AutoPM_Get_Interface(pObj->pUsb_Dev,pObj->intf)) == 1) { DBGPRINT(RT_DEBUG_TRACE, ("MlmeJoinReqAction: autopm_resume success\n")); RTMP_CLEAR_FLAG(pAd, fRTMP_ADAPTER_SUSPEND); } else if ((RTMP_Usb_AutoPM_Get_Interface(pObj->pUsb_Dev,pObj->intf)) == (-1)) { DBGPRINT(RT_DEBUG_ERROR, ("MlmeJoinReqAction autopm_resume fail ------\n")); RTMP_SET_FLAG(pAd, fRTMP_ADAPTER_SUSPEND); return; } else DBGPRINT(RT_DEBUG_TRACE, ("MlmeJoinReqAction: autopm_resume do nothing \n")); #endif /* USB_SUPPORT_SELECTIVE_SUSPEND */ #endif /* CONFIG_PM */ #ifdef PCIE_PS_SUPPORT if ((OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE)) && (IDLE_ON(pAd)) && (pAd->StaCfg.bRadio == TRUE) && (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_IDLE_RADIO_OFF))) { RT28xxPciAsicRadioOn(pAd, GUI_IDLE_POWER_SAVE); } #endif /* PCIE_PS_SUPPORT */ /* reset all the timers */ RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &TimerCancelled); RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled); pBss = &pAd->MlmeAux.SsidBssTab.BssEntry[pInfo->BssIdx]; /* record the desired SSID & BSSID we're waiting for */ COPY_MAC_ADDR(pAd->MlmeAux.Bssid, pBss->Bssid); /* If AP's SSID is not hidden, it is OK for updating ssid to MlmeAux again. */ if (pBss->Hidden == 0) { RTMPZeroMemory(pAd->MlmeAux.Ssid, MAX_LEN_OF_SSID); NdisMoveMemory(pAd->MlmeAux.Ssid, pBss->Ssid, pBss->SsidLen); pAd->MlmeAux.SsidLen = pBss->SsidLen; } pAd->MlmeAux.BssType = pBss->BssType; pAd->MlmeAux.Channel = pBss->Channel; pAd->MlmeAux.CentralChannel = pBss->CentralChannel; #ifdef EXT_BUILD_CHANNEL_LIST /* Country IE of the AP will be evaluated and will be used. */ if ((pAd->StaCfg.IEEE80211dClientMode != Rt802_11_D_None) && (pBss->bHasCountryIE == TRUE)) { NdisMoveMemory(&pAd->CommonCfg.CountryCode[0], &pBss->CountryString[0], 2); if (pBss->CountryString[2] == 'I') pAd->CommonCfg.Geography = IDOR; else if (pBss->CountryString[2] == 'O') pAd->CommonCfg.Geography = ODOR; else pAd->CommonCfg.Geography = BOTH; BuildChannelListEx(pAd); } #endif /* EXT_BUILD_CHANNEL_LIST */ { bChangeInitBW = TRUE; } if (bChangeInitBW == TRUE) { /* Let BBP register at 20MHz to do scan */ rtmp_bbp_set_bw(pAd, BW_20); DBGPRINT(RT_DEBUG_TRACE, ("%s(): Set BBP BW=20MHz\n", __FUNCTION__)); /* switch channel and waiting for beacon timer */ AsicSwitchChannel(pAd, pAd->MlmeAux.Channel, FALSE); AsicLockChannel(pAd, pAd->MlmeAux.Channel); } RTMPSetTimer(&pAd->MlmeAux.BeaconTimer, JOIN_TIMEOUT); do { if (((pAd->CommonCfg.bIEEE80211H == 1) && (pAd->MlmeAux.Channel > 14) && RadarChannelCheck(pAd, pAd->MlmeAux.Channel)) #ifdef CARRIER_DETECTION_SUPPORT /* Roger sync Carrier */ || (pAd->CommonCfg.CarrierDetect.Enable == TRUE) #endif /* CARRIER_DETECTION_SUPPORT */ ) { /* We can't send any Probe request frame to meet 802.11h. */ if (pBss->Hidden == 0) break; } /* send probe request */ NStatus = MlmeAllocateMemory(pAd, &pOutBuffer); if (NStatus == NDIS_STATUS_SUCCESS) { if (pAd->MlmeAux.Channel <= 14) { pSupRate = pAd->CommonCfg.SupRate; SupRateLen = pAd->CommonCfg.SupRateLen; pExtRate = pAd->CommonCfg.ExtRate; ExtRateLen = pAd->CommonCfg.ExtRateLen; } else { /* Overwrite Support Rate, CCK rate are not allowed */ pSupRate = ASupRate; SupRateLen = ASupRateLen; ExtRateLen = 0; } if (pAd->MlmeAux.BssType == BSS_INFRA) MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, pAd->MlmeAux.Bssid, pAd->MlmeAux.Bssid); else MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, BROADCAST_ADDR, BROADCAST_ADDR); MakeOutgoingFrame(pOutBuffer, &FrameLen, sizeof(HEADER_802_11), &Hdr80211, 1, &SsidIe, 1, &pAd->MlmeAux.SsidLen, pAd->MlmeAux.SsidLen, pAd->MlmeAux.Ssid, 1, &SupRateIe, 1, &SupRateLen, SupRateLen, pSupRate, END_OF_ARGS); if (ExtRateLen) { ULONG Tmp; MakeOutgoingFrame(pOutBuffer + FrameLen, &Tmp, 1, &ExtRateIe, 1, &ExtRateLen, ExtRateLen, pExtRate, END_OF_ARGS); FrameLen += Tmp; } #ifdef WPA_SUPPLICANT_SUPPORT if ((pAd->OpMode == OPMODE_STA) && (pAd->StaCfg.WpaSupplicantUP != WPA_SUPPLICANT_DISABLE) && (pAd->StaCfg.WpsProbeReqIeLen != 0)) { ULONG WpsTmpLen = 0; MakeOutgoingFrame(pOutBuffer + FrameLen, &WpsTmpLen, pAd->StaCfg.WpsProbeReqIeLen, pAd->StaCfg.pWpsProbeReqIe, END_OF_ARGS); FrameLen += WpsTmpLen; } #endif /* WPA_SUPPLICANT_SUPPORT */ #ifdef WFD_SUPPORT #ifdef RT_CFG80211_SUPPORT if (pAd->StaCfg.WfdCfg.bSuppInsertWfdIe) { ULONG WfdIeLen, WfdIeBitmap; PUCHAR ptr; ptr = pOutBuffer + FrameLen; WfdIeBitmap = (0x1 << SUBID_WFD_DEVICE_INFO) | (0x1 << SUBID_WFD_ASSOCIATED_BSSID) | (0x1 << SUBID_WFD_COUPLED_SINK_INFO); WfdMakeWfdIE(pAd, WfdIeBitmap, ptr, &WfdIeLen); FrameLen += WfdIeLen; } #endif /* RT_CFG80211_SUPPORT */ #endif /* WFD_SUPPORT */ MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen); MlmeFreeMemory(pAd, pOutBuffer); } } while (FALSE); DBGPRINT(RT_DEBUG_TRACE, ("SYNC - Switch to ch %d, Wait BEACON from %02x:%02x:%02x:%02x:%02x:%02x\n", pBss->Channel, pBss->Bssid[0], pBss->Bssid[1], pBss->Bssid[2], pBss->Bssid[3], pBss->Bssid[4], pBss->Bssid[5])); pAd->Mlme.SyncMachine.CurrState = JOIN_WAIT_BEACON; } /* ========================================================================== Description: MLME START Request state machine procedure, starting an IBSS ========================================================================== */ VOID MlmeStartReqAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { UCHAR Ssid[MAX_LEN_OF_SSID], SsidLen; BOOLEAN TimerCancelled; UCHAR *VarIE = NULL; /* New for WPA security suites */ NDIS_802_11_VARIABLE_IEs *pVIE = NULL; LARGE_INTEGER TimeStamp; BOOLEAN Privacy; USHORT Status; /* allocate memory */ os_alloc_mem(NULL, (UCHAR **)&VarIE, MAX_VIE_LEN); if (VarIE == NULL) { DBGPRINT(RT_DEBUG_ERROR, ("%s: Allocate memory fail!!!\n", __FUNCTION__)); return; } /* Init Variable IE structure */ pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE; pVIE->Length = 0; TimeStamp.u.LowPart = 0; TimeStamp.u.HighPart = 0; if ((MlmeStartReqSanity(pAd, Elem->Msg, Elem->MsgLen, (PCHAR)Ssid, &SsidLen)) && (CHAN_PropertyCheck(pAd, pAd->MlmeAux.Channel, CHANNEL_NO_IBSS) == FALSE)) { /* reset all the timers */ RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &TimerCancelled); RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled); /* Start a new IBSS. All IBSS parameters are decided now */ DBGPRINT(RT_DEBUG_TRACE, ("MlmeStartReqAction - Start a new IBSS. All IBSS parameters are decided now.... \n")); pAd->MlmeAux.BssType = BSS_ADHOC; NdisMoveMemory(pAd->MlmeAux.Ssid, Ssid, SsidLen); pAd->MlmeAux.SsidLen = SsidLen; { /* generate a radom number as BSSID */ MacAddrRandomBssid(pAd, pAd->MlmeAux.Bssid); DBGPRINT(RT_DEBUG_TRACE, ("MlmeStartReqAction - generate a radom number as BSSID \n")); } Privacy = (pAd->StaCfg.WepStatus == Ndis802_11Encryption1Enabled) || (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) || (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled); pAd->MlmeAux.CapabilityInfo = CAP_GENERATE(0,1,Privacy, (pAd->CommonCfg.TxPreamble == Rt802_11PreambleShort), 1, 0); pAd->MlmeAux.BeaconPeriod = pAd->CommonCfg.BeaconPeriod; pAd->MlmeAux.AtimWin = pAd->StaCfg.AtimWin; pAd->MlmeAux.Channel = pAd->CommonCfg.Channel; pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel; pAd->MlmeAux.CentralChannel = pAd->CommonCfg.CentralChannel; pAd->MlmeAux.SupRateLen= pAd->CommonCfg.SupRateLen; NdisMoveMemory(pAd->MlmeAux.SupRate, pAd->CommonCfg.SupRate, MAX_LEN_OF_SUPPORTED_RATES); RTMPCheckRates(pAd, pAd->MlmeAux.SupRate, &pAd->MlmeAux.SupRateLen); pAd->MlmeAux.ExtRateLen = pAd->CommonCfg.ExtRateLen; NdisMoveMemory(pAd->MlmeAux.ExtRate, pAd->CommonCfg.ExtRate, MAX_LEN_OF_SUPPORTED_RATES); RTMPCheckRates(pAd, pAd->MlmeAux.ExtRate, &pAd->MlmeAux.ExtRateLen); #ifdef DOT11_N_SUPPORT if (WMODE_CAP_N(pAd->CommonCfg.PhyMode) && (pAd->StaCfg.bAdhocN == TRUE)) { RTMPUpdateHTIE(&pAd->CommonCfg.DesiredHtPhy, &pAd->StaCfg.DesiredHtPhyInfo.MCSSet[0], &pAd->MlmeAux.HtCapability, &pAd->MlmeAux.AddHtInfo); pAd->MlmeAux.HtCapabilityLen = sizeof(HT_CAPABILITY_IE); /* Not turn pAd->StaActive.SupportedHtPhy.bHtEnable = TRUE here. */ DBGPRINT(RT_DEBUG_TRACE, ("SYNC -pAd->StaActive.SupportedHtPhy.bHtEnable = TRUE\n")); #ifdef DOT11_VHT_AC if (WMODE_CAP_AC(pAd->CommonCfg.PhyMode) && (pAd->MlmeAux.Channel > 14)) { build_vht_cap_ie(pAd, (UCHAR *)&pAd->MlmeAux.vht_cap); pAd->MlmeAux.vht_cap_len = sizeof(VHT_CAP_IE); } #endif /* DOT11_VHT_AC */ } else #endif /* DOT11_N_SUPPORT */ { pAd->MlmeAux.HtCapabilityLen = 0; pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE; NdisZeroMemory(&pAd->StaActive.SupportedPhyInfo.MCSSet[0], 16); } /* temporarily not support QOS in IBSS */ NdisZeroMemory(&pAd->MlmeAux.APEdcaParm, sizeof(EDCA_PARM)); NdisZeroMemory(&pAd->MlmeAux.APQbssLoad, sizeof(QBSS_LOAD_PARM)); NdisZeroMemory(&pAd->MlmeAux.APQosCapability, sizeof(QOS_CAPABILITY_PARM)); AsicSwitchChannel(pAd, pAd->MlmeAux.Channel, FALSE); AsicLockChannel(pAd, pAd->MlmeAux.Channel); DBGPRINT(RT_DEBUG_TRACE, ("SYNC - MlmeStartReqAction(ch= %d,sup rates= %d, ext rates=%d)\n", pAd->MlmeAux.Channel, pAd->MlmeAux.SupRateLen, pAd->MlmeAux.ExtRateLen)); pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE; Status = MLME_SUCCESS; MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_START_CONF, 2, &Status, 0); } else { DBGPRINT_ERR(("SYNC - MlmeStartReqAction() sanity check fail.\n")); pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE; Status = MLME_INVALID_FORMAT; MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_START_CONF, 2, &Status, 0); } if (VarIE != NULL) os_free_mem(NULL, VarIE); } //+++Add by shiang to check correctness of new sanity function VOID rtmp_dbg_sanity_diff(RTMP_ADAPTER *pAd, MLME_QUEUE_ELEM *Elem) { /* Parameters used for old sanity function */ UCHAR Bssid[MAC_ADDR_LEN], Addr2[MAC_ADDR_LEN]; UCHAR *Ssid = NULL; UCHAR SsidLen=0, DtimCount, DtimPeriod, BcastFlag, MessageToMe, NewChannel, Channel = 0, BssType; CF_PARM CfParm = {0}; USHORT BeaconPeriod, AtimWin, CapabilityInfo; LARGE_INTEGER TimeStamp; UCHAR SupRate[MAX_LEN_OF_SUPPORTED_RATES], ExtRate[MAX_LEN_OF_SUPPORTED_RATES]; UCHAR CkipFlag; EDCA_PARM EdcaParm = {0}; UCHAR AironetCellPowerLimit; UCHAR SupRateLen, ExtRateLen; QBSS_LOAD_PARM QbssLoad; QOS_CAPABILITY_PARM QosCapability = {0}; ULONG RalinkIe; UCHAR AddHtInfoLen; EXT_CAP_INFO_ELEMENT ExtCapInfo; HT_CAPABILITY_IE *pHtCapability = NULL; ADD_HT_INFO_IE *pAddHtInfo = NULL; /* AP might use this additional ht info IE */ UCHAR HtCapabilityLen = 0, PreNHtCapabilityLen = 0; UCHAR Erp; UCHAR NewExtChannelOffset = 0xff; USHORT LenVIE; UCHAR *VarIE = NULL; NDIS_802_11_VARIABLE_IEs *pVIE = NULL; BCN_IE_LIST *ie_list = NULL; BOOLEAN sanity_new, sanity_old; /* allocate memory */ os_alloc_mem(NULL, (UCHAR **)&Ssid, MAX_LEN_OF_SSID); if (Ssid == NULL) goto LabelErr; os_alloc_mem(NULL, (UCHAR **)&pHtCapability, sizeof(HT_CAPABILITY_IE)); if (pHtCapability == NULL) goto LabelErr; os_alloc_mem(NULL, (UCHAR **)&pAddHtInfo, sizeof(ADD_HT_INFO_IE)); if (pAddHtInfo == NULL) goto LabelErr; NdisZeroMemory(&QbssLoad, sizeof(QBSS_LOAD_PARM)); /* woody */ #ifdef DOT11_N_SUPPORT RTMPZeroMemory(pHtCapability, sizeof(HT_CAPABILITY_IE)); RTMPZeroMemory(pAddHtInfo, sizeof(ADD_HT_INFO_IE)); #endif /* DOT11_N_SUPPORT */ NdisZeroMemory(Ssid, MAX_LEN_OF_SSID); os_alloc_mem(NULL, (UCHAR **)&ie_list, sizeof(BCN_IE_LIST)); if (ie_list == NULL) goto LabelErr; NdisZeroMemory(ie_list, sizeof(BCN_IE_LIST)); sanity_new = PeerBeaconAndProbeRspSanity(pAd, &Elem->Msg[0], Elem->MsgLen, Elem->Channel, ie_list, &LenVIE, pVIE); sanity_old = PeerBeaconAndProbeRspSanity_Old(pAd, Elem->Msg, Elem->MsgLen, Elem->Channel, Addr2, Bssid, (PCHAR)Ssid, &SsidLen, &BssType, &BeaconPeriod, &Channel, &NewChannel, &TimeStamp, &CfParm, &AtimWin, &CapabilityInfo, &Erp, &DtimCount, &DtimPeriod, &BcastFlag, &MessageToMe, SupRate, &SupRateLen, ExtRate, &ExtRateLen, &CkipFlag, &AironetCellPowerLimit, &EdcaParm, &QbssLoad, &QosCapability, &RalinkIe, &HtCapabilityLen, #ifdef CONFIG_STA_SUPPORT &PreNHtCapabilityLen, #endif /* CONFIG_STA_SUPPORT */ pHtCapability, &ExtCapInfo, &AddHtInfoLen, pAddHtInfo, &NewExtChannelOffset, &LenVIE, pVIE); if (sanity_old != sanity_new) { DBGPRINT(RT_DEBUG_ERROR, ("sanity mismatch, old=%d, new=%d\n", sanity_old, sanity_new)); } else { if (NdisCmpMemory(&ie_list->Addr2[0], &Addr2[0], MAC_ADDR_LEN) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("Add2 mismatch!Old=%02x:%02x:%02x:%02x:%02x:%02x!New=%02x:%02x:%02x:%02x:%02x:%02x!\n", PRINT_MAC(Addr2), PRINT_MAC(ie_list->Addr2))); } if (NdisCmpMemory(&ie_list->Bssid[0], &Bssid[0], MAC_ADDR_LEN) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("Bssid mismatch!Old=%02x:%02x:%02x:%02x:%02x:%02x!New=%02x:%02x:%02x:%02x:%02x:%02x!\n", PRINT_MAC(Bssid), PRINT_MAC(ie_list->Bssid))); } if (SsidLen != ie_list->SsidLen) { DBGPRINT(RT_DEBUG_ERROR, ("SsidLen mismatch!Old=%d, New=%d\n", SsidLen, ie_list->SsidLen)); } if (NdisCmpMemory(&ie_list->Ssid[0], &Ssid[0], SsidLen) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("Ssid mismatch!Old=%s, New=%s\n", Ssid, ie_list->Ssid)); } if (BssType != ie_list->BssType) { DBGPRINT(RT_DEBUG_ERROR, ("BssType mismatch!Old=%d, New=%d\n", BssType, ie_list->BssType)); } if (BeaconPeriod != ie_list->BeaconPeriod) { DBGPRINT(RT_DEBUG_ERROR, ("BeaconPeriod mismatch!Old=%d, New=%d\n", BeaconPeriod, ie_list->BeaconPeriod)); } if (Channel != ie_list->Channel) { DBGPRINT(RT_DEBUG_ERROR, ("Channel mismatch!Old=%d, New=%d\n", Channel, ie_list->Channel)); } if (NewChannel != ie_list->NewChannel) { DBGPRINT(RT_DEBUG_ERROR, ("NewChannel mismatch!Old=%d, New=%d\n", NewChannel, ie_list->NewChannel)); } if (NdisCmpMemory(&ie_list->TimeStamp, &TimeStamp, sizeof(LARGE_INTEGER)) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("TimeStamp mismatch!Old=%d - %d, New=%d - %d\n", TimeStamp.u.LowPart, TimeStamp.u.HighPart, ie_list->TimeStamp.u.LowPart, ie_list->TimeStamp.u.HighPart)); } if (NdisCmpMemory(&ie_list->CfParm, &CfParm, sizeof(CF_PARM)) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("CFParam mismatch!\n")); hex_dump("Old CFParam", (UCHAR *)&CfParm, sizeof(CF_PARM)); hex_dump("New CFParam", (UCHAR *)&ie_list->CfParm, sizeof(CF_PARM)); } if (AtimWin != ie_list->AtimWin) { DBGPRINT(RT_DEBUG_ERROR, ("AtimWin mismatch!Old=%d, New=%d\n", AtimWin, ie_list->AtimWin)); } if (CapabilityInfo != ie_list->CapabilityInfo) { DBGPRINT(RT_DEBUG_ERROR, ("CapabilityInfo mismatch!Old=%d, New=%d\n", CapabilityInfo, ie_list->CapabilityInfo)); } if (Erp != ie_list->Erp) { DBGPRINT(RT_DEBUG_ERROR, ("Erp mismatch!Old=%d, New=%d\n", Erp, ie_list->Erp)); } if (DtimCount != ie_list->DtimCount) { DBGPRINT(RT_DEBUG_ERROR, ("DtimCount mismatch!Old=%d, New=%d\n", DtimCount, ie_list->DtimCount)); } if (DtimPeriod != ie_list->DtimPeriod) { DBGPRINT(RT_DEBUG_ERROR, ("DtimPeriod mismatch!Old=%d, New=%d\n", DtimPeriod, ie_list->DtimPeriod)); } if (BcastFlag != ie_list->BcastFlag) { DBGPRINT(RT_DEBUG_ERROR, ("BcastFlag mismatch!Old=%d, New=%d\n", BcastFlag, ie_list->BcastFlag)); } if (MessageToMe != ie_list->MessageToMe) { DBGPRINT(RT_DEBUG_ERROR, ("MessageToMe mismatch!Old=%d, New=%d\n", MessageToMe, ie_list->MessageToMe)); } if (SupRateLen != ie_list->SupRateLen) { DBGPRINT(RT_DEBUG_ERROR, ("SupRateLen mismatch!Old=%d, New=%d\n", SupRateLen, ie_list->SupRateLen)); } if (NdisCmpMemory(&ie_list->SupRate[0], &SupRate, ie_list->SupRateLen) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("SupRate mismatch!\n")); hex_dump("Old SupRate", (UCHAR *)&SupRate, ie_list->SupRateLen); hex_dump("New SupRate", (UCHAR *)&ie_list->SupRate, ie_list->SupRateLen); } if (ExtRateLen != ie_list->ExtRateLen) { DBGPRINT(RT_DEBUG_ERROR, ("ExtRateLen mismatch!Old=%d, New=%d\n", ExtRateLen, ie_list->ExtRateLen)); } if (NdisCmpMemory(&ie_list->ExtRate[0], &ExtRate, ie_list->ExtRateLen) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("ExtRate mismatch!\n")); hex_dump("Old ExtRate", (UCHAR *)&ExtRate, ie_list->ExtRateLen); hex_dump("New ExtRate", (UCHAR *)&ie_list->ExtRate, ie_list->ExtRateLen); } if (CkipFlag != ie_list->CkipFlag) { DBGPRINT(RT_DEBUG_ERROR, ("CkipFlag mismatch!Old=%d, New=%d\n", CkipFlag, ie_list->CkipFlag)); } if (AironetCellPowerLimit != ie_list->AironetCellPowerLimit) { DBGPRINT(RT_DEBUG_ERROR, ("AironetCellPowerLimit mismatch!Old=%d, New=%d\n", AironetCellPowerLimit, ie_list->AironetCellPowerLimit)); } if (NdisCmpMemory(&ie_list->EdcaParm, &EdcaParm, sizeof(EDCA_PARM)) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("EdcaParm mismatch!\n")); hex_dump("Old EdcaParm", (UCHAR *)&EdcaParm, sizeof(EDCA_PARM)); hex_dump("New EdcaParm", (UCHAR *)&ie_list->EdcaParm, sizeof(EDCA_PARM)); } if (NdisCmpMemory(&ie_list->QbssLoad, &QbssLoad, sizeof(QBSS_LOAD_PARM)) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("QbssLoad mismatch!\n")); hex_dump("Old QbssLoad", (UCHAR *)&QbssLoad, sizeof(QBSS_LOAD_PARM)); hex_dump("New QbssLoad", (UCHAR *)&ie_list->QbssLoad, sizeof(QBSS_LOAD_PARM)); } if (NdisCmpMemory(&ie_list->QosCapability, &QosCapability, sizeof(QOS_CAPABILITY_PARM)) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("QosCapability mismatch!\n")); hex_dump("Old QosCapability", (UCHAR *)&QosCapability, sizeof(QOS_CAPABILITY_PARM)); hex_dump("New QosCapability", (UCHAR *)&ie_list->QosCapability, sizeof(QOS_CAPABILITY_PARM)); } if (RalinkIe != ie_list->RalinkIe) { DBGPRINT(RT_DEBUG_ERROR, ("RalinkIe mismatch!Old=%lx, New=%lx\n", RalinkIe, ie_list->RalinkIe)); } if (HtCapabilityLen != ie_list->HtCapabilityLen) { DBGPRINT(RT_DEBUG_ERROR, ("HtCapabilityLen mismatch!Old=%d, New=%d\n", HtCapabilityLen, ie_list->HtCapabilityLen)); } #ifdef CONFIG_STA_SUPPORT if (PreNHtCapabilityLen != ie_list->PreNHtCapabilityLen) { DBGPRINT(RT_DEBUG_ERROR, ("PreNHtCapabilityLen mismatch!Old=%d, New=%d\n", PreNHtCapabilityLen, ie_list->PreNHtCapabilityLen)); } #endif /* CONFIG_STA_SUPPORT */ if (NdisCmpMemory(&ie_list->HtCapability, pHtCapability, sizeof(HT_CAPABILITY_IE)) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("pHtCapability mismatch!\n")); hex_dump("Old HtCapability", (UCHAR *)pHtCapability, sizeof(HT_CAPABILITY_IE)); hex_dump("New HtCapability", (UCHAR *)&ie_list->HtCapability, sizeof(HT_CAPABILITY_IE)); } if (NdisCmpMemory(&ie_list->ExtCapInfo, &ExtCapInfo, sizeof(EXT_CAP_INFO_ELEMENT)) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("ExtCapInfo mismatch!\n")); hex_dump("Old ExtCapInfo", (UCHAR *)&ExtCapInfo, sizeof(EXT_CAP_INFO_ELEMENT)); hex_dump("New ExtCapInfo", (UCHAR *)&ie_list->ExtCapInfo, sizeof(EXT_CAP_INFO_ELEMENT)); } if (AddHtInfoLen != ie_list->AddHtInfoLen) { DBGPRINT(RT_DEBUG_ERROR, ("AddHtInfoLen mismatch!Old=%d, New=%d\n", AddHtInfoLen, ie_list->AddHtInfoLen)); } if (NdisCmpMemory(&ie_list->AddHtInfo, pAddHtInfo, sizeof(ADD_HT_INFO_IE)) != 0) { DBGPRINT(RT_DEBUG_ERROR, ("AddHtInfo mismatch!\n")); hex_dump("Old AddHtInfo", (UCHAR *)pAddHtInfo, sizeof(ADD_HT_INFO_IE)); hex_dump("New AddHtInfo", (UCHAR *)&ie_list->AddHtInfo, sizeof(ADD_HT_INFO_IE)); } if (NewExtChannelOffset != ie_list->NewExtChannelOffset) { DBGPRINT(RT_DEBUG_ERROR, ("AddHtInfoLen mismatch!Old=%d, New=%d\n", NewExtChannelOffset, ie_list->NewExtChannelOffset)); } } goto LabelOK; LabelErr: DBGPRINT(RT_DEBUG_ERROR, ("%s: Allocate memory fail!!!\n", __FUNCTION__)); LabelOK: if (Ssid != NULL) os_free_mem(NULL, Ssid); if (VarIE != NULL) os_free_mem(NULL, VarIE); if (pHtCapability != NULL) os_free_mem(NULL, pHtCapability); if (pAddHtInfo != NULL) os_free_mem(NULL, pAddHtInfo); if (ie_list != NULL) os_free_mem(NULL, ie_list); } //---Add by shiang to check correctness of new sanity function /* ========================================================================== Description: peer sends beacon back when scanning ========================================================================== */ VOID PeerBeaconAtScanAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { PFRAME_802_11 pFrame; USHORT LenVIE; UCHAR *VarIE = NULL; NDIS_802_11_VARIABLE_IEs *pVIE = NULL; BCN_IE_LIST *ie_list = NULL; os_alloc_mem(NULL, (UCHAR **)&ie_list, sizeof(BCN_IE_LIST)); if (!ie_list) { DBGPRINT(RT_DEBUG_ERROR, ("%s():Alloc ie_list failed!\n", __FUNCTION__)); return; } NdisZeroMemory((UCHAR *)ie_list, sizeof(BCN_IE_LIST)); /* Init Variable IE structure */ os_alloc_mem(NULL, (UCHAR **)&VarIE, MAX_VIE_LEN); if (VarIE == NULL) goto LabelErr; pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE; pVIE->Length = 0; pFrame = (PFRAME_802_11) Elem->Msg; if (PeerBeaconAndProbeRspSanity(pAd, &Elem->Msg[0], Elem->MsgLen, Elem->Channel, ie_list, &LenVIE, pVIE)) { ULONG Idx = 0; CHAR Rssi = 0; Idx = BssTableSearch(&pAd->ScanTab, &ie_list->Bssid[0], ie_list->Channel); if (Idx != BSS_NOT_FOUND) Rssi = pAd->ScanTab.BssEntry[Idx].Rssi; Rssi = RTMPMaxRssi(pAd, ConvertToRssi(pAd, Elem->Rssi0, RSSI_0), ConvertToRssi(pAd, Elem->Rssi1, RSSI_1), ConvertToRssi(pAd, Elem->Rssi2, RSSI_2)); #ifdef DOT11_N_SUPPORT if ((ie_list->HtCapabilityLen > 0) || (ie_list->PreNHtCapabilityLen > 0)) ie_list->HtCapabilityLen = SIZE_HT_CAP_IE; #endif /* DOT11_N_SUPPORT */ Idx = BssTableSetEntry(pAd, &pAd->ScanTab, ie_list, Rssi, LenVIE, pVIE); #ifdef DOT11_N_SUPPORT /* TODO: Check for things need to do when enable "DOT11V_WNM_SUPPORT" */ #ifdef DOT11N_DRAFT3 /* Check if this scan channel is the effeced channel */ if (INFRA_ON(pAd) && (pAd->CommonCfg.bBssCoexEnable == TRUE) && ((ie_list->Channel > 0) && (ie_list->Channel <= 14))) { int chListIdx; /* find the channel list idx by the channel number */ for (chListIdx = 0; chListIdx < pAd->ChannelListNum; chListIdx++) { if (ie_list->Channel == pAd->ChannelList[chListIdx].Channel) break; } if (chListIdx < pAd->ChannelListNum) { /* If this channel is effected channel for the 20/40 coex operation. Check the related IEs. */ if (pAd->ChannelList[chListIdx].bEffectedChannel == TRUE) { UCHAR RegClass; OVERLAP_BSS_SCAN_IE BssScan; /* Read Beacon's Reg Class IE if any. */ PeerBeaconAndProbeRspSanity2(pAd, Elem->Msg, Elem->MsgLen, &BssScan, &RegClass); TriEventTableSetEntry(pAd, &pAd->CommonCfg.TriggerEventTab, &ie_list->Bssid[0], &ie_list->HtCapability, ie_list->HtCapabilityLen, RegClass, ie_list->Channel); } } } #endif /* DOT11N_DRAFT3 */ #endif /* DOT11_N_SUPPORT */ if (Idx != BSS_NOT_FOUND) { PBSS_ENTRY pBssEntry = &pAd->ScanTab.BssEntry[Idx]; NdisMoveMemory(pBssEntry->PTSF, &Elem->Msg[24], 4); NdisMoveMemory(&pBssEntry->TTSF[0], &Elem->TimeStamp.u.LowPart, 4); NdisMoveMemory(&pBssEntry->TTSF[4], &Elem->TimeStamp.u.LowPart, 4); pBssEntry->MinSNR = Elem->Signal % 10; if (pBssEntry->MinSNR == 0) pBssEntry->MinSNR = -5; NdisMoveMemory(pBssEntry->MacAddr, &ie_list->Addr2[0], MAC_ADDR_LEN); if ((pFrame->Hdr.FC.SubType == SUBTYPE_PROBE_RSP) && (LenVIE != 0)) { pBssEntry->VarIeFromProbeRspLen = 0; if (pBssEntry->pVarIeFromProbRsp) { pBssEntry->VarIeFromProbeRspLen = LenVIE; RTMPZeroMemory(pBssEntry->pVarIeFromProbRsp, MAX_VIE_LEN); RTMPMoveMemory(pBssEntry->pVarIeFromProbRsp, pVIE, LenVIE); } } } #ifdef LINUX #ifdef RT_CFG80211_SUPPORT RT_CFG80211_SCANNING_INFORM(pAd, Idx, Elem->Channel, (UCHAR *)pFrame, Elem->MsgLen, Rssi); #endif /* RT_CFG80211_SUPPORT */ #endif /* LINUX */ } /* sanity check fail, ignored */ goto LabelOK; LabelErr: DBGPRINT(RT_DEBUG_ERROR, ("%s: Allocate memory fail!!!\n", __FUNCTION__)); LabelOK: if (VarIE != NULL) os_free_mem(NULL, VarIE); if (ie_list) os_free_mem(NULL, ie_list); return; } /* ========================================================================== Description: When waiting joining the (I)BSS, beacon received from external ========================================================================== */ VOID PeerBeaconAtJoinAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { BOOLEAN TimerCancelled; USHORT LenVIE; USHORT Status; UCHAR *VarIE = NULL; NDIS_802_11_VARIABLE_IEs *pVIE = NULL; ULONG Idx = 0; CHAR Rssi = 0; #ifdef DOT11_N_SUPPORT UCHAR CentralChannel; BOOLEAN bAllowNrate = FALSE; #endif /* DOT11_N_SUPPORT */ BCN_IE_LIST *ie_list = NULL; /* allocate memory */ os_alloc_mem(NULL, (UCHAR **)&ie_list, sizeof(BCN_IE_LIST)); if (ie_list == NULL) goto LabelErr; NdisZeroMemory(ie_list, sizeof(BCN_IE_LIST)); os_alloc_mem(NULL, (UCHAR **)&VarIE, MAX_VIE_LEN); if (VarIE == NULL) goto LabelErr; /* Init Variable IE structure */ pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE; pVIE->Length = 0; if (PeerBeaconAndProbeRspSanity(pAd, Elem->Msg, Elem->MsgLen, Elem->Channel, ie_list, &LenVIE, pVIE)) { /* Disqualify 11b only adhoc when we are in 11g only adhoc mode */ if ((ie_list->BssType == BSS_ADHOC) && WMODE_EQUAL(pAd->CommonCfg.PhyMode, WMODE_G) && ((ie_list->SupRateLen+ie_list->ExtRateLen)< 12)) goto LabelOK; /* BEACON from desired BSS/IBSS found. We should be able to decide most BSS parameters here. Q. But what happen if this JOIN doesn't conclude a successful ASSOCIATEION? Do we need to receover back all parameters belonging to previous BSS? A. Should be not. There's no back-door recover to previous AP. It still need a new JOIN-AUTH-ASSOC sequence. */ if (MAC_ADDR_EQUAL(pAd->MlmeAux.Bssid, &ie_list->Bssid[0])) { DBGPRINT(RT_DEBUG_TRACE, ("%s():receive desired BEACON,Channel=%d\n", __FUNCTION__, ie_list->Channel)); RTMPCancelTimer(&pAd->MlmeAux.BeaconTimer, &TimerCancelled); /* Update RSSI to prevent No signal display when cards first initialized */ pAd->StaCfg.RssiSample.LastRssi0 = ConvertToRssi(pAd, Elem->Rssi0, RSSI_0); pAd->StaCfg.RssiSample.LastRssi1 = ConvertToRssi(pAd, Elem->Rssi1, RSSI_1); pAd->StaCfg.RssiSample.LastRssi2 = ConvertToRssi(pAd, Elem->Rssi2, RSSI_2); pAd->StaCfg.RssiSample.AvgRssi0 = pAd->StaCfg.RssiSample.LastRssi0; pAd->StaCfg.RssiSample.AvgRssi0X8 = pAd->StaCfg.RssiSample.AvgRssi0 << 3; pAd->StaCfg.RssiSample.AvgRssi1 = pAd->StaCfg.RssiSample.LastRssi1; pAd->StaCfg.RssiSample.AvgRssi1X8 = pAd->StaCfg.RssiSample.AvgRssi1 << 3; pAd->StaCfg.RssiSample.AvgRssi2 = pAd->StaCfg.RssiSample.LastRssi2; pAd->StaCfg.RssiSample.AvgRssi2X8 = pAd->StaCfg.RssiSample.AvgRssi2 << 3; /* We need to check if SSID only set to any, then we can record the current SSID. Otherwise will cause hidden SSID association failed. */ if (pAd->MlmeAux.SsidLen == 0) { NdisMoveMemory(pAd->MlmeAux.Ssid, ie_list->Ssid, ie_list->SsidLen); pAd->MlmeAux.SsidLen = ie_list->SsidLen; } else { Idx = BssSsidTableSearch(&pAd->ScanTab, ie_list->Bssid, pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen, ie_list->Channel); if (Idx == BSS_NOT_FOUND) { Rssi = RTMPMaxRssi(pAd, ConvertToRssi(pAd, Elem->Rssi0, RSSI_0), ConvertToRssi(pAd, Elem->Rssi1, RSSI_1), ConvertToRssi(pAd, Elem->Rssi2, RSSI_2)); Idx = BssTableSetEntry(pAd, &pAd->ScanTab, ie_list, Rssi, LenVIE, pVIE); if (Idx != BSS_NOT_FOUND) { NdisMoveMemory(pAd->ScanTab.BssEntry[Idx].PTSF, &Elem->Msg[24], 4); NdisMoveMemory(&pAd->ScanTab.BssEntry[Idx].TTSF[0], &Elem->TimeStamp.u.LowPart, 4); NdisMoveMemory(&pAd->ScanTab.BssEntry[Idx].TTSF[4], &Elem->TimeStamp.u.LowPart, 4); ie_list->CapabilityInfo = pAd->ScanTab.BssEntry[Idx].CapabilityInfo; pAd->ScanTab.BssEntry[Idx].MinSNR = Elem->Signal % 10; if (pAd->ScanTab.BssEntry[Idx].MinSNR == 0) pAd->ScanTab.BssEntry[Idx].MinSNR = -5; NdisMoveMemory(pAd->ScanTab.BssEntry[Idx].MacAddr, ie_list->Addr2, MAC_ADDR_LEN); } } else { #ifdef WPA_SUPPLICANT_SUPPORT if (pAd->StaCfg.WpaSupplicantUP & WPA_SUPPLICANT_ENABLE_WPS) ; else #endif /* WPA_SUPPLICANT_SUPPORT */ { /* Check if AP privacy is different Staion, if yes, start a new scan and ignore the frame (often happen during AP change privacy at short time) */ if ((((pAd->StaCfg.WepStatus != Ndis802_11WEPDisabled) << 4) ^ ie_list->CapabilityInfo) & 0x0010) { MLME_SCAN_REQ_STRUCT ScanReq; DBGPRINT(RT_DEBUG_TRACE, ("%s:AP privacy %d is differenct from STA privacy%d\n", __FUNCTION__, (ie_list->CapabilityInfo & 0x0010) >> 4 , pAd->StaCfg.WepStatus != Ndis802_11WEPDisabled)); ScanParmFill(pAd, &ScanReq, (PSTRING) pAd->MlmeAux.Ssid, pAd->MlmeAux.SsidLen, BSS_ANY, SCAN_ACTIVE); MlmeEnqueue(pAd, SYNC_STATE_MACHINE, MT2_MLME_SCAN_REQ, sizeof(MLME_SCAN_REQ_STRUCT), &ScanReq, 0); pAd->Mlme.CntlMachine.CurrState = CNTL_WAIT_OID_LIST_SCAN; NdisGetSystemUpTime(&pAd->StaCfg.LastScanTime); goto LabelOK; } } /* Multiple SSID case, used correct CapabilityInfo */ ie_list->CapabilityInfo = pAd->ScanTab.BssEntry[Idx].CapabilityInfo; } } pAd->MlmeAux.CapabilityInfo = ie_list->CapabilityInfo & SUPPORTED_CAPABILITY_INFO; pAd->MlmeAux.BssType = ie_list->BssType; pAd->MlmeAux.BeaconPeriod = ie_list->BeaconPeriod; /* Some AP may carrys wrong beacon interval (ex. 0) in Beacon IE. We need to check here for preventing divided by 0 error. */ if (pAd->MlmeAux.BeaconPeriod == 0) pAd->MlmeAux.BeaconPeriod = 100; pAd->MlmeAux.Channel = ie_list->Channel; pAd->MlmeAux.AtimWin = ie_list->AtimWin; pAd->MlmeAux.CfpPeriod = ie_list->CfParm.CfpPeriod; pAd->MlmeAux.CfpMaxDuration = ie_list->CfParm.CfpMaxDuration; pAd->MlmeAux.APRalinkIe = ie_list->RalinkIe; /* Copy AP's supported rate to MlmeAux for creating assoication request Also filter out not supported rate */ pAd->MlmeAux.SupRateLen = ie_list->SupRateLen; NdisMoveMemory(pAd->MlmeAux.SupRate, ie_list->SupRate, ie_list->SupRateLen); RTMPCheckRates(pAd, pAd->MlmeAux.SupRate, &pAd->MlmeAux.SupRateLen); pAd->MlmeAux.ExtRateLen = ie_list->ExtRateLen; NdisMoveMemory(pAd->MlmeAux.ExtRate, ie_list->ExtRate, ie_list->ExtRateLen); RTMPCheckRates(pAd, pAd->MlmeAux.ExtRate, &pAd->MlmeAux.ExtRateLen); NdisZeroMemory(pAd->StaActive.SupportedPhyInfo.MCSSet, 16); /* Get the ext capability info element */ NdisMoveMemory(&pAd->MlmeAux.ExtCapInfo, &ie_list->ExtCapInfo,sizeof(ie_list->ExtCapInfo)); pAd->StaActive.SupportedPhyInfo.bVhtEnable = FALSE; pAd->StaActive.SupportedPhyInfo.vht_bw = VHT_BW_2040; #ifdef DOT11_N_SUPPORT #ifdef DOT11N_DRAFT3 DBGPRINT(RT_DEBUG_TRACE, ("MlmeAux.ExtCapInfo=%d\n", pAd->MlmeAux.ExtCapInfo.BssCoexistMgmtSupport)); if (pAd->CommonCfg.bBssCoexEnable == TRUE) pAd->CommonCfg.ExtCapIE.BssCoexistMgmtSupport = 1; #endif /* DOT11N_DRAFT3 */ if (((pAd->StaCfg.WepStatus != Ndis802_11WEPEnabled) && (pAd->StaCfg.WepStatus != Ndis802_11Encryption2Enabled)) || (pAd->CommonCfg.HT_DisallowTKIP == FALSE)) { if ((pAd->StaCfg.BssType == BSS_INFRA) || ((pAd->StaCfg.BssType == BSS_ADHOC) && (pAd->StaCfg.bAdhocN == TRUE))) bAllowNrate = TRUE; } pAd->MlmeAux.NewExtChannelOffset = ie_list->NewExtChannelOffset; pAd->MlmeAux.HtCapabilityLen = ie_list->HtCapabilityLen; CentralChannel = ie_list->Channel; RTMPZeroMemory(&pAd->MlmeAux.HtCapability, SIZE_HT_CAP_IE); /* filter out un-supported ht rates */ if (((ie_list->HtCapabilityLen > 0) || (ie_list->PreNHtCapabilityLen > 0)) && (pAd->StaCfg.DesiredHtPhyInfo.bHtEnable) && (WMODE_CAP_N(pAd->CommonCfg.PhyMode) && bAllowNrate)) { RTMPMoveMemory(&pAd->MlmeAux.AddHtInfo, &ie_list->AddHtInfo, SIZE_ADD_HT_INFO_IE); /* StaActive.SupportedHtPhy.MCSSet stores Peer AP's 11n Rx capability */ NdisMoveMemory(pAd->StaActive.SupportedPhyInfo.MCSSet, ie_list->HtCapability.MCSSet, 16); pAd->MlmeAux.NewExtChannelOffset = ie_list->NewExtChannelOffset; pAd->MlmeAux.HtCapabilityLen = SIZE_HT_CAP_IE; pAd->StaActive.SupportedPhyInfo.bHtEnable = TRUE; if (ie_list->PreNHtCapabilityLen > 0) pAd->StaActive.SupportedPhyInfo.bPreNHt = TRUE; RTMPCheckHt(pAd, BSSID_WCID, &ie_list->HtCapability, &ie_list->AddHtInfo); /* Copy AP Parameter to StaActive. This is also in LinkUp. */ DBGPRINT(RT_DEBUG_TRACE, ("%s():(MpduDensity=%d, MaxRAmpduFactor=%d, BW=%d)\n", __FUNCTION__, pAd->StaActive.SupportedHtPhy.MpduDensity, pAd->StaActive.SupportedHtPhy.MaxRAmpduFactor, ie_list->HtCapability.HtCapInfo.ChannelWidth)); if (ie_list->AddHtInfoLen > 0) { /* Check again the Bandwidth capability of this AP. */ CentralChannel = get_cent_ch_by_htinfo(pAd, &ie_list->AddHtInfo, &ie_list->HtCapability); DBGPRINT(RT_DEBUG_OFF, ("%s(): HT-CtrlChannel=%d, CentralChannel=>%d\n", __FUNCTION__, ie_list->AddHtInfo.ControlChan, CentralChannel)); } #ifdef DOT11_VHT_AC if (WMODE_CAP_AC(pAd->CommonCfg.PhyMode) && (pAd->MlmeAux.Channel > 14) && (ie_list->vht_cap_len)) { VHT_OP_INFO *vht_op = &ie_list->vht_op_ie.vht_op_info; NdisMoveMemory(&pAd->MlmeAux.vht_cap, &ie_list->vht_cap_ie, ie_list->vht_cap_len); pAd->MlmeAux.vht_cap_len = ie_list->vht_cap_len; pAd->StaActive.SupportedPhyInfo.bVhtEnable = TRUE; if (vht_op->ch_width == 0) { pAd->StaActive.SupportedPhyInfo.vht_bw = VHT_BW_2040; } else if (vht_op->ch_width == 1) { CentralChannel = vht_op->center_freq_1; pAd->StaActive.SupportedPhyInfo.vht_bw = VHT_BW_80; } DBGPRINT(RT_DEBUG_OFF, ("%s(): VHT->center_freq_1=%d, CentralChannel=>%d, vht_cent_ch=%d\n", __FUNCTION__, vht_op->center_freq_1, CentralChannel, pAd->CommonCfg.vht_cent_ch)); } #endif /* DOT11_VHT_AC */ } else #endif /* DOT11_N_SUPPORT */ { /* To prevent error, let legacy AP must have same CentralChannel and Channel. */ if ((ie_list->HtCapabilityLen == 0) && (ie_list->PreNHtCapabilityLen == 0)) pAd->MlmeAux.CentralChannel = pAd->MlmeAux.Channel; pAd->StaActive.SupportedPhyInfo.bHtEnable = FALSE; #ifdef DOT11_VHT_AC pAd->StaActive.SupportedPhyInfo.bVhtEnable = FALSE; pAd->StaActive.SupportedPhyInfo.vht_bw = VHT_BW_2040; #endif /* DOT11_VHT_AC */ pAd->MlmeAux.NewExtChannelOffset = 0xff; RTMPZeroMemory(&pAd->MlmeAux.HtCapability, SIZE_HT_CAP_IE); pAd->MlmeAux.HtCapabilityLen = 0; RTMPZeroMemory(&pAd->MlmeAux.AddHtInfo, SIZE_ADD_HT_INFO_IE); } pAd->hw_cfg.cent_ch = CentralChannel; pAd->MlmeAux.CentralChannel = CentralChannel; DBGPRINT(RT_DEBUG_OFF, ("%s(): Set CentralChannel=%d\n", __FUNCTION__, pAd->MlmeAux.CentralChannel)); RTMPUpdateMlmeRate(pAd); /* copy QOS related information */ if ((pAd->CommonCfg.bWmmCapable) #ifdef DOT11_N_SUPPORT || WMODE_CAP_N(pAd->CommonCfg.PhyMode) #endif /* DOT11_N_SUPPORT */ ) { NdisMoveMemory(&pAd->MlmeAux.APEdcaParm, &ie_list->EdcaParm, sizeof(EDCA_PARM)); NdisMoveMemory(&pAd->MlmeAux.APQbssLoad, &ie_list->QbssLoad, sizeof(QBSS_LOAD_PARM)); NdisMoveMemory(&pAd->MlmeAux.APQosCapability, &ie_list->QosCapability, sizeof(QOS_CAPABILITY_PARM)); } else { NdisZeroMemory(&pAd->MlmeAux.APEdcaParm, sizeof(EDCA_PARM)); NdisZeroMemory(&pAd->MlmeAux.APQbssLoad, sizeof(QBSS_LOAD_PARM)); NdisZeroMemory(&pAd->MlmeAux.APQosCapability, sizeof(QOS_CAPABILITY_PARM)); } DBGPRINT(RT_DEBUG_TRACE, ("%s(): - after JOIN, SupRateLen=%d, ExtRateLen=%d\n", __FUNCTION__, pAd->MlmeAux.SupRateLen, pAd->MlmeAux.ExtRateLen)); if (ie_list->AironetCellPowerLimit != 0xFF) { /* We need to change our TxPower for CCX 2.0 AP Control of Client Transmit Power */ ChangeToCellPowerLimit(pAd, ie_list->AironetCellPowerLimit); } else /* Used the default TX Power Percentage. */ pAd->CommonCfg.TxPowerPercentage = pAd->CommonCfg.TxPowerDefault; if (pAd->StaCfg.BssType == BSS_INFRA) { BOOLEAN InfraAP_BW; UCHAR BwFallBack = 0; if (pAd->MlmeAux.HtCapability.HtCapInfo.ChannelWidth == BW_40) InfraAP_BW = TRUE; else InfraAP_BW = FALSE; AdjustChannelRelatedValue(pAd, &BwFallBack, BSS0, InfraAP_BW, pAd->MlmeAux.Channel, pAd->MlmeAux.CentralChannel); } pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE; Status = MLME_SUCCESS; MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_JOIN_CONF, 2, &Status, 0); #ifdef LINUX #ifdef RT_CFG80211_SUPPORT RT_CFG80211_SCANNING_INFORM(pAd, Idx, Elem->Channel, Elem->Msg, Elem->MsgLen, Rssi); #endif /* RT_CFG80211_SUPPORT */ #endif /* LINUX */ } /* not to me BEACON, ignored */ } /* sanity check fail, ignore this frame */ goto LabelOK; LabelErr: DBGPRINT(RT_DEBUG_ERROR, ("%s: Allocate memory fail!!!\n", __FUNCTION__)); LabelOK: if (ie_list != NULL) os_free_mem(NULL, ie_list); if (VarIE != NULL) os_free_mem(NULL, VarIE); return; } /* ========================================================================== Description: receive BEACON from peer IRQL = DISPATCH_LEVEL ========================================================================== */ VOID PeerBeacon( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { UCHAR index=0; USHORT TbttNumToNextWakeUp; USHORT LenVIE; UCHAR *VarIE = NULL; /* Total VIE length = MAX_VIE_LEN - -5 */ NDIS_802_11_VARIABLE_IEs *pVIE = NULL; BCN_IE_LIST *ie_list = NULL; #ifdef RALINK_ATE if (ATE_ON(pAd)) { return; } #endif /* RALINK_ATE */ if (!(INFRA_ON(pAd) || ADHOC_ON(pAd) )) return; /* allocate memory */ os_alloc_mem(NULL, (UCHAR **)&ie_list, sizeof(BCN_IE_LIST)); if (ie_list == NULL) goto LabelErr; NdisZeroMemory(ie_list, sizeof(BCN_IE_LIST)); os_alloc_mem(NULL, (UCHAR **)&VarIE, MAX_VIE_LEN); if (VarIE == NULL) goto LabelErr; /* Init Variable IE structure */ pVIE = (PNDIS_802_11_VARIABLE_IEs) VarIE; pVIE->Length = 0; if (PeerBeaconAndProbeRspSanity(pAd, Elem->Msg, Elem->MsgLen, Elem->Channel, ie_list, &LenVIE, pVIE)) { BOOLEAN is_my_bssid, is_my_ssid; ULONG Bssidx, Now; BSS_ENTRY *pBss; CHAR RealRssi = RTMPMaxRssi(pAd, ConvertToRssi(pAd, Elem->Rssi0, RSSI_0), ConvertToRssi(pAd, Elem->Rssi1, RSSI_1), ConvertToRssi(pAd, Elem->Rssi2, RSSI_2)); is_my_bssid = MAC_ADDR_EQUAL(ie_list->Bssid, pAd->CommonCfg.Bssid)? TRUE : FALSE; is_my_ssid = SSID_EQUAL(ie_list->Ssid, ie_list->SsidLen, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen)? TRUE:FALSE; /* ignore BEACON not for my SSID */ if ((!is_my_ssid) && (!is_my_bssid)) goto LabelOK; /* It means STA waits disassoc completely from this AP, ignores this beacon. */ if (pAd->Mlme.CntlMachine.CurrState == CNTL_WAIT_DISASSOC) goto LabelOK; #ifdef DOT11_N_SUPPORT /* Copy Control channel for this BSSID. */ if (ie_list->AddHtInfoLen != 0) ie_list->Channel = ie_list->AddHtInfo.ControlChan; if ((ie_list->HtCapabilityLen > 0) || (ie_list->PreNHtCapabilityLen > 0)) ie_list->HtCapabilityLen = SIZE_HT_CAP_IE; #endif /* DOT11_N_SUPPORT */ /* Housekeeping "SsidBssTab" table for later-on ROAMing usage. */ Bssidx = BssTableSearchWithSSID(&pAd->MlmeAux.SsidBssTab, ie_list->Bssid, ie_list->Ssid, ie_list->SsidLen, ie_list->Channel); if (Bssidx == BSS_NOT_FOUND) { /* discover new AP of this network, create BSS entry */ Bssidx = BssTableSetEntry(pAd, &pAd->MlmeAux.SsidBssTab, ie_list, RealRssi, LenVIE, pVIE); if (Bssidx == BSS_NOT_FOUND) ; else { PBSS_ENTRY pBssEntry = &pAd->MlmeAux.SsidBssTab.BssEntry[Bssidx]; NdisMoveMemory(&pBssEntry->PTSF[0], &Elem->Msg[24], 4); NdisMoveMemory(&pBssEntry->TTSF[0], &Elem->TimeStamp.u.LowPart, 4); NdisMoveMemory(&pBssEntry->TTSF[4], &Elem->TimeStamp.u.LowPart, 4); pBssEntry->Rssi = RealRssi; NdisMoveMemory(pBssEntry->MacAddr, ie_list->Addr2, MAC_ADDR_LEN); } } /* Update ScanTab */ Bssidx = BssTableSearch(&pAd->ScanTab, ie_list->Bssid, ie_list->Channel); if (Bssidx == BSS_NOT_FOUND) { /* discover new AP of this network, create BSS entry */ Bssidx = BssTableSetEntry(pAd, &pAd->ScanTab, ie_list, RealRssi, LenVIE, pVIE); if (Bssidx == BSS_NOT_FOUND) /* return if BSS table full */ goto LabelOK; NdisMoveMemory(pAd->ScanTab.BssEntry[Bssidx].PTSF, &Elem->Msg[24], 4); NdisMoveMemory(&pAd->ScanTab.BssEntry[Bssidx].TTSF[0], &Elem->TimeStamp.u.LowPart, 4); NdisMoveMemory(&pAd->ScanTab.BssEntry[Bssidx].TTSF[4], &Elem->TimeStamp.u.LowPart, 4); pAd->ScanTab.BssEntry[Bssidx].MinSNR = Elem->Signal % 10; if (pAd->ScanTab.BssEntry[Bssidx].MinSNR == 0) pAd->ScanTab.BssEntry[Bssidx].MinSNR = -5; NdisMoveMemory(pAd->ScanTab.BssEntry[Bssidx].MacAddr, ie_list->Addr2, MAC_ADDR_LEN); } /* if the ssid matched & bssid unmatched, we should select the bssid with large value. This might happened when two STA start at the same time */ if ((! is_my_bssid) && ADHOC_ON(pAd)) { INT i; /* Add the safeguard against the mismatch of adhoc wep status */ if ((pAd->StaCfg.WepStatus != pAd->ScanTab.BssEntry[Bssidx].WepStatus) || (pAd->StaCfg.AuthMode != pAd->ScanTab.BssEntry[Bssidx].AuthMode)) { goto LabelOK; } /* collapse into the ADHOC network which has bigger BSSID value. */ for (i = 0; i < 6; i++) { if (ie_list->Bssid[i] > pAd->CommonCfg.Bssid[i]) { DBGPRINT(RT_DEBUG_TRACE, ("SYNC - merge to the IBSS with bigger BSSID=%02x:%02x:%02x:%02x:%02x:%02x\n", PRINT_MAC(ie_list->Bssid))); AsicDisableSync(pAd); COPY_MAC_ADDR(pAd->CommonCfg.Bssid, ie_list->Bssid); AsicSetBssid(pAd, pAd->CommonCfg.Bssid); MakeIbssBeacon(pAd); /* re-build BEACON frame */ AsicEnableIbssSync(pAd); /* copy BEACON frame to on-chip memory */ is_my_bssid = TRUE; break; } else if (ie_list->Bssid[i] < pAd->CommonCfg.Bssid[i]) break; } } NdisGetSystemUpTime(&Now); pBss = &pAd->ScanTab.BssEntry[Bssidx]; pBss->Rssi = RealRssi; /* lastest RSSI */ pBss->LastBeaconRxTime = Now; /* last RX timestamp */ /* BEACON from my BSSID - either IBSS or INFRA network */ if (is_my_bssid) { RXWI_STRUC RxWI; UINT8 RXWISize = pAd->chipCap.RXWISize; #ifdef DOT11_N_SUPPORT #ifdef DOT11N_DRAFT3 OVERLAP_BSS_SCAN_IE BssScan; UCHAR RegClass; BOOLEAN brc; /* Read Beacon's Reg Class IE if any. */ brc = PeerBeaconAndProbeRspSanity2(pAd, Elem->Msg, Elem->MsgLen, &BssScan, &RegClass); if (brc == TRUE) { UpdateBssScanParm(pAd, BssScan); pAd->StaCfg.RegClass = RegClass; } #endif /* DOT11N_DRAFT3 */ #endif /* DOT11_N_SUPPORT */ pAd->StaCfg.DtimCount = ie_list->DtimCount; pAd->StaCfg.DtimPeriod = ie_list->DtimPeriod; pAd->StaCfg.LastBeaconRxTime = Now; NdisZeroMemory(&RxWI, RXWISize); RxWI.RxWIRSSI0 = Elem->Rssi0; RxWI.RxWIRSSI1 = Elem->Rssi1; RxWI.RxWIRSSI2 = Elem->Rssi2; RxWI.RxWIPhyMode = 0; /* Prevent SNR calculate error. */ if (INFRA_ON(pAd)) { MAC_TABLE_ENTRY *pEntry = &pAd->MacTab.Content[BSSID_WCID]; if (pEntry) Update_Rssi_Sample(pAd, &pEntry->RssiSample, &RxWI); } Update_Rssi_Sample(pAd, &pAd->StaCfg.RssiSample, &RxWI); if ((pAd->CommonCfg.bIEEE80211H == 1) && (ie_list->NewChannel != 0) && (ie_list->Channel != ie_list->NewChannel)) { /* Switching to channel 1 can prevent from rescanning the current channel immediately (by auto reconnection). */ /* In addition, clear the MLME queue and the scan table to discard the RX packets and previous scanning results. */ AsicSwitchChannel(pAd, 1, FALSE); AsicLockChannel(pAd, 1); LinkDown(pAd, FALSE); MlmeQueueInit(pAd, &pAd->Mlme.Queue); BssTableInit(&pAd->ScanTab); RTMPusecDelay(1000000); /* use delay to prevent STA do reassoc */ /* channel sanity check */ for (index = 0 ; index < pAd->ChannelListNum; index++) { if (pAd->ChannelList[index].Channel == ie_list->NewChannel) { pAd->ScanTab.BssEntry[Bssidx].Channel = ie_list->NewChannel; pAd->CommonCfg.Channel = ie_list->NewChannel; AsicSwitchChannel(pAd, pAd->CommonCfg.Channel, FALSE); AsicLockChannel(pAd, pAd->CommonCfg.Channel); DBGPRINT(RT_DEBUG_TRACE, ("PeerBeacon - STA receive channel switch announcement IE (New Channel =%d)\n", ie_list->NewChannel)); break; } } if (index >= pAd->ChannelListNum) { DBGPRINT_ERR(("PeerBeacon(can not find New Channel=%d in ChannelList[%d]\n", pAd->CommonCfg.Channel, pAd->ChannelListNum)); } } #ifdef WPA_SUPPLICANT_SUPPORT if (pAd->StaCfg.WpaSupplicantUP & WPA_SUPPLICANT_ENABLE_WPS) ; else #endif /* WPA_SUPPLICANT_SUPPORT */ { if ((((pAd->StaCfg.WepStatus != Ndis802_11WEPDisabled) << 4) ^ ie_list->CapabilityInfo) & 0x0010) { /* To prevent STA connect to OPEN/WEP AP when STA is OPEN/NONE or STA connect to OPEN/NONE AP when STA is OPEN/WEP AP. */ DBGPRINT(RT_DEBUG_TRACE, ("%s:AP privacy:%x is differenct from STA privacy:%x\n", __FUNCTION__, (ie_list->CapabilityInfo & 0x0010) >> 4 , pAd->StaCfg.WepStatus != Ndis802_11WEPDisabled)); if (INFRA_ON(pAd)) { LinkDown(pAd,FALSE); BssTableInit(&pAd->ScanTab); } goto LabelOK; } } #ifdef LINUX #ifdef RT_CFG80211_SUPPORT /* CFG80211_BeaconCountryRegionParse(pAd, pVIE, LenVIE); */ #endif /* RT_CFG80211_SUPPORT */ #endif /* LINUX */ if (ie_list->AironetCellPowerLimit != 0xFF) { /* We get the Cisco (ccx) "TxPower Limit" required Changed to appropriate TxPower Limit for Ciso Compatible Extensions */ ChangeToCellPowerLimit(pAd, ie_list->AironetCellPowerLimit); } else { /* AironetCellPowerLimit equal to 0xFF means the Cisco (ccx) "TxPower Limit" not exist. Used the default TX Power Percentage, that set from UI. */ pAd->CommonCfg.TxPowerPercentage = pAd->CommonCfg.TxPowerDefault; } if (ADHOC_ON(pAd) && (CAP_IS_IBSS_ON(ie_list->CapabilityInfo))) { UCHAR MaxSupportedRateIn500Kbps = 0; UCHAR idx; MAC_TABLE_ENTRY *pEntry; MaxSupportedRateIn500Kbps = dot11_max_sup_rate(ie_list->SupRateLen, &ie_list->SupRate[0], ie_list->ExtRateLen, &ie_list->ExtRate[0]); /* look up the existing table */ pEntry = MacTableLookup(pAd, ie_list->Addr2); /* Ad-hoc mode is using MAC address as BA session. So we need to continuously find newly joined adhoc station by receiving beacon. To prevent always check this, we use wcid == RESERVED_WCID to recognize it as newly joined adhoc station. */ if ((ADHOC_ON(pAd) && ((!pEntry) || (pEntry && IS_ENTRY_NONE(pEntry)))) || (pEntry && RTMP_TIME_AFTER(Now, pEntry->LastBeaconRxTime + ADHOC_ENTRY_BEACON_LOST_TIME))) { if (pEntry == NULL) /* Another adhoc joining, add to our MAC table. */ pEntry = MacTableInsertEntry(pAd, ie_list->Addr2, BSS0, OPMODE_STA, FALSE); if (pEntry == NULL) goto LabelOK; #ifdef DOT11_VHT_AC { BOOLEAN result; IE_LISTS *ielist; os_alloc_mem(NULL, (UCHAR **)&ielist, sizeof(IE_LISTS)); if (!ielist) goto LabelOK; NdisZeroMemory((UCHAR *)ielist, sizeof(IE_LISTS)); if (ie_list->vht_cap_len && ie_list->vht_op_len) { NdisMoveMemory(&ielist->vht_cap, &ie_list->vht_cap_ie, sizeof(VHT_CAP_IE)); NdisMoveMemory(&ielist->vht_op, &ie_list->vht_op_ie, sizeof(VHT_OP_IE)); ielist->vht_cap_len = ie_list->vht_cap_len; ielist->vht_op_len = ie_list->vht_op_len; } result = StaAddMacTableEntry(pAd, pEntry, MaxSupportedRateIn500Kbps, &ie_list->HtCapability, ie_list->HtCapabilityLen, &ie_list->AddHtInfo, ie_list->AddHtInfoLen, ielist, ie_list->CapabilityInfo); os_free_mem(NULL, ielist); if ( result== FALSE) { DBGPRINT(RT_DEBUG_TRACE, ("ADHOC - Add Entry failed.\n")); goto LabelOK; } } #else if (StaAddMacTableEntry(pAd, pEntry, MaxSupportedRateIn500Kbps, &ie_list->HtCapability, ie_list->HtCapabilityLen, &ie_list->AddHtInfo, ie_list->AddHtInfoLen, ie_list, ie_list->CapabilityInfo) == FALSE) { DBGPRINT(RT_DEBUG_TRACE, ("ADHOC - Add Entry failed.\n")); goto LabelOK; } #endif /* DOT11_VHT_AC */ if (ADHOC_ON(pAd) && pEntry) { RTMPSetSupportMCS(pAd, OPMODE_STA, pEntry, ie_list->SupRate, ie_list->SupRateLen, ie_list->ExtRate, ie_list->ExtRateLen, #ifdef DOT11_VHT_AC ie_list->vht_cap_len, &ie_list->vht_cap_ie, #endif /* DOT11_VHT_AC */ &ie_list->HtCapability, ie_list->HtCapabilityLen); } pEntry->LastBeaconRxTime = 0; if (pEntry && (Elem->Wcid == RESERVED_WCID)) { idx = pAd->StaCfg.DefaultKeyId; RTMP_SET_WCID_SEC_INFO(pAd, BSS0, idx, pAd->SharedKey[BSS0][idx].CipherAlg, pEntry->Aid, SHAREDKEYTABLE); } } if (pEntry && IS_ENTRY_CLIENT(pEntry)) { pEntry->LastBeaconRxTime = Now; } /* At least another peer in this IBSS, declare MediaState as CONNECTED */ if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED)) { OPSTATUS_SET_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED); RTMP_IndicateMediaState(pAd, NdisMediaStateConnected); pAd->ExtraInfo = GENERAL_LINK_UP; DBGPRINT(RT_DEBUG_TRACE, ("ADHOC fOP_STATUS_MEDIA_STATE_CONNECTED.\n")); } } if (INFRA_ON(pAd)) { BOOLEAN bUseShortSlot, bUseBGProtection; /* decide to use/change to - 1. long slot (20 us) or short slot (9 us) time 2. turn on/off RTS/CTS and/or CTS-to-self protection 3. short preamble */ /* bUseShortSlot = pAd->CommonCfg.bUseShortSlotTime && CAP_IS_SHORT_SLOT(CapabilityInfo); */ bUseShortSlot = CAP_IS_SHORT_SLOT(ie_list->CapabilityInfo); if (bUseShortSlot != OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SHORT_SLOT_INUSED)) AsicSetSlotTime(pAd, bUseShortSlot); bUseBGProtection = (pAd->CommonCfg.UseBGProtection == 1) || /* always use */ ((pAd->CommonCfg.UseBGProtection == 0) && ERP_IS_USE_PROTECTION(ie_list->Erp)); if (pAd->CommonCfg.Channel > 14) /* always no BG protection in A-band. falsely happened when switching A/G band to a dual-band AP */ bUseBGProtection = FALSE; if (bUseBGProtection != OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED)) { if (bUseBGProtection) { OPSTATUS_SET_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED); AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, (OFDMSETPROTECT|CCKSETPROTECT|ALLN_SETPROTECT), FALSE,(pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent == 1)); } else { OPSTATUS_CLEAR_FLAG(pAd, fOP_STATUS_BG_PROTECTION_INUSED); AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, (OFDMSETPROTECT|CCKSETPROTECT|ALLN_SETPROTECT),TRUE, (pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent == 1)); } DBGPRINT(RT_DEBUG_WARN, ("SYNC - AP changed B/G protection to %d\n", bUseBGProtection)); } #ifdef DOT11_N_SUPPORT /* check Ht protection mode. and adhere to the Non-GF device indication by AP. */ if ((ie_list->AddHtInfoLen != 0) && ((ie_list->AddHtInfo.AddHtInfo2.OperaionMode != pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode) || (ie_list->AddHtInfo.AddHtInfo2.NonGfPresent != pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent))) { pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent = ie_list->AddHtInfo.AddHtInfo2.NonGfPresent; pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode = ie_list->AddHtInfo.AddHtInfo2.OperaionMode; if (pAd->MlmeAux.AddHtInfo.AddHtInfo2.NonGfPresent == 1) { AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, ALLN_SETPROTECT, FALSE, TRUE); } else AsicUpdateProtect(pAd, pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode, ALLN_SETPROTECT, FALSE, FALSE); DBGPRINT(RT_DEBUG_TRACE, ("SYNC - AP changed N OperaionMode to %d\n", pAd->MlmeAux.AddHtInfo.AddHtInfo2.OperaionMode)); } #endif /* DOT11_N_SUPPORT */ if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_SHORT_PREAMBLE_INUSED) && ERP_IS_USE_BARKER_PREAMBLE(ie_list->Erp)) { MlmeSetTxPreamble(pAd, Rt802_11PreambleLong); DBGPRINT(RT_DEBUG_TRACE, ("SYNC - AP forced to use LONG preamble\n")); } if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) && (ie_list->EdcaParm.bValid == TRUE) && (ie_list->EdcaParm.EdcaUpdateCount != pAd->CommonCfg.APEdcaParm.EdcaUpdateCount)) { DBGPRINT(RT_DEBUG_TRACE, ("SYNC - AP change EDCA parameters(from %d to %d)\n", pAd->CommonCfg.APEdcaParm.EdcaUpdateCount, ie_list->EdcaParm.EdcaUpdateCount)); AsicSetEdcaParm(pAd, &ie_list->EdcaParm); } /* copy QOS related information */ NdisMoveMemory(&pAd->CommonCfg.APQbssLoad, &ie_list->QbssLoad, sizeof(QBSS_LOAD_PARM)); NdisMoveMemory(&pAd->CommonCfg.APQosCapability, &ie_list->QosCapability, sizeof(QOS_CAPABILITY_PARM)); #ifdef DOT11_N_SUPPORT #ifdef DOT11N_DRAFT3 /* 2009: PF#1: 20/40 Coexistence in 2.4 GHz Band When AP changes "STA Channel Width" and "Secondary Channel Offset" fields of HT Operation Element in the Beacon to 0 */ if ((ie_list->AddHtInfoLen != 0) && INFRA_ON(pAd) && pAd->CommonCfg.Channel <= 14) { BOOLEAN bChangeBW = FALSE; /* 1) HT Information 2) Secondary Channel Offset Element 40 -> 20 case */ if (pAd->CommonCfg.BBPCurrentBW == BW_40) { if (((ie_list->AddHtInfo.AddHtInfo.ExtChanOffset == EXTCHA_NONE) && (ie_list->AddHtInfo.AddHtInfo.RecomWidth == 0)) ||(ie_list->NewExtChannelOffset==0x0) ) { pAd->StaActive.SupportedHtPhy.ChannelWidth = BW_20; pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.BW = 0; { bChangeBW = TRUE; pAd->CommonCfg.CentralChannel = pAd->CommonCfg.Channel; DBGPRINT(RT_DEBUG_TRACE, ("FallBack from 40MHz to 20MHz(CtrlCh=%d, CentralCh=%d)\n", pAd->CommonCfg.Channel, pAd->CommonCfg.CentralChannel)); CntlChannelWidth(pAd, pAd->CommonCfg.Channel, pAd->CommonCfg.CentralChannel, BW_20, 0); } } } /* 20 -> 40 case 1.) Supported Channel Width Set Field of the HT Capabilities element of both STAs is set to a non-zero 2.) Secondary Channel Offset field is SCA or SCB 3.) 40MHzRegulatoryClass is TRUE (not implement it) */ else if (((pAd->CommonCfg.BBPCurrentBW == BW_20) ||(ie_list->NewExtChannelOffset!=0x0)) && (pAd->CommonCfg.DesiredHtPhy.ChannelWidth != BW_20) ) { if ((ie_list->AddHtInfo.AddHtInfo.ExtChanOffset != EXTCHA_NONE) && (ie_list->AddHtInfo.AddHtInfo.RecomWidth == 1) && (ie_list->HtCapabilityLen>0) && (ie_list->HtCapability.HtCapInfo.ChannelWidth == 1) ) { { pAd->CommonCfg.CentralChannel = get_cent_ch_by_htinfo(pAd, &ie_list->AddHtInfo, &ie_list->HtCapability); if (pAd->CommonCfg.CentralChannel != ie_list->AddHtInfo.ControlChan) bChangeBW = TRUE; if (bChangeBW) { pAd->CommonCfg.Channel = ie_list->AddHtInfo.ControlChan; pAd->StaActive.SupportedHtPhy.ChannelWidth = BW_40; DBGPRINT(RT_DEBUG_TRACE, ("FallBack from 20MHz to 40MHz(CtrlCh=%d, CentralCh=%d)\n", pAd->CommonCfg.Channel, pAd->CommonCfg.CentralChannel)); CntlChannelWidth(pAd, pAd->CommonCfg.Channel, pAd->CommonCfg.CentralChannel, BW_40, ie_list->AddHtInfo.AddHtInfo.ExtChanOffset); pAd->MacTab.Content[BSSID_WCID].HTPhyMode.field.BW = 1; } } } } if (bChangeBW) { pAd->CommonCfg.BSSCoexist2040.word = 0; TriEventInit(pAd); BuildEffectedChannelList(pAd); } } #endif /* DOT11N_DRAFT3 */ #endif /* DOT11_N_SUPPORT */ } /* only INFRASTRUCTURE mode support power-saving feature */ if ((INFRA_ON(pAd) && (RtmpPktPmBitCheck(pAd) == TRUE)) || (pAd->CommonCfg.bAPSDForcePowerSave)) { UCHAR FreeNumber; /* 1. AP has backlogged unicast-to-me frame, stay AWAKE, send PSPOLL 2. AP has backlogged broadcast/multicast frame and we want those frames, stay AWAKE 3. we have outgoing frames in TxRing or MgmtRing, better stay AWAKE 4. Psm change to PWR_SAVE, but AP not been informed yet, we better stay AWAKE 5. otherwise, put PHY back to sleep to save battery. */ if (ie_list->MessageToMe) { #ifdef PCIE_PS_SUPPORT if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE)) { /* Restore to correct BBP R3 value */ if (pAd->Antenna.field.RxPath > 1) RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, pAd->StaCfg.BBPR3); /* Turn clk to 80Mhz. */ } #endif /* PCIE_PS_SUPPORT */ #ifdef UAPSD_SUPPORT if (pAd->StaCfg.UapsdInfo.bAPSDCapable && pAd->CommonCfg.APEdcaParm.bAPSDCapable && pAd->CommonCfg.bAPSDAC_BE && pAd->CommonCfg.bAPSDAC_BK && pAd->CommonCfg.bAPSDAC_VI && pAd->CommonCfg.bAPSDAC_VO) { pAd->CommonCfg.bNeedSendTriggerFrame = TRUE; } else #endif /* UAPSD_SUPPORT */ { if (pAd->StaCfg.WindowsBatteryPowerMode == Ndis802_11PowerModeFast_PSP) { /* wake up and send a NULL frame with PM = 0 to the AP */ RTMP_SET_PSM_BIT(pAd, PWR_ACTIVE); RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) ? TRUE:FALSE), PWR_ACTIVE); } else { /* use PS-Poll to get any buffered packet */ RTMP_PS_POLL_ENQUEUE(pAd); } } } else if (ie_list->BcastFlag && (ie_list->DtimCount == 0) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM)) { #ifdef PCIE_PS_SUPPORT if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE)) { if (pAd->Antenna.field.RxPath > 1) RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, pAd->StaCfg.BBPR3); } #endif /* PCIE_PS_SUPPORT */ } else if ((pAd->TxSwQueue[QID_AC_BK].Number != 0) || (pAd->TxSwQueue[QID_AC_BE].Number != 0) || (pAd->TxSwQueue[QID_AC_VI].Number != 0) || (pAd->TxSwQueue[QID_AC_VO].Number != 0) || (RTMPFreeTXDRequest(pAd, QID_AC_BK, TX_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS) || (RTMPFreeTXDRequest(pAd, QID_AC_BE, TX_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS) || (RTMPFreeTXDRequest(pAd, QID_AC_VI, TX_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS) || (RTMPFreeTXDRequest(pAd, QID_AC_VO, TX_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS) || (RTMPFreeTXDRequest(pAd, QID_MGMT, MGMT_RING_SIZE - 1, &FreeNumber) != NDIS_STATUS_SUCCESS)) { /* TODO: consider scheduled HCCA. might not be proper to use traditional DTIM-based power-saving scheme */ /* can we cheat here (i.e. just check MGMT & AC_BE) for better performance? */ #ifdef PCIE_PS_SUPPORT if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_ADVANCE_POWER_SAVE_PCIE_DEVICE)) { if (pAd->Antenna.field.RxPath > 1) RTMP_BBP_IO_WRITE8_BY_REG_ID(pAd, BBP_R3, pAd->StaCfg.BBPR3); } #endif /* PCIE_PS_SUPPORT */ } else { if ((pAd->CommonCfg.bACMAPSDTr[QID_AC_VO]) || (pAd->CommonCfg.bACMAPSDTr[QID_AC_VI]) || (pAd->CommonCfg.bACMAPSDTr[QID_AC_BK]) || (pAd->CommonCfg.bACMAPSDTr[QID_AC_BE]) ) { } else { USHORT NextDtim = ie_list->DtimCount; if (NextDtim == 0) NextDtim = ie_list->DtimPeriod; TbttNumToNextWakeUp = pAd->StaCfg.DefaultListenCount; if (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_RECEIVE_DTIM) && (TbttNumToNextWakeUp > NextDtim)) TbttNumToNextWakeUp = NextDtim; if (!OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_DOZE)) { /* Set a flag to go to sleep . Then after parse this RxDoneInterrupt, will go to sleep mode. */ pAd->ThisTbttNumToNextWakeUp = TbttNumToNextWakeUp; AsicSleepThenAutoWakeup(pAd, pAd->ThisTbttNumToNextWakeUp); } } } } } /* not my BSSID, ignore it */ } /* sanity check fail, ignore this frame */ goto LabelOK; LabelErr: DBGPRINT(RT_DEBUG_ERROR, ("%s: Allocate memory fail!!!\n", __FUNCTION__)); LabelOK: if (VarIE != NULL) os_free_mem(NULL, VarIE); if (ie_list != NULL) os_free_mem(NULL, ie_list); return; } /* ========================================================================== Description: Receive PROBE REQ from remote peer when operating in IBSS mode ========================================================================== */ VOID PeerProbeReqAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { UCHAR Addr2[MAC_ADDR_LEN]; CHAR Ssid[MAX_LEN_OF_SSID]; UCHAR SsidLen; #ifdef DOT11_N_SUPPORT UCHAR HtLen, AddHtLen, NewExtLen; #endif /* DOT11_N_SUPPORT */ HEADER_802_11 ProbeRspHdr; NDIS_STATUS NStatus; PUCHAR pOutBuffer = NULL; ULONG FrameLen = 0; LARGE_INTEGER FakeTimestamp; UCHAR DsLen = 1, IbssLen = 2; UCHAR LocalErpIe[3] = {IE_ERP, 1, 0}; BOOLEAN Privacy; USHORT CapabilityInfo; if (! ADHOC_ON(pAd)) return; if (PeerProbeReqSanity(pAd, Elem->Msg, Elem->MsgLen, Addr2, Ssid, &SsidLen, NULL)) { if ((SsidLen == 0) || SSID_EQUAL(Ssid, SsidLen, pAd->CommonCfg.Ssid, pAd->CommonCfg.SsidLen)) { /* allocate and send out ProbeRsp frame */ NStatus = MlmeAllocateMemory(pAd, &pOutBuffer); /* Get an unused nonpaged memory */ if (NStatus != NDIS_STATUS_SUCCESS) return; MgtMacHeaderInit(pAd, &ProbeRspHdr, SUBTYPE_PROBE_RSP, 0, Addr2, pAd->CommonCfg.Bssid); Privacy = (pAd->StaCfg.WepStatus == Ndis802_11Encryption1Enabled) || (pAd->StaCfg.WepStatus == Ndis802_11Encryption2Enabled) || (pAd->StaCfg.WepStatus == Ndis802_11Encryption3Enabled); CapabilityInfo = CAP_GENERATE(0, 1, Privacy, (pAd->CommonCfg.TxPreamble == Rt802_11PreambleShort), 0, 0); MakeOutgoingFrame(pOutBuffer, &FrameLen, sizeof(HEADER_802_11), &ProbeRspHdr, TIMESTAMP_LEN, &FakeTimestamp, 2, &pAd->CommonCfg.BeaconPeriod, 2, &CapabilityInfo, 1, &SsidIe, 1, &pAd->CommonCfg.SsidLen, pAd->CommonCfg.SsidLen, pAd->CommonCfg.Ssid, 1, &SupRateIe, 1, &pAd->StaActive.SupRateLen, pAd->StaActive.SupRateLen, pAd->StaActive.SupRate, 1, &DsIe, 1, &DsLen, 1, &pAd->CommonCfg.Channel, 1, &IbssIe, 1, &IbssLen, 2, &pAd->StaActive.AtimWin, END_OF_ARGS); if (pAd->StaActive.ExtRateLen) { ULONG tmp; MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp, 3, LocalErpIe, 1, &ExtRateIe, 1, &pAd->StaActive.ExtRateLen, pAd->StaActive.ExtRateLen, &pAd->StaActive.ExtRate, END_OF_ARGS); FrameLen += tmp; } /* Modify by Eddy, support WPA2PSK in Adhoc mode */ if ((pAd->StaCfg.AuthMode == Ndis802_11AuthModeWPANone) ) { ULONG tmp; UCHAR RSNIe = IE_WPA; MakeOutgoingFrame(pOutBuffer + FrameLen, &tmp, 1, &RSNIe, 1, &pAd->StaCfg.RSNIE_Len, pAd->StaCfg.RSNIE_Len, pAd->StaCfg.RSN_IE, END_OF_ARGS); FrameLen += tmp; } #ifdef DOT11_N_SUPPORT if (WMODE_CAP_N(pAd->CommonCfg.PhyMode)) { ULONG TmpLen; USHORT epigram_ie_len; UCHAR BROADCOM[4] = {0x0, 0x90, 0x4c, 0x33}; HtLen = sizeof(pAd->CommonCfg.HtCapability); AddHtLen = sizeof(pAd->CommonCfg.AddHTInfo); NewExtLen = 1; /* New extension channel offset IE is included in Beacon, Probe Rsp or channel Switch Announcement Frame */ if (pAd->bBroadComHT == TRUE) { epigram_ie_len = pAd->MlmeAux.HtCapabilityLen + 4; MakeOutgoingFrame(pOutBuffer + FrameLen, &TmpLen, 1, &WpaIe, 1, &epigram_ie_len, 4, &BROADCOM[0], pAd->MlmeAux.HtCapabilityLen, &pAd->MlmeAux.HtCapability, END_OF_ARGS); } else { MakeOutgoingFrame(pOutBuffer + FrameLen, &TmpLen, 1, &HtCapIe, 1, &HtLen, sizeof(HT_CAPABILITY_IE), &pAd->CommonCfg.HtCapability, 1, &AddHtInfoIe, 1, &AddHtLen, sizeof(ADD_HT_INFO_IE), &pAd->CommonCfg.AddHTInfo, END_OF_ARGS); } FrameLen += TmpLen; } #endif /* DOT11_N_SUPPORT */ MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen); MlmeFreeMemory(pAd, pOutBuffer); } } } VOID BeaconTimeoutAtJoinAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { USHORT Status; DBGPRINT(RT_DEBUG_TRACE, ("SYNC - BeaconTimeoutAtJoinAction\n")); pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE; Status = MLME_REJ_TIMEOUT; MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_JOIN_CONF, 2, &Status, 0); } /* ========================================================================== Description: Scan timeout procedure. basically add channel index by 1 and rescan ========================================================================== */ VOID ScanTimeoutAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { #ifdef RTMP_MAC_USB /* To prevent data lost. Send an NULL data with turned PSM bit on to current associated AP when SCAN in the channel where associated AP located. */ if ((pAd->CommonCfg.Channel == pAd->MlmeAux.Channel) && (pAd->MlmeAux.ScanType == SCAN_ACTIVE) && (INFRA_ON(pAd)) && OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED) ) { RTMPSendNullFrame(pAd, pAd->CommonCfg.TxRate, (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_WMM_INUSED) ? TRUE:FALSE), PWR_SAVE); } #endif /* RTMP_MAC_USB */ if (pAd->StaCfg.bFastConnect && !pAd->StaCfg.bNotFirstScan) { pAd->MlmeAux.Channel = 0; pAd->StaCfg.bNotFirstScan = TRUE; } else { pAd->MlmeAux.Channel = NextChannel(pAd, pAd->MlmeAux.Channel); } /* Only one channel scanned for CISCO beacon request */ if ((pAd->MlmeAux.ScanType == SCAN_CISCO_ACTIVE) || (pAd->MlmeAux.ScanType == SCAN_CISCO_PASSIVE) || (pAd->MlmeAux.ScanType == SCAN_CISCO_NOISE) || (pAd->MlmeAux.ScanType == SCAN_CISCO_CHANNEL_LOAD)) pAd->MlmeAux.Channel = 0; /* this routine will stop if pAd->MlmeAux.Channel == 0 */ ScanNextChannel(pAd, OPMODE_STA); } /* ========================================================================== Description: ========================================================================== */ VOID InvalidStateWhenScan( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { USHORT Status; if (Elem->MsgType != MT2_MLME_SCAN_REQ) DBGPRINT(RT_DEBUG_TRACE, ("AYNC - InvalidStateWhenScan(state=%ld). Reset SYNC machine\n", pAd->Mlme.SyncMachine.CurrState)); else DBGPRINT(RT_DEBUG_TRACE, ("AYNC - Already in scanning, do nothing here.(state=%ld). \n", pAd->Mlme.SyncMachine.CurrState)); if (Elem->MsgType != MT2_MLME_SCAN_REQ) { pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE; Status = MLME_STATE_MACHINE_REJECT; MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_SCAN_CONF, 2, &Status, 0); } } /* ========================================================================== Description: ========================================================================== */ VOID InvalidStateWhenJoin( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { USHORT Status; DBGPRINT(RT_DEBUG_TRACE, ("InvalidStateWhenJoin(state=%ld, msg=%ld). Reset SYNC machine\n", pAd->Mlme.SyncMachine.CurrState, Elem->MsgType)); if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS)) { RTMPResumeMsduTransmission(pAd); } pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE; Status = MLME_STATE_MACHINE_REJECT; MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_JOIN_CONF, 2, &Status, 0); } /* ========================================================================== Description: ========================================================================== */ VOID InvalidStateWhenStart( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { USHORT Status; DBGPRINT(RT_DEBUG_TRACE, ("InvalidStateWhenStart(state=%ld). Reset SYNC machine\n", pAd->Mlme.SyncMachine.CurrState)); pAd->Mlme.SyncMachine.CurrState = SYNC_IDLE; Status = MLME_STATE_MACHINE_REJECT; MlmeEnqueue(pAd, MLME_CNTL_STATE_MACHINE, MT2_START_CONF, 2, &Status, 0); } /* ========================================================================== Description: IRQL = DISPATCH_LEVEL ========================================================================== */ VOID EnqueuePsPoll( IN PRTMP_ADAPTER pAd) { #ifdef RALINK_ATE if (ATE_ON(pAd)) { return; } #endif /* RALINK_ATE */ if (pAd->StaCfg.WindowsPowerMode == Ndis802_11PowerModeLegacy_PSP) pAd->PsPollFrame.FC.PwrMgmt = PWR_SAVE; MiniportMMRequest(pAd, 0, (PUCHAR)&pAd->PsPollFrame, sizeof(PSPOLL_FRAME)); #ifdef RTMP_MAC_USB /* Keep Waking up */ if (pAd->CountDowntoPsm == 0) pAd->CountDowntoPsm = 2; /* 100 ms; stay awake 200ms at most, average will be 1xx ms */ #endif /* RTMP_MAC_USB */ } /* ========================================================================== Description: ========================================================================== */ VOID EnqueueProbeRequest( IN PRTMP_ADAPTER pAd) { NDIS_STATUS NState; PUCHAR pOutBuffer; ULONG FrameLen = 0; HEADER_802_11 Hdr80211; DBGPRINT(RT_DEBUG_TRACE, ("force out a ProbeRequest ...\n")); NState = MlmeAllocateMemory(pAd, &pOutBuffer); /* Get an unused nonpaged memory */ if (NState == NDIS_STATUS_SUCCESS) { MgtMacHeaderInit(pAd, &Hdr80211, SUBTYPE_PROBE_REQ, 0, BROADCAST_ADDR, BROADCAST_ADDR); /* this ProbeRequest explicitly specify SSID to reduce unwanted ProbeResponse */ MakeOutgoingFrame(pOutBuffer, &FrameLen, sizeof(HEADER_802_11), &Hdr80211, 1, &SsidIe, 1, &pAd->CommonCfg.SsidLen, pAd->CommonCfg.SsidLen, pAd->CommonCfg.Ssid, 1, &SupRateIe, 1, &pAd->StaActive.SupRateLen, pAd->StaActive.SupRateLen, pAd->StaActive.SupRate, END_OF_ARGS); MiniportMMRequest(pAd, 0, pOutBuffer, FrameLen); MlmeFreeMemory(pAd, pOutBuffer); } } #ifdef DOT11_N_SUPPORT #ifdef DOT11N_DRAFT3 VOID BuildEffectedChannelList( IN PRTMP_ADAPTER pAd) { UCHAR EChannel[11]; UCHAR i, j, k; UCHAR UpperChannel = 0, LowerChannel = 0; RTMPZeroMemory(EChannel, 11); DBGPRINT(RT_DEBUG_TRACE, ("BuildEffectedChannelList:CtrlCh=%d,CentCh=%d,AuxCtrlCh=%d,AuxExtCh=%d\n", pAd->CommonCfg.Channel, pAd->CommonCfg.CentralChannel, pAd->MlmeAux.AddHtInfo.ControlChan, pAd->MlmeAux.AddHtInfo.AddHtInfo.ExtChanOffset)); /* 802.11n D4 11.14.3.3: If no secondary channel has been selected, all channels in the frequency band shall be scanned. */ { for (k = 0;k < pAd->ChannelListNum;k++) { if (pAd->ChannelList[k].Channel <=14 ) pAd->ChannelList[k].bEffectedChannel = TRUE; } return; } i = 0; /* Find upper and lower channel according to 40MHz current operation. */ if (pAd->CommonCfg.CentralChannel < pAd->CommonCfg.Channel) { UpperChannel = pAd->CommonCfg.Channel; LowerChannel = pAd->CommonCfg.CentralChannel-2; } else if (pAd->CommonCfg.CentralChannel > pAd->CommonCfg.Channel) { UpperChannel = pAd->CommonCfg.CentralChannel+2; LowerChannel = pAd->CommonCfg.Channel; } else { DBGPRINT(RT_DEBUG_TRACE, ("LinkUP 20MHz . No Effected Channel \n")); /* Now operating in 20MHz, doesn't find 40MHz effected channels */ return; } DeleteEffectedChannelList(pAd); DBGPRINT(RT_DEBUG_TRACE, ("BuildEffectedChannelList!LowerChannel ~ UpperChannel; %d ~ %d \n", LowerChannel, UpperChannel)); /* Find all channels that are below lower channel.. */ if (LowerChannel > 1) { EChannel[0] = LowerChannel - 1; i = 1; if (LowerChannel > 2) { EChannel[1] = LowerChannel - 2; i = 2; if (LowerChannel > 3) { EChannel[2] = LowerChannel - 3; i = 3; } } } /* Find all channels that are between lower channel and upper channel. */ for (k = LowerChannel;k <= UpperChannel;k++) { EChannel[i] = k; i++; } /* Find all channels that are above upper channel.. */ if (UpperChannel < 14) { EChannel[i] = UpperChannel + 1; i++; if (UpperChannel < 13) { EChannel[i] = UpperChannel + 2; i++; if (UpperChannel < 12) { EChannel[i] = UpperChannel + 3; i++; } } } /* Total i channels are effected channels. Now find corresponding channel in ChannelList array. Then set its bEffectedChannel= TRUE */ for (j = 0;j < i;j++) { for (k = 0;k < pAd->ChannelListNum;k++) { if (pAd->ChannelList[k].Channel == EChannel[j]) { pAd->ChannelList[k].bEffectedChannel = TRUE; DBGPRINT(RT_DEBUG_TRACE,(" EffectedChannel[%d]( =%d)\n", k, EChannel[j])); break; } } } } VOID DeleteEffectedChannelList( IN PRTMP_ADAPTER pAd) { UCHAR i; /*Clear all bEffectedChannel in ChannelList array. */ for (i = 0; i < pAd->ChannelListNum; i++) { pAd->ChannelList[i].bEffectedChannel = FALSE; } } /* ======================================================================== Routine Description: Control Primary&Central Channel, ChannelWidth and Second Channel Offset Arguments: pAd Pointer to our adapter PrimaryChannel Primary Channel CentralChannel Central Channel ChannelWidth BW_20 or BW_40 SecondaryChannelOffset EXTCHA_NONE, EXTCHA_ABOVE and EXTCHA_BELOW Return Value: None Note: ======================================================================== */ VOID CntlChannelWidth( IN PRTMP_ADAPTER pAd, IN UCHAR prim_ch, IN UCHAR cent_ch, IN UCHAR ch_bw, IN UCHAR sec_ch_offset) { UCHAR rf_channel = 0, rf_bw; INT32 ext_ch; DBGPRINT(RT_DEBUG_TRACE, ("%s: PrimaryChannel[%d] \n",__FUNCTION__,prim_ch)); DBGPRINT(RT_DEBUG_TRACE, ("%s: CentralChannel[%d] \n",__FUNCTION__,cent_ch)); DBGPRINT(RT_DEBUG_TRACE, ("%s: ChannelWidth[%d] \n",__FUNCTION__,ch_bw)); DBGPRINT(RT_DEBUG_TRACE, ("%s: SecondaryChannelOffset[%d] \n",__FUNCTION__,sec_ch_offset)); #ifdef DOT11_N_SUPPORT /*Change to AP channel */ if (ch_bw == BW_40) { if(sec_ch_offset == EXTCHA_ABOVE) { rf_bw = BW_40; ext_ch = EXTCHA_ABOVE; rf_channel = cent_ch; } else if (sec_ch_offset == EXTCHA_BELOW) { rf_bw = BW_40; ext_ch = EXTCHA_BELOW; rf_channel = cent_ch; } } else #endif /* DOT11_N_SUPPORT */ { rf_bw = BW_20; ext_ch = EXTCHA_NONE; rf_channel = prim_ch; } if (rf_channel != 0) { rtmp_bbp_set_bw(pAd, rf_bw); /* Tx/ RX : control channel setting */ rtmp_bbp_set_ctrlch(pAd, ext_ch); rtmp_mac_set_ctrlch(pAd, ext_ch); AsicSwitchChannel(pAd, rf_channel, FALSE); AsicLockChannel(pAd, rf_channel); #ifdef RT28xx RT28xx_ch_tunning(pAd, rf_bw); #endif /* RT28xx */ DBGPRINT(RT_DEBUG_TRACE, ("!!!40MHz Lower !!! Control Channel at Below. Central = %d \n", pAd->CommonCfg.CentralChannel )); rtmp_bbp_get_agc(pAd, &pAd->BbpTuning.R66CurrentValue, RX_CHAIN_0); } } #endif /* DOT11N_DRAFT3 */ #endif /* DOT11_N_SUPPORT */ /* ========================================================================== Description: MLME Cancel the SCAN req state machine procedure ========================================================================== */ VOID ScanCnclAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { BOOLEAN Cancelled; RTMPCancelTimer(&pAd->MlmeAux.ScanTimer, &Cancelled); pAd->MlmeAux.Channel = 0; ScanNextChannel(pAd, OPMODE_STA); return; }
8996d240bfa40c94108e94690556033a6752b474
8a6b9cdf1c2e6e8b62d5c7a30f87105c9822ab22
/tontec_35_mz61581.h
b07da59a4386e80bfc7814730d0b302ade3e70c7
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
juj/fbcp-ili9341
605c71f9a7bcb4daf4da30777ceb8b089a0bb2e5
45e77fe63cda77e9636c9f23225313a458e55377
refs/heads/master
2023-08-11T14:10:25.911373
2022-11-16T11:07:53
2022-11-16T11:07:53
111,223,550
1,388
249
MIT
2023-01-30T13:53:30
2017-11-18T17:09:15
C++
UTF-8
C
false
false
280
h
tontec_35_mz61581.h
#pragma once #ifdef TONTEC_MZ61581 #if !defined(GPIO_TFT_DATA_CONTROL) #define GPIO_TFT_DATA_CONTROL 25 #endif #if !defined(GPIO_TFT_RESET_PIN) #define GPIO_TFT_RESET_PIN 15 #endif #if !defined(GPIO_TFT_BACKLIGHT) #define GPIO_TFT_BACKLIGHT 18 #endif #endif
20e090a689776687a24dbab0b944d142a605b109
7c857119fe1505b1d80d6e62969661c06dc1a2f4
/rEFIt_UEFI/Platform/Console.h
8b098902e108f0ba3cf24cf7cfd322c5a58bc702
[ "BSD-2-Clause" ]
permissive
CloverHackyColor/CloverBootloader
7042ca7dd6b513d22be591a295e49071ae1482ee
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
refs/heads/master
2023-08-30T22:14:34.590134
2023-08-27T19:14:02
2023-08-27T19:14:02
205,810,121
4,734
770
BSD-2-Clause
2023-09-03T12:41:33
2019-09-02T08:22:14
C
UTF-8
C
false
false
246
h
Console.h
/* * Console.h * * Created on: 16 Apr 2020 * Author: jief */ #ifndef PLATFORM_CONSOLE_H_ #define PLATFORM_CONSOLE_H_ EFI_STATUS InitializeConsoleSim (void); EFI_STATUS UninitializeConsoleSim (); #endif /* PLATFORM_CONSOLE_H_ */
052024531dbb87bb7bc6cd51c50b33864b14be81
a7856278e39f6030eacbb0680ca66b57e30ca06b
/generation/DirectX/um/dxdiag/um-dxdiag.h
52ef96fbbcf1dd2c4039fb38558d44271b2bf416
[ "MIT" ]
permissive
terrafx/terrafx.interop.windows
07f1ac52cbaea6c0f5f8f6147df7a8dd50345f49
fadce5a41fa5e6f0282e80e96f033d0a2c130991
refs/heads/main
2023-07-09T03:56:06.057946
2023-06-23T16:01:17
2023-06-23T16:01:17
192,857,891
208
46
MIT
2023-07-07T17:25:55
2019-06-20T05:58:46
C#
UTF-8
C
false
false
50
h
um-dxdiag.h
#include "..\..\..\TerraFX.h" #include <dxdiag.h>
b7998e3e0e888abbc260d78b5502a7412ed8e388
e5f4f37d941ceb8145d65f92028cc54658b1ac01
/Code/ThirdParty/glfw/tests/gamma.c
7419592f07d4a90be721aa57b8ac08466a0b58c3
[ "Zlib", "MIT" ]
permissive
ezEngine/ezEngine
19983d2733a5409fb2665c6c3a0a575dadcefb50
c46e3b4b2cd46798e4abb4938fbca281c054b039
refs/heads/dev
2023-09-06T02:17:28.152665
2023-09-05T18:25:43
2023-09-05T18:25:43
18,179,848
1,050
165
MIT
2023-09-14T21:44:39
2014-03-27T15:02:16
C++
UTF-8
C
false
false
5,651
c
gamma.c
//======================================================================== // Gamma correction test program // Copyright (c) Camilla Löwy <elmindreda@glfw.org> // // 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. // //======================================================================== // // This program is used to test the gamma correction functionality for // both full screen and windowed mode windows // //======================================================================== #include <glad/gl.h> #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> #define NK_IMPLEMENTATION #define NK_INCLUDE_FIXED_TYPES #define NK_INCLUDE_FONT_BAKING #define NK_INCLUDE_DEFAULT_FONT #define NK_INCLUDE_DEFAULT_ALLOCATOR #define NK_INCLUDE_VERTEX_BUFFER_OUTPUT #define NK_INCLUDE_STANDARD_VARARGS #define NK_BUTTON_TRIGGER_ON_RELEASE #include <nuklear.h> #define NK_GLFW_GL2_IMPLEMENTATION #include <nuklear_glfw_gl2.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static void error_callback(int error, const char* description) { fprintf(stderr, "Error: %s\n", description); } static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (action == GLFW_PRESS && key == GLFW_KEY_ESCAPE) glfwSetWindowShouldClose(window, GLFW_TRUE); } static void chart_ramp_array(struct nk_context* nk, struct nk_color color, int count, unsigned short int* values) { if (nk_chart_begin_colored(nk, NK_CHART_LINES, color, nk_rgb(255, 255, 255), count, 0, 65535)) { int i; for (i = 0; i < count; i++) { char buffer[1024]; if (nk_chart_push(nk, values[i])) { snprintf(buffer, sizeof(buffer), "#%u: %u (%0.5f) ", i, values[i], values[i] / 65535.f); nk_tooltip(nk, buffer); } } nk_chart_end(nk); } } int main(int argc, char** argv) { GLFWmonitor* monitor = NULL; GLFWwindow* window; GLFWgammaramp orig_ramp; struct nk_context* nk; struct nk_font_atlas* atlas; float gamma_value = 1.f; glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); monitor = glfwGetPrimaryMonitor(); glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE); window = glfwCreateWindow(800, 400, "Gamma Test", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } { const GLFWgammaramp* ramp = glfwGetGammaRamp(monitor); if (!ramp) { glfwTerminate(); exit(EXIT_FAILURE); } const size_t array_size = ramp->size * sizeof(short); orig_ramp.size = ramp->size; orig_ramp.red = malloc(array_size); orig_ramp.green = malloc(array_size); orig_ramp.blue = malloc(array_size); memcpy(orig_ramp.red, ramp->red, array_size); memcpy(orig_ramp.green, ramp->green, array_size); memcpy(orig_ramp.blue, ramp->blue, array_size); } glfwMakeContextCurrent(window); gladLoadGL(glfwGetProcAddress); glfwSwapInterval(1); nk = nk_glfw3_init(window, NK_GLFW3_INSTALL_CALLBACKS); nk_glfw3_font_stash_begin(&atlas); nk_glfw3_font_stash_end(); glfwSetKeyCallback(window, key_callback); while (!glfwWindowShouldClose(window)) { int width, height; struct nk_rect area; glfwGetWindowSize(window, &width, &height); area = nk_rect(0.f, 0.f, (float) width, (float) height); nk_window_set_bounds(nk, "", area); glClear(GL_COLOR_BUFFER_BIT); nk_glfw3_new_frame(); if (nk_begin(nk, "", area, 0)) { const GLFWgammaramp* ramp; nk_layout_row_dynamic(nk, 30, 3); if (nk_slider_float(nk, 0.1f, &gamma_value, 5.f, 0.1f)) glfwSetGamma(monitor, gamma_value); nk_labelf(nk, NK_TEXT_LEFT, "%0.1f", gamma_value); if (nk_button_label(nk, "Revert")) glfwSetGammaRamp(monitor, &orig_ramp); ramp = glfwGetGammaRamp(monitor); nk_layout_row_dynamic(nk, height - 60.f, 3); chart_ramp_array(nk, nk_rgb(255, 0, 0), ramp->size, ramp->red); chart_ramp_array(nk, nk_rgb(0, 255, 0), ramp->size, ramp->green); chart_ramp_array(nk, nk_rgb(0, 0, 255), ramp->size, ramp->blue); } nk_end(nk); nk_glfw3_render(NK_ANTI_ALIASING_ON); glfwSwapBuffers(window); glfwWaitEventsTimeout(1.0); } free(orig_ramp.red); free(orig_ramp.green); free(orig_ramp.blue); nk_glfw3_shutdown(); glfwTerminate(); exit(EXIT_SUCCESS); }
41ba18448d3f374b2dd76837758a79bdaf6d20fb
03b2c80dbc41e904b167d504666e27d798da5447
/src/array_adjust.h
ee84db01edd6c08d3adbb18c24ec4b818b2a052c
[ "Unlicense" ]
permissive
nptcl/npt
7c1570b497cdce0b8971cb445fbc04cb500232d3
aa714a2370ac9fa5348c2fc96159b40b9de3de07
refs/heads/master
2023-03-20T09:13:54.669118
2022-07-02T11:17:44
2022-07-02T11:17:44
171,985,905
160
12
Unlicense
2023-03-11T01:36:37
2019-02-22T03:11:34
C
UTF-8
C
false
false
304
h
array_adjust.h
#ifndef __ARRAY_ADJUST_HEADER__ #define __ARRAY_ADJUST_HEADER__ #include "typedef.h" #define array_adjust_array_ _n(array_adjust_array_) int array_adjust_array_(addr *ret, addr array, addr dimension, addr type, addr initial, addr contents, addr fillpointer, addr displaced, addr offset); #endif
26b87731f138e72101aafda6195c2f4a886d3b6c
e47e2263ca0b60d0c8327f74b4d4078deadea430
/tess-two/jni/com_googlecode_leptonica_android/src/prog/adaptmap_dark.c
5e561cba187144b7fe4a0a80bb86500ebbb04947
[ "Apache-2.0", "BSD-2-Clause", "CC-BY-2.5" ]
permissive
rmtheis/tess-two
43ed1bdcceee88df696efdee7c3965572ff2121f
ab4cab1bd9794aacb74162aff339daa921a68c3f
refs/heads/master
2023-03-10T08:27:42.539055
2022-03-17T11:21:24
2022-03-17T11:21:24
2,581,357
3,632
1,331
Apache-2.0
2019-10-20T00:51:50
2011-10-15T11:14:00
C
UTF-8
C
false
false
7,989
c
adaptmap_dark.c
/*====================================================================* - Copyright (C) 2001 Leptonica. 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. - - 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 ANY - 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. *====================================================================*/ /* * adaptmap_dark.c * * Demonstrates the effect of the fg threshold on adaptive mapping * and cleaning for images with dark and variable background. * * The example pages are text and image. For both, because the * background is both dark and variable, using a lower threshold * gives much better results. * * For text, cleaning the background to white after adaptively * remapping to make the background uniform is preferable. * The final cleaning step uses pixGammaTRC() where the white value * (here, 180) is set below the remapped gray value (here, 200). * * For the image, however, it is best to stop after remapping * the background. Going further and moving pixels near the * background color to white removes the details in the lighter * regions of the image. In practice, parts of a scanned page * that are image (as opposed to text) don't necessarily have * background pixels that should be white. These regions can be * protected by masks from operations, such as pixGammaTRC(), * where the white value is less than 255. * * This also tests some code useful for rendering: * * NUp display from pixa to pixa * * Interleaving of both pixa and pixacomp */ #include "string.h" #include "allheaders.h" void GenCleans(const char *fname, l_int32 *pindex, l_int32 thresh, L_BMF *bmf); l_int32 main(int argc, char **argv) { l_int32 index; L_BMF *bmf; PIXA *pixa1, *pixa2, *pixa3, *pixa4; PIXAC *pixac1, *pixac2, *pixac3; PROCNAME("adaptmap_dark"); bmf = bmfCreate(NULL, 10); index = 0; lept_mkdir("lept/adapt"); /* Using a variety of different thresholds */ GenCleans("cavalerie.29.jpg", &index, 80, bmf); GenCleans("cavalerie.29.jpg", &index, 60, bmf); GenCleans("cavalerie.29.jpg", &index, 40, bmf); GenCleans("cavalerie.11.jpg", &index, 80, bmf); GenCleans("cavalerie.11.jpg", &index, 60, bmf); GenCleans("cavalerie.11.jpg", &index, 40, bmf); /* Read the images and convert to a 4-up pixa */ pixa1 = convertToNUpPixa("/tmp/lept/adapt", "adapt_", 2, 2, 500, 6, 2, 0); /* Convert to pdf */ L_INFO("Writing to /tmp/lept/adapt/cleaning.pdf\n", procName); pixaConvertToPdf(pixa1, 100, 1.0, L_JPEG_ENCODE, 75, "Adaptive cleaning", "/tmp/lept/adapt/cleaning.pdf"); pixaDestroy(&pixa1); /* Test the pixac interleaving. Make two copies, * and interleave them: * (1) convert NUp 2 x 1 * (2) convert twice to pixac * (3) interleave the two copies * (4) convert back to pixa * (5) convert NUp 1 x 2 (result now is 2 x 2) * (6) output as pdf */ pixa1 = convertToNUpPixa("/tmp/lept/adapt", "adapt_", 2, 1, 500, 6, 2, 0); startTimer(); pixac1 = pixacompCreateFromPixa(pixa1, IFF_DEFAULT, L_CLONE); pixac2 = pixacompCreateFromPixa(pixa1, IFF_DEFAULT, L_CLONE); pixac3 = pixacompInterleave(pixac1, pixac2); pixa2 = pixaCreateFromPixacomp(pixac3, L_CLONE); pixa3 = pixaConvertToNUpPixa(pixa2, NULL, 1, 2, 1000, 6, 2, 0); fprintf(stderr, "Time with pixac interleaving = %7.3f sec\n", stopTimer()); L_INFO("Writing to /tmp/lept/adapt/cleaning2.pdf\n", procName); pixaConvertToPdf(pixa3, 100, 1.0, L_JPEG_ENCODE, 75, "Adaptive cleaning", "/tmp/lept/adapt/cleaning2.pdf"); pixaDestroy(&pixa1); pixaDestroy(&pixa2); pixaDestroy(&pixa3); pixacompDestroy(&pixac1); pixacompDestroy(&pixac2); pixacompDestroy(&pixac3); /* Test the pixa interleaving. Make two copies, * and interleave them: * (1) convert NUp 2 x 1 * (2) copy and interleave * (3) convert NUp 1 x 2 (result now is 2 x 2) * (4) output as pdf */ pixa1 = convertToNUpPixa("/tmp/lept/adapt", "adapt_", 2, 1, 500, 6, 2, 0); startTimer(); pixa2 = pixaCopy(pixa1, L_COPY_CLONE); pixa3 = pixaInterleave(pixa1, pixa2, L_CLONE); pixa4 = pixaConvertToNUpPixa(pixa3, NULL, 1, 2, 1000, 6, 2, 0); fprintf(stderr, "Time with pixa interleaving = %7.3f sec\n", stopTimer()); L_INFO("Writing to /tmp/lept/adapt/cleaning3.pdf\n", procName); pixaConvertToPdf(pixa4, 100, 1.0, L_JPEG_ENCODE, 75, "Adaptive cleaning", "/tmp/lept/adapt/cleaning3.pdf"); pixaDestroy(&pixa1); pixaDestroy(&pixa2); pixaDestroy(&pixa3); pixaDestroy(&pixa4); bmfDestroy(&bmf); return 0; } void GenCleans(const char *fname, l_int32 *pindex, l_int32 thresh, L_BMF *bmf) { l_int32 index, blackval, whiteval; char buf[256]; PIX *pix1, *pix2, *pix3, *pix4, *pix5; blackval = 70; whiteval = 180; index = *pindex; pix1 = pixRead(fname); snprintf(buf, sizeof(buf), "/tmp/lept/adapt/adapt_%03d.jpg", index++); pixWrite(buf, pix1, IFF_JFIF_JPEG); pix2 = pixBackgroundNorm(pix1, NULL, NULL, 10, 15, thresh, 25, 200, 2, 1); snprintf(buf, sizeof(buf), "Norm color: fg thresh = %d", thresh); fprintf(stderr, "%s\n", buf); pix3 = pixAddTextlines(pix2, bmf, buf, 0x00ff0000, L_ADD_BELOW); snprintf(buf, sizeof(buf), "/tmp/lept/adapt/adapt_%03d.jpg", index++); pixWrite(buf, pix3, IFF_JFIF_JPEG); pixDestroy(&pix3); pix3 = pixGammaTRC(NULL, pix2, 1.0, blackval, whiteval); snprintf(buf, sizeof(buf), "Clean color: fg thresh = %d", thresh); pix4 = pixAddSingleTextblock(pix3, bmf, buf, 0x00ff0000, L_ADD_BELOW, NULL); snprintf(buf, sizeof(buf), "/tmp/lept/adapt/adapt_%03d.jpg", index++); pixWrite(buf, pix4, IFF_JFIF_JPEG); pixDestroy(&pix2); pixDestroy(&pix3); pixDestroy(&pix4); pix2 = pixConvertRGBToGray(pix1, 0.33, 0.34, 0.33); pix3 = pixBackgroundNorm(pix2, NULL, NULL, 10, 15, thresh, 25, 200, 2, 1); pix4 = pixGammaTRC(NULL, pix3, 1.0, blackval, whiteval); snprintf(buf, sizeof(buf), "Clean gray: fg thresh = %d", thresh); pix5 = pixAddSingleTextblock(pix4, bmf, buf, 0x00ff0000, L_ADD_BELOW, NULL); snprintf(buf, sizeof(buf), "/tmp/lept/adapt/adapt_%03d.jpg", index++); pixWrite(buf, pix5, IFF_JFIF_JPEG); pixDestroy(&pix2); pixDestroy(&pix3); pixDestroy(&pix4); pixDestroy(&pix5); pixDestroy(&pix1); *pindex = index; return; }
2bb5c9bdec8498abb61d33417c57152bcc7f691d
8838eb997879add5759b6dfb23f9a646464e53ca
/src/arch/x86/include/asm/multiboot.h
ed1475afcd10e4365237ecf92f4a4f16663beacd
[ "BSD-2-Clause" ]
permissive
embox/embox
d6aacec876978522f01cdc4b8de37a668c6f4c80
98e3c06e33f3fdac10a29c069c20775568e0a6d1
refs/heads/master
2023-09-04T03:02:20.165042
2023-09-02T14:55:31
2023-09-02T14:55:31
33,078,138
1,087
325
BSD-2-Clause
2023-09-14T16:58:34
2015-03-29T15:27:48
C
UTF-8
C
false
false
5,170
h
multiboot.h
/** * @file * @brief the header for Multiboot * * @date 10.11.10 * @author Nikolay Korotky */ #ifndef X86_MULTIBOOT_H_ #define X86_MULTIBOOT_H_ /* The magic number for the Multiboot header. */ #define MULTIBOOT_HEADER_MAGIC 0x1BADB002 /* The magic number passed by a Multiboot-compliant boot loader. It's placed into EBX register by loader */ #define MULTIBOOT_BOOTLOADER_MAGIC 0x2BADB002 /* The flags for the Multiboot header. */ #define MULTIBOOT_MUSTKNOW 0x0000ffff /* Align all boot modules on page (4KB) boundaries. */ #define MULTIBOOT_PAGE_ALIGN 0x00000001 /* Must be provided memory information in multiboot_info structure */ #define MULTIBOOT_MEMORY_INFO 0x00000002 /* Must be provided information about the video mode table */ #define MULTIBOOT_VIDEO_INFO 0x00000004 /* If bit 16 in the ‘flags’ word is set, then the fields at offsets 12-28 in the Multiboot header are valid. * his information does not need to be provided if the kernel image is in elf format, * but it must be provided if the images is in a.out format or in some other format */ #define MULTIBOOT_AOUT_KLUDGE 0x00010000 #define MULTIBOOT_HEADER_FLAGS MULTIBOOT_MEMORY_INFO | MULTIBOOT_PAGE_ALIGN /* is there basic lower/upper memory information? */ #define MULTIBOOT_INFO_MEMORY 0x00000001 /* is there a boot device set? */ #define MULTIBOOT_INFO_BOOTDEV 0x00000002 /* is the command-line defined? */ #define MULTIBOOT_INFO_CMDLINE 0x00000004 /* are there modules to do something with? */ #define MULTIBOOT_INFO_MODS 0x00000008 /* These next two are mutually exclusive */ /* is there a symbol table loaded? */ #define MULTIBOOT_INFO_AOUT_SYMS 0x00000010 /* is there an ELF section header table? */ #define MULTIBOOT_INFO_ELF_SHDR 0X00000020 /* is there a full memory map? */ #define MULTIBOOT_INFO_MEM_MAP 0x00000040 /* Is there drive info? */ #define MULTIBOOT_INFO_DRIVE_INFO 0x00000080 /* Is there a config table? */ #define MULTIBOOT_INFO_CONFIG_TABLE 0x00000100 /* Is there a boot loader name? */ #define MULTIBOOT_INFO_BOOT_LOADER_NAME 0x00000200 /* Is there a APM table? */ #define MULTIBOOT_INFO_APM_TABLE 0x00000400 /* Is there video information? */ #define MULTIBOOT_INFO_VIDEO_INFO 0x00000800 #ifndef __ASSEMBLER__ #include <stdint.h> /* The Multiboot header. */ typedef struct multiboot_header { /* Must be MULTIBOOT_MAGIC */ uint32_t magic; /* Feature flags */ uint32_t flags; uint32_t checksum; /* These are only valid if MULTIBOOT_AOUT_KLUDGE is set. */ uint32_t header_addr; uint32_t load_addr; uint32_t load_end_addr; uint32_t bss_end_addr; uint32_t entry_addr; /* These are only valid if MULTIBOOT_VIDEO_INFO is set */ uint32_t mode_type; /* 32 */ uint32_t width; /* 36 */ uint32_t height; /* 40 */ uint32_t depth; /* 44 */ } multiboot_header_t; /* The symbol table for a.out. */ typedef struct aout_symbol_table { unsigned long tabsize; unsigned long strsize; unsigned long addr; unsigned long reserved; } aout_symbol_table_t; /* The section header table for ELF. */ typedef struct elf_section_header_table { unsigned long num; unsigned long size; unsigned long addr; unsigned long shndx; } elf_section_header_table_t; /* The Multiboot information. The boot loader passes this data structure to the embox in register EBX on entry. */ typedef struct multiboot_info { /* These flags indicate which parts of the multiboot_info are valid */ uint32_t flags; /* Lower/Upper memory installed in the machine. */ uint32_t mem_lower; uint32_t mem_upper; /* BIOS disk device the kernel was loaded from. */ uint32_t boot_device; /* Command-line for the OS kernel: a null-terminated ASCII string. */ uint32_t cmdline; /* List of boot modules loaded with the kernel. */ uint32_t mods_count; uint32_t mods_addr; /* Symbol information for a.out or ELF executables. */ union { aout_symbol_table_t aout_sym; elf_section_header_table_t elf_sec; } u; /* Memory map buffer. */ uint32_t mmap_length; uint32_t mmap_addr; /* Drive Info buffer */ uint32_t drives_length; uint32_t drives_addr; /* ROM configuration table */ uint32_t config_table; /* Boot Loader Name */ uint32_t boot_loader_name; /* APM table */ uint32_t apm_table; /* Video */ uint32_t vbe_control_info; uint32_t vbe_mode_info; uint16_t vbe_mode; uint16_t vbe_interface_seg; uint16_t vbe_interface_off; uint16_t vbe_interface_len; } multiboot_info_t; /* The module structure. */ typedef struct multiboot_module { unsigned long mod_start; unsigned long mod_end; unsigned long string; unsigned long reserved; } multiboot_module_t; /* The memory map. Be careful that the offset 0 is base_addr_low but no size. */ typedef struct multiboot_memory_map { unsigned long size; unsigned long base_addr_low; unsigned long base_addr_high; unsigned long length_low; unsigned long length_high; unsigned long type; } memory_map_t; #endif /* __ASSEMBLER__ */ #endif /* X86_MULTIBOOT_H_ */
07fcfdc1d859c18876d90bc270790f67a330f4f1
88bd66842df4e38167ed0d07e29f33040029931b
/notes/mit6.s081/docs/lec/l-coordination.c
214075d68d2aa179d5eac01540496119a6f44b20
[ "CC-BY-SA-4.0" ]
permissive
PiperLiu/CS-courses-notes
3855292f4e58eac24e559c0aedea00a334a260a1
78315802cb61800a607575e13a17bb5d4765471e
refs/heads/master
2022-05-30T01:23:28.878483
2022-05-11T03:35:50
2022-05-11T03:35:50
221,176,862
360
57
Apache-2.0
2021-09-26T15:57:23
2019-11-12T09:16:55
C++
UTF-8
C
false
false
1,369
c
l-coordination.c
// // uart.c // these functions replace uartputc() and uartintr() // static int tx_done; // has the UART finished sending? static int tx_chan; // &tx_chan is the "wait channel" // transmit buf[]. void uartwrite(char buf[], int n) { acquire(&uart_tx_lock); int i = 0; while(i < n){ while(tx_done == 0){ // UART is busy sending a character. // wait for it to interrupt. sleep(&tx_chan, &uart_tx_lock); } WriteReg(THR, buf[i]); i += 1; tx_done = 0; } release(&uart_tx_lock); } // handle a uart interrupt, raised because input has // arrived, or the uart is ready for more output, or // both. called from trap.c. void uartintr(void) { acquire(&uart_tx_lock); if(ReadReg(LSR) & LSR_TX_IDLE){ // UART finished transmitting; wake up any sending thread. tx_done = 1; wakeup(&tx_chan); } release(&uart_tx_lock); // read and process incoming characters. while(1){ int c = uartgetc(); if(c == -1) break; consoleintr(c); } } // // proc.c // // (this sleep() does not work correctly) // void broken_sleep(void *chan) { struct proc *p = myproc(); // Must acquire p->lock in order to // change p->state and then call sched. acquire(&p->lock); // Go to sleep. p->chan = chan; p->state = SLEEPING; sched(); // Tidy up. p->chan = 0; release(&p->lock); }
53a0d346f15809274c8c1b100b2ea32ba4dfc3de
07aeb5740a8dae36edf24e2686ff67e2959758fe
/programs/subprojects/doom/i_timer.h
9b3dbb8d105afcf42efb6a80ffbb89935002e9e3
[ "MIT" ]
permissive
codyd51/axle
59e992987bb871296aeadc69fc7244798090f3b1
96ae8852f15ad5c0a77c621c323ba47b4a7bdc69
refs/heads/paging-demo
2023-06-08T11:31:19.429032
2023-05-30T06:45:30
2023-05-30T06:45:30
58,590,685
597
61
MIT
2023-02-21T06:02:34
2016-05-11T23:41:08
C
UTF-8
C
false
false
1,038
h
i_timer.h
// // Copyright(C) 1993-1996 Id Software, Inc. // Copyright(C) 2005-2014 Simon Howard // // 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. // // DESCRIPTION: // System-specific timer interface // #ifndef __I_TIMER__ #define __I_TIMER__ #define TICRATE 35 // Called by D_DoomLoop, // returns current time in tics. int I_GetTime (void); // returns current time in ms int I_GetTimeMS (void); // Pause for a specified number of ms void I_Sleep(int ms); // Initialize timer void I_InitTimer(void); // Wait for vertical retrace or pause a bit. void I_WaitVBL(int count); #endif
d276afedc9b792c0196303f92cbc9568507efbda
e1d9c54e9925e30e388a255b53a93cccad0b94cb
/kubernetes/model/v1beta2_priority_level_configuration_status.c
78dfaa9f6cf60ecb0a0da683366d3b0576be39e2
[ "Apache-2.0", "curl" ]
permissive
kubernetes-client/c
dd4fd8095485c083e0f40f2b48159b1609a6141b
5ac5ff25e9809a92a48111b1f77574b6d040b711
refs/heads/master
2023-08-13T10:51:03.702497
2023-08-07T19:18:32
2023-08-07T19:18:32
247,958,425
127
47
Apache-2.0
2023-09-07T20:07:00
2020-03-17T11:59:05
C
UTF-8
C
false
false
4,157
c
v1beta2_priority_level_configuration_status.c
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "v1beta2_priority_level_configuration_status.h" v1beta2_priority_level_configuration_status_t *v1beta2_priority_level_configuration_status_create( list_t *conditions ) { v1beta2_priority_level_configuration_status_t *v1beta2_priority_level_configuration_status_local_var = malloc(sizeof(v1beta2_priority_level_configuration_status_t)); if (!v1beta2_priority_level_configuration_status_local_var) { return NULL; } v1beta2_priority_level_configuration_status_local_var->conditions = conditions; return v1beta2_priority_level_configuration_status_local_var; } void v1beta2_priority_level_configuration_status_free(v1beta2_priority_level_configuration_status_t *v1beta2_priority_level_configuration_status) { if(NULL == v1beta2_priority_level_configuration_status){ return ; } listEntry_t *listEntry; if (v1beta2_priority_level_configuration_status->conditions) { list_ForEach(listEntry, v1beta2_priority_level_configuration_status->conditions) { v1beta2_priority_level_configuration_condition_free(listEntry->data); } list_freeList(v1beta2_priority_level_configuration_status->conditions); v1beta2_priority_level_configuration_status->conditions = NULL; } free(v1beta2_priority_level_configuration_status); } cJSON *v1beta2_priority_level_configuration_status_convertToJSON(v1beta2_priority_level_configuration_status_t *v1beta2_priority_level_configuration_status) { cJSON *item = cJSON_CreateObject(); // v1beta2_priority_level_configuration_status->conditions if(v1beta2_priority_level_configuration_status->conditions) { cJSON *conditions = cJSON_AddArrayToObject(item, "conditions"); if(conditions == NULL) { goto fail; //nonprimitive container } listEntry_t *conditionsListEntry; if (v1beta2_priority_level_configuration_status->conditions) { list_ForEach(conditionsListEntry, v1beta2_priority_level_configuration_status->conditions) { cJSON *itemLocal = v1beta2_priority_level_configuration_condition_convertToJSON(conditionsListEntry->data); if(itemLocal == NULL) { goto fail; } cJSON_AddItemToArray(conditions, itemLocal); } } } return item; fail: if (item) { cJSON_Delete(item); } return NULL; } v1beta2_priority_level_configuration_status_t *v1beta2_priority_level_configuration_status_parseFromJSON(cJSON *v1beta2_priority_level_configuration_statusJSON){ v1beta2_priority_level_configuration_status_t *v1beta2_priority_level_configuration_status_local_var = NULL; // define the local list for v1beta2_priority_level_configuration_status->conditions list_t *conditionsList = NULL; // v1beta2_priority_level_configuration_status->conditions cJSON *conditions = cJSON_GetObjectItemCaseSensitive(v1beta2_priority_level_configuration_statusJSON, "conditions"); if (conditions) { cJSON *conditions_local_nonprimitive = NULL; if(!cJSON_IsArray(conditions)){ goto end; //nonprimitive container } conditionsList = list_createList(); cJSON_ArrayForEach(conditions_local_nonprimitive,conditions ) { if(!cJSON_IsObject(conditions_local_nonprimitive)){ goto end; } v1beta2_priority_level_configuration_condition_t *conditionsItem = v1beta2_priority_level_configuration_condition_parseFromJSON(conditions_local_nonprimitive); list_addElement(conditionsList, conditionsItem); } } v1beta2_priority_level_configuration_status_local_var = v1beta2_priority_level_configuration_status_create ( conditions ? conditionsList : NULL ); return v1beta2_priority_level_configuration_status_local_var; end: if (conditionsList) { listEntry_t *listEntry = NULL; list_ForEach(listEntry, conditionsList) { v1beta2_priority_level_configuration_condition_free(listEntry->data); listEntry->data = NULL; } list_freeList(conditionsList); conditionsList = NULL; } return NULL; }
355c15e74f0894b9e6811e1cbcb57e1096072195
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/devel/sdl12/files/SDL_sndioaudio.h
32c566ed93e5742a53442e75654b691e29a5afdb
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C
false
false
1,512
h
SDL_sndioaudio.h
/* * Copyright (c) 2008 Jacob Meuser <jakemsr@sdf.lonestar.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "SDL_config.h" #ifndef _SDL_sndioaudio_h #define _SDL_sndioaudio_h #include <sndio.h> #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the video functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* The stream descriptor for the audio device */ struct sio_hdl *hdl; /* The parent process id, to detect when application quits */ pid_t parent; /* Raw mixing buffer */ Uint8 *mixbuf; int mixlen; }; /* Old variable names */ #define stream (this->hidden->stream) #define parent (this->hidden->parent) #define mixbuf (this->hidden->mixbuf) #define mixlen (this->hidden->mixlen) #define hdl (this->hidden->hdl) #endif /* _SDL_sndioaudio_h */
70eef67091955fd2eccdcc78c77b81a7ebf55b27
e22fd36933c9114a9df1694e7a6274bf059de2a6
/third_party/acados/include/hpipm/include/hpipm_m_ocp_qp_ipm_hard.h
1c44acee2e849720a8959508383b717fec3fcc55
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
commaai/openpilot
66dfb7f31290bc8f58c9ead95d56697a52b45afb
a0b49d54222c52ff0112c402bc0e0d9262e77a66
refs/heads/master
2023-09-05T21:34:14.076796
2023-09-05T21:15:18
2023-09-05T21:15:18
74,627,617
46,071
9,878
MIT
2023-09-14T21:51:23
2016-11-24T01:33:30
Python
UTF-8
C
false
false
6,224
h
hpipm_m_ocp_qp_ipm_hard.h
/************************************************************************************************** * * * This file is part of HPIPM. * * * * HPIPM -- High-Performance Interior Point Method. * * Copyright (C) 2019 by Gianluca Frison. * * Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * * All rights reserved. * * * * The 2-Clause BSD License * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * * 1. Redistributions of source code must retain the above copyright notice, this * * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * * this list of conditions and the following disclaimer in the documentation * * and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * * * **************************************************************************************************/ #include <blasfeo_target.h> #include <blasfeo_common.h> #ifdef __cplusplus extern "C" { #endif struct m_ipm_hard_ocp_qp_workspace { struct d_ipm_hard_core_qp_workspace *core_workspace; struct blasfeo_dvec *dux; struct blasfeo_dvec *dpi; struct blasfeo_dvec *dt_lb; struct blasfeo_dvec *dt_lg; struct blasfeo_svec *sdux; // XXX struct blasfeo_svec *sdpi; // XXX struct blasfeo_dvec *res_g; // q-residuals struct blasfeo_dvec *res_b; // b-residuals struct blasfeo_dvec *res_d; // d-residuals XXX remove ??? struct blasfeo_dvec *res_d_lb; // d-residuals struct blasfeo_dvec *res_d_ub; // d-residuals struct blasfeo_dvec *res_d_lg; // d-residuals struct blasfeo_dvec *res_d_ug; // d-residuals struct blasfeo_dvec *res_m; // m-residuals struct blasfeo_dvec *res_m_lb; // m-residuals struct blasfeo_dvec *res_m_ub; // m-residuals struct blasfeo_dvec *res_m_lg; // m-residuals struct blasfeo_dvec *res_m_ug; // m-residuals struct blasfeo_svec *sres_g; // q-residuals // XXX struct blasfeo_svec *sres_b; // b-residuals // XXX struct blasfeo_dvec *Qx_lb; // hessian update struct blasfeo_dvec *Qx_lg; // hessian update struct blasfeo_dvec *qx_lb; // gradient update struct blasfeo_dvec *qx_lg; // gradient update struct blasfeo_svec *sQx_lb; // hessian update // XXX struct blasfeo_svec *sQx_lg; // hessian update // XXX struct blasfeo_svec *sqx_lb; // gradient update // XXX struct blasfeo_svec *sqx_lg; // gradient update // XXX struct blasfeo_dvec *tmp_nbM; // work space of size nbM struct blasfeo_svec *tmp_nxM; // work space of size nxM // XXX struct blasfeo_dvec *tmp_ngM; // work space of size ngM struct blasfeo_svec *Pb; // Pb // XXX struct blasfeo_smat *L; // XXX struct blasfeo_smat *AL; // XXX struct blasfeo_svec *sSx; // scaling struct blasfeo_svec *sSi; // scaling inverted double *stat; // convergence statistics double res_mu; // mu-residual int iter; // iteration number int compute_Pb; int scale; }; struct m_ipm_hard_ocp_qp_arg { double alpha_min; // exit cond on step length double mu_max; // exit cond on duality measure double mu0; // initial value for duality measure int iter_max; // exit cond in iter number }; // hpipm_size_t m_memsize_ipm_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct m_ipm_hard_ocp_qp_arg *arg); // void m_create_ipm_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct m_ipm_hard_ocp_qp_arg *arg, struct m_ipm_hard_ocp_qp_workspace *ws, void *mem); // void m_solve_ipm_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct d_ocp_qp_sol *qp_sol, struct m_ipm_hard_ocp_qp_workspace *ws); // void m_solve_ipm2_hard_ocp_qp(struct d_ocp_qp *d_qp, struct s_ocp_qp *s_qp, struct d_ocp_qp_sol *qp_sol, struct m_ipm_hard_ocp_qp_workspace *ws); #ifdef __cplusplus } /* extern "C" */ #endif
4e3d39536bedf0344878f89c3c1f273c3e81df36
dae15b230f6a39e8451420b2dea61fb719f9ffdf
/src/ofp_ipsec_spd.c
1f72ab2b27500243430d4b247e71567fff8a2c5a
[ "BSD-3-Clause", "GPL-1.0-or-later" ]
permissive
OpenFastPath/ofp
2b97bbd152fd877cb8b2125128d6826c0f4491dd
6b48500af9752c7d51a290390751988759a8256d
refs/heads/master
2023-05-25T15:21:17.682339
2023-05-10T07:14:01
2023-05-10T11:01:16
37,121,923
367
146
BSD-3-Clause
2023-09-13T14:19:24
2015-06-09T09:08:43
C
UTF-8
C
false
false
11,729
c
ofp_ipsec_spd.c
/* * Copyright (c) 2018, Nokia * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <odp_api.h> #include "api/ofp_types.h" #include "api/ofp_pkt_processing.h" #include "api/ofp_log.h" #include "api/ofp_ipsec.h" #include "api/ofp_icmp.h" #include "ofpi_in.h" #include "ofpi_ip.h" #include "ofpi_shared_mem.h" #include "ofpi_ipsec_spd.h" #include "ofpi_ipsec_sad.h" struct ofp_ipsec_sp { ofp_ipsec_sp_param_t param; struct ofp_ipsec_sp *next_in_lookup; ofp_ipsec_sa_handle sa; /* user managed */ uint32_t refcount; int destroyed; struct ofp_ipsec_sp *next; }; struct ofp_ipsec_spd { odp_rwlock_t lock; struct ofp_ipsec_sp *sp_list; struct ofp_ipsec_sp *outbound_lookup_list; struct ofp_ipsec_sp *inbound_lookup_list; struct ofp_ipsec_sp *free_sp_list; }; struct ofp_ipsec_selector_values { uint32_t src_addr; uint32_t dst_addr; uint8_t ip_proto; }; #define SHM_NAME_IPSEC_SPD "ofp_ipsec_spd" static __thread struct ofp_ipsec_spd *shm; #define SHM_NAME_IPSEC_SP_TABLE "ofp_ipsec_sp_table" static __thread struct ofp_ipsec_sp *shm_sp_table; static struct ofp_ipsec_sp *sp_alloc(void) { struct ofp_ipsec_sp *sp; sp = shm->free_sp_list; if (sp) { shm->free_sp_list = sp->next; sp->refcount = 1; } return sp; } static void sp_free(struct ofp_ipsec_sp *sp) { sp->next = shm->free_sp_list; shm->free_sp_list = sp; } static void sp_ref(struct ofp_ipsec_sp *sp) { if (sp) sp->refcount++; } static void sp_unref(struct ofp_ipsec_sp *sp) { if (sp && --sp->refcount == 0) sp_free(sp); } void ofp_ipsec_sp_ref(struct ofp_ipsec_sp *sp) { odp_rwlock_write_lock(&shm->lock); sp_ref(sp); odp_rwlock_write_unlock(&shm->lock); } void ofp_ipsec_sp_unref(struct ofp_ipsec_sp *sp) { odp_rwlock_write_lock(&shm->lock); sp_unref(sp); odp_rwlock_write_unlock(&shm->lock); } static void ipsec_ntohl(uint32_t *val) { *val = odp_be_to_cpu_32(*val); } static void ipsec_htonl(uint32_t *val) { *val = odp_cpu_to_be_32(*val); } static uint64_t sp_table_size(uint32_t max_num_sp) { return max_num_sp * sizeof(struct ofp_ipsec_sp); } void ofp_ipsec_spd_init_prepare(uint32_t max_num_sp) { ofp_shared_memory_prealloc(SHM_NAME_IPSEC_SPD, sizeof(*shm)); ofp_shared_memory_prealloc(SHM_NAME_IPSEC_SP_TABLE, sp_table_size(max_num_sp)); } int ofp_ipsec_spd_init_global(uint32_t max_num_sp) { uint32_t n; shm = ofp_shared_memory_alloc(SHM_NAME_IPSEC_SPD, sizeof(*shm)); if (!shm) { OFP_ERR("Failed to allocate IPsec SPD shared memory"); return -1; } odp_rwlock_init(&shm->lock); shm->sp_list = NULL; shm->outbound_lookup_list = NULL; shm->inbound_lookup_list = NULL; shm->free_sp_list = NULL; shm_sp_table = ofp_shared_memory_alloc(SHM_NAME_IPSEC_SP_TABLE, sp_table_size(max_num_sp)); if (!shm_sp_table) { OFP_ERR("Failed to allocate IPsec SP table"); ofp_shared_memory_free(SHM_NAME_IPSEC_SPD); return -1; } for (n = 0; n < max_num_sp; n++) sp_free(&shm_sp_table[n]); return 0; } int ofp_ipsec_spd_init_local(void) { shm = ofp_shared_memory_lookup(SHM_NAME_IPSEC_SPD); if (!shm) { OFP_ERR("Failed to lookup IPsec SPD shared memory"); return -1; } shm_sp_table = ofp_shared_memory_lookup(SHM_NAME_IPSEC_SP_TABLE); if (!shm) { OFP_ERR("Failed to lookup IPsec SP table shared memory"); return -1; } return 0; } int ofp_ipsec_spd_term_global(void) { ofp_shared_memory_free(SHM_NAME_IPSEC_SPD); ofp_shared_memory_free(SHM_NAME_IPSEC_SP_TABLE); return 0; } static struct ofp_ipsec_sp *sp_find_by_id(uint32_t id) { struct ofp_ipsec_sp *sp = shm->sp_list; while (sp) { if (sp->param.id == id) { break; } sp = sp->next; } return sp; } struct ofp_ipsec_sp *ofp_ipsec_sp_find_by_id(uint32_t id) { struct ofp_ipsec_sp *sp; odp_rwlock_write_lock(&shm->lock); sp = sp_find_by_id(id); sp_ref(sp); odp_rwlock_write_unlock(&shm->lock); return sp; } ofp_ipsec_sp_handle ofp_ipsec_sp_first(void) { ofp_ipsec_sp_handle sp; odp_rwlock_write_lock(&shm->lock); sp = shm->sp_list; sp_ref(sp); odp_rwlock_write_unlock(&shm->lock); return sp; } ofp_ipsec_sp_handle ofp_ipsec_sp_next(ofp_ipsec_sp_handle sp) { ofp_ipsec_sp_handle next; odp_rwlock_write_lock(&shm->lock); next = sp->next; sp_ref(next); sp_unref(sp); odp_rwlock_write_unlock(&shm->lock); return next; } void ofp_ipsec_sp_get_info(ofp_ipsec_sp_handle sp, ofp_ipsec_sp_info_t *info) { odp_rwlock_read_lock(&shm->lock); if (sp->destroyed) info->status = OFP_IPSEC_SP_DESTROYED; else info->status = OFP_IPSEC_SP_ACTIVE; info->param = sp->param; /* * Convert addresses back to network byte order as expected by the API */ ipsec_htonl(&info->param.selectors.src_ipv4_range.first_addr.s_addr); ipsec_htonl(&info->param.selectors.src_ipv4_range.last_addr.s_addr); ipsec_htonl(&info->param.selectors.dst_ipv4_range.first_addr.s_addr); ipsec_htonl(&info->param.selectors.dst_ipv4_range.last_addr.s_addr); odp_rwlock_read_unlock(&shm->lock); } /* * Insert SP to the right place in the given lookup list based on priority. */ static void sp_insert(struct ofp_ipsec_sp **link, struct ofp_ipsec_sp *sp) { while (*link) { if ((*link)->param.priority >= sp->param.priority) break; link = &(*link)->next_in_lookup; } sp->next_in_lookup = *link; *link = sp; } void ofp_ipsec_sp_param_init(ofp_ipsec_sp_param_t *param) { memset(param, 0, sizeof(*param)); } struct ofp_ipsec_sp *ofp_ipsec_sp_add(const ofp_ipsec_sp_param_t *param) { struct ofp_ipsec_sp *sp = NULL; odp_rwlock_write_lock(&shm->lock); if (param->selectors.src_port_range.first_port != 0 || param->selectors.src_port_range.last_port != 0 || param->selectors.dst_port_range.first_port != 0 || param->selectors.dst_port_range.last_port != 0) { OFP_ERR("Port based IPsec selectors are not supported"); goto out; } if (param->selectors.type != OFP_IPSEC_SELECTOR_IPV4) { OFP_ERR("IPsec is not supported with IPv6"); goto out; } if (sp_find_by_id(param->id)) { OFP_ERR("IPsec SP with the same ID already exists"); goto out; } if (param->sa != OFP_IPSEC_SA_INVALID) { OFP_ERR("Binding IPsec SA to an SP is not supported as part" "of IPsec SP creation."); goto out; } sp = sp_alloc(); if (!sp) { OFP_ERR("Out of free IPsec SPs"); goto out; } sp->param = *param; sp->destroyed = 0; sp->sa = OFP_IPSEC_SA_INVALID; /* * Convert IPv4 addresses to host byte order here to avoid * the conversion in SP matching. */ ipsec_ntohl(&sp->param.selectors.src_ipv4_range.first_addr.s_addr); ipsec_ntohl(&sp->param.selectors.src_ipv4_range.last_addr.s_addr); ipsec_ntohl(&sp->param.selectors.dst_ipv4_range.first_addr.s_addr); ipsec_ntohl(&sp->param.selectors.dst_ipv4_range.last_addr.s_addr); sp->next = shm->sp_list; shm->sp_list = sp; /* * We already hold one reference ourselves since the SP is now part * of SPD. Increment refcount for the returned handle too. */ sp_ref(sp); out: odp_rwlock_write_unlock(&shm->lock); return sp; } int ofp_ipsec_sp_del(struct ofp_ipsec_sp *sp) { struct ofp_ipsec_sp **link; int found = 0; odp_rwlock_write_lock(&shm->lock); link = &shm->sp_list; while (*link) { if (*link == sp) { found = 1; *link = sp->next; break; } link = &(*link)->next; } if (found) { sp->destroyed = 1; sp_unref(sp); } odp_rwlock_write_unlock(&shm->lock); return !found; } const ofp_ipsec_sp_param_t *ofp_ipsec_sp_get_param(struct ofp_ipsec_sp *sp) { return &sp->param; } ofp_ipsec_sa_handle *ofp_ipsec_sp_get_sa_area(struct ofp_ipsec_sp *sp) { return &sp->sa; } static void get_selector_values(odp_packet_t pkt, struct ofp_ipsec_selector_values *s) { struct ofp_ip *ip; uint32_t len; ip = odp_packet_l3_ptr(pkt, &len); if (odp_unlikely(!ip || len < sizeof(*ip))) { memset(s, 0, sizeof(*s)); return; } /* * We assume, like other OFP code, that unaligned access is ok */ s->src_addr = odp_be_to_cpu_32(ip->ip_src.s_addr); s->dst_addr = odp_be_to_cpu_32(ip->ip_dst.s_addr); s->ip_proto = ip->ip_p; } static int sel_match(const struct ofp_ipsec_selectors_t *pol_sel, const struct ofp_ipsec_selector_values *sel) { if (pol_sel->type != OFP_IPSEC_SELECTOR_IPV4) return 0; if (sel->src_addr < pol_sel->src_ipv4_range.first_addr.s_addr || sel->src_addr > pol_sel->src_ipv4_range.last_addr.s_addr) return 0; if (sel->dst_addr < pol_sel->dst_ipv4_range.first_addr.s_addr || sel->dst_addr > pol_sel->dst_ipv4_range.last_addr.s_addr) return 0; if (pol_sel->ip_proto != 0 && sel->ip_proto != pol_sel->ip_proto) return 0; return 1; } void ofp_ipsec_sp_lookup_add_sp(struct ofp_ipsec_sp *sp) { if (sp->param.dir == OFP_IPSEC_DIR_INBOUND) sp_insert(&shm->inbound_lookup_list, sp); else sp_insert(&shm->outbound_lookup_list, sp); } int ofp_ipsec_sp_lookup_del_sp(struct ofp_ipsec_sp *sp, int *empty) { struct ofp_ipsec_sp **link; if (sp->param.dir == OFP_IPSEC_DIR_INBOUND) link = &shm->inbound_lookup_list; else link = &shm->outbound_lookup_list; while (*link && (*link) != sp) link = &(*link)->next_in_lookup; if (link == NULL) return -1; *link = sp->next_in_lookup; *empty = (shm->inbound_lookup_list == NULL && shm->outbound_lookup_list == NULL); return 0; } static inline ofp_ipsec_action_t sp_lookup(struct ofp_ipsec_sp *sp, uint16_t vrf, odp_packet_t pkt, ofp_ipsec_sa_handle *sa) { ofp_ipsec_action_t action; struct ofp_ipsec_selector_values sel; get_selector_values(pkt, &sel); while (sp) { if (sp->param.vrf == vrf && sel_match(&sp->param.selectors, &sel)) break; sp = sp->next_in_lookup; } if (sp) { if (sa) { if (!ofp_ipsec_sa_disabled(sp->sa)) { *sa = sp->sa; } else { *sa = OFP_IPSEC_SA_INVALID; } } action = sp->param.action; } else { action = OFP_IPSEC_ACTION_BYPASS; } return action; } ofp_ipsec_action_t ofp_ipsec_sp_out_lookup(uint16_t vrf, odp_packet_t pkt, ofp_ipsec_sa_handle *sa) { return sp_lookup(shm->outbound_lookup_list, vrf, pkt, sa); } ofp_ipsec_action_t ofp_ipsec_sp_in_lookup(uint16_t vrf, odp_packet_t pkt) { return sp_lookup(shm->inbound_lookup_list, vrf, pkt, NULL); } /* * Length of common (to the types we handle below) ICMP header before the * payload containing the triggering packets. */ #define ICMP_COMMON_LEN 8 /* * Check if a packet is ICMP and if so, match the header of the tiggering * packet (contained in the ICMP payload) against the provided selectors. * See RFC 4301, section 6.2. */ static int icmp_match(odp_packet_t pkt, ofp_ipsec_selectors_t *sel) { struct ofp_ip *ip; uint32_t len; struct ofp_icmp *icmp; struct ofp_ipsec_selector_values sel_values; ip = odp_packet_l3_ptr(pkt, &len); if (!ip || len < sizeof(*ip)) return 0; if (ip->ip_p != OFP_IPPROTO_ICMP) return 0; if (len < ip->ip_hl * 4 + ICMP_COMMON_LEN + sizeof(*ip)) return 0; icmp = (struct ofp_icmp *)((uint8_t *)ip + ip->ip_hl); switch (icmp->icmp_type) { case OFP_ICMP_UNREACH: case OFP_ICMP_TIMXCEED: case OFP_ICMP_PARAMPROB: case OFP_ICMP_SOURCEQUENCH: break; default: return 0; } /* IP header of the triggering packet */ ip = (struct ofp_ip *)((uint8_t *)icmp + ICMP_COMMON_LEN); /* Swap source and destination addresses of the triggering packet. */ sel_values.src_addr = odp_be_to_cpu_32(ip->ip_dst.s_addr); sel_values.dst_addr = odp_be_to_cpu_32(ip->ip_src.s_addr); sel_values.ip_proto = ip->ip_p; return sel_match(sel, &sel_values); } int ofp_ipsec_selector_match(odp_packet_t pkt, ofp_ipsec_selectors_t *sel) { struct ofp_ipsec_selector_values sel_values; get_selector_values(pkt, &sel_values); if (odp_unlikely(!sel_match(sel, &sel_values))) { return icmp_match(pkt, sel); } return 1; }
580f098bcf188fbfbd1e2a1f970f0cd4ee2b2d96
50e95229b9a1161ac294137120aaba94c9eb06bc
/sources/ippcp/pcpgfpecesgetsizesm2.c
1eee866e54d4ed016800c268d15e9aaf183356a0
[ "Apache-2.0", "Intel" ]
permissive
intel/ipp-crypto
f0f05b87203705e82603db67bed5f8def13a5ee8
36e76e2388f3dd10cc440e213dfcf6ef59a0dfb8
refs/heads/develop
2023-09-04T08:15:06.851373
2023-07-27T12:47:12
2023-07-27T12:47:12
140,034,345
304
81
Apache-2.0
2023-08-30T17:18:36
2018-07-06T22:16:28
C
UTF-8
C
false
false
2,043
c
pcpgfpecesgetsizesm2.c
/******************************************************************************* * Copyright (C) 2018 Intel 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. * *******************************************************************************/ /* // // Purpose: // Intel(R) Integrated Performance Primitives. Cryptography Primitives. // EC over GF(p) Operations // // Context: // ippsGFpECESGetSize_SM2() // */ #include "pcpgfpecessm2.h" #include "pcpgfpecstuff.h" /*F* // Name: ippsGFpECESGetSize_SM2 // // Purpose: Computes space required to allocate a SM2 algorithm state // // Returns: Reason: // ippStsNullPtrErr pSize == NULL / pEC == NULL // ippStsContextMatchErr pEC invalid context // ippStsNotSupportedModeErr pGFE->extdegree > 1 // ippStsNoErr no errors // // Parameters: // pEC Pointer to an EC to calculate a shared secret size // pSize Pointer to write a SM2 algorithm state size // *F*/ IPPFUN(IppStatus, ippsGFpECESGetSize_SM2, (const IppsGFpECState* pEC, int* pSize)) { IPP_BAD_PTR2_RET(pEC, pSize); IPP_BADARG_RET(!VALID_ECP_ID(pEC), ippStsContextMatchErr); IPP_BADARG_RET(!pEC->subgroup, ippStsContextMatchErr); IPP_BADARG_RET(1 < pEC->pGF->pGFE->extdegree, ippStsNotSupportedModeErr); { int sm3size; ippsHashGetSize_rmf(&sm3size); *pSize = (Ipp32s)sizeof(IppsECESState_SM2) + sm3size * 2 + BITS2WORD8_SIZE(pEC->pGF->pGFE->modBitLen) * 2; } return ippStsNoErr; }
35128cd2867a0d4625b608cbb964231203c39a06
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/tests/usr.bin/xlint/lint1/msg_240.c
ce4cf70990e814652295e0c7e7db811d36e8fbb9
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
1,040
c
msg_240.c
/* $NetBSD: msg_240.c,v 1.8 2023/08/02 18:51:25 rillig Exp $ */ # 3 "msg_240.c" // Test for message: assignment of different structures (%s != %s) [240] // This message is not used. /* lint1-extra-flags: -X 351 */ struct s_param { int member; }; struct s_local { int member; }; struct s_return { int member; }; union u_arg { int member; }; /* expect+2: warning: parameter 's_param' unused in function 'return_other_struct' [231] */ struct s_return return_other_struct(struct s_param s_param) { /* XXX: No warning? */ return s_param; } /* expect+2: warning: parameter 's_param' unused in function 'assign_other_struct' [231] */ void assign_other_struct(struct s_param s_param) { /* expect+1: warning: 's_local' unused in function 'assign_other_struct' [192] */ static struct s_local s_local; /* XXX: No warning? */ s_local = s_param; } /* expect+2: warning: parameter 'u_arg' unused in function 'return_other_union' [231] */ struct s_return return_other_union(union u_arg u_arg) { /* XXX: No warning? */ return u_arg; }
c7681f44b2e1ceb6fccc722e7409f80aed9fe2a0
8838eb997879add5759b6dfb23f9a646464e53ca
/third-party/tcl/tclsh/tcl_embox_compat.h
f8c1a724b9c872be2eaf95d0a26524f68161caad
[ "BSD-2-Clause" ]
permissive
embox/embox
d6aacec876978522f01cdc4b8de37a668c6f4c80
98e3c06e33f3fdac10a29c069c20775568e0a6d1
refs/heads/master
2023-09-04T03:02:20.165042
2023-09-02T14:55:31
2023-09-02T14:55:31
33,078,138
1,087
325
BSD-2-Clause
2023-09-14T16:58:34
2015-03-29T15:27:48
C
UTF-8
C
false
false
1,877
h
tcl_embox_compat.h
/* * tcl_embox_compat.h * * Created on: Feb 23, 2014 * Author: alexander */ #ifndef TCL_EMBOX_COMPAT_H_ #define TCL_EMBOX_COMPAT_H_ #include <stdio.h> #include <netinet/in.h> #include <sys/types.h> #define HUGE_VAL ((double)-1) /* (termios.h) Extensions to the termios c_iflag bit map. */ #define IXANY 0x0800 /* allow any key to continue ouptut */ #define NI_MAXHOST 1025 // is not POSIX #define NI_MAXSERV 32 // is not POSIX struct utimbuf; static inline void tzset (void) { printf("tcl>>> %s\n", __func__); return; } static inline double ldexp(double x, int exp) { printf("tcl>>> %s\n", __func__); return -1; } static inline char *realpath(const char *path, char *resolved_path) { printf("tcl>>> %s\n", __func__); return (char *)0; } static inline int mkfifo(const char *pathname, mode_t mode) { printf("tcl>>> %s\n", __func__); return -1; } static inline int mknod(const char *pathname, mode_t mode, dev_t dev) { printf("tcl>>> %s\n", __func__); return -1; } static inline ssize_t readlink(const char *path, char *buf, size_t bufsiz) { printf("tcl>>> %s\n", __func__); return -1; } static inline int symlink(const char *oldpath, const char *newpath) { printf("tcl>>> %s\n", __func__); return -1; } static inline int utime(const char *filename, const struct utimbuf *times) { printf("tcl>>> %s\n", __func__); return -1; } static inline int mkstemps(char *template, int suffixlen) { printf("tcl>>> %s\n", __func__); return -1; } static inline double tan(double x) { printf("tcl>>> %s\n", __func__); return -1; } static inline double tanh(double x) { printf("tcl>>> %s\n", __func__); return -1; } static inline struct group *getgrgid(gid_t gid) { printf("tcl>>> %s\n", __func__); return NULL; } static inline int fork(void) { printf("tcl>>> %s\n", __func__); return -1; } #endif /* TCL_EMBOX_COMPAT_H_ */
941e5e540ffe58d1eb48e8da42dd91f337f4720a
77c4f4dd27b8d7497e66a7a5a87ad7ea83f2c4be
/c_glib/arrow-flight-sql-glib/client.h
f2a025fef099bf5448c212675b969e84faee8754
[ "Apache-2.0", "MIT", "BSD-3-Clause", "BSD-2-Clause", "ZPL-2.1", "BSL-1.0", "LicenseRef-scancode-public-domain", "NTP", "OpenSSL", "CC-BY-4.0", "LLVM-exception", "Python-2.0", "CC0-1.0", "LicenseRef-scancode-protobuf", "JSON", "Zlib", "CC-BY-3.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
apache/arrow
0714bfbf6fd491e1f4ed4acf838845ce4b94ec3e
59954225d4615f9b3bd7a3c266fb68761794229a
refs/heads/main
2023-08-24T09:04:22.253199
2023-08-24T07:21:51
2023-08-24T07:21:51
51,905,353
12,955
3,585
Apache-2.0
2023-09-14T20:45:56
2016-02-17T08:00:23
C++
UTF-8
C
false
false
4,016
h
client.h
/* * 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. */ #pragma once #include <arrow-flight-glib/arrow-flight-glib.h> G_BEGIN_DECLS #define GAFLIGHTSQL_TYPE_PREPARED_STATEMENT \ (gaflightsql_prepared_statement_get_type()) G_DECLARE_DERIVABLE_TYPE(GAFlightSQLPreparedStatement, gaflightsql_prepared_statement, GAFLIGHTSQL, PREPARED_STATEMENT, GObject) struct _GAFlightSQLPreparedStatementClass { GObjectClass parent_class; }; GARROW_AVAILABLE_IN_14_0 GAFlightInfo * gaflightsql_prepared_statement_execute( GAFlightSQLPreparedStatement *statement, GAFlightCallOptions *options, GError **error); GARROW_AVAILABLE_IN_14_0 gint64 gaflightsql_prepared_statement_execute_update( GAFlightSQLPreparedStatement *statement, GAFlightCallOptions *options, GError **error); GARROW_AVAILABLE_IN_14_0 GArrowSchema * gaflightsql_prepared_statement_get_parameter_schema( GAFlightSQLPreparedStatement *statement); GARROW_AVAILABLE_IN_14_0 GArrowSchema * gaflightsql_prepared_statement_get_dataset_schema( GAFlightSQLPreparedStatement *statement); GARROW_AVAILABLE_IN_14_0 gboolean gaflightsql_prepared_statement_set_record_batch( GAFlightSQLPreparedStatement *statement, GArrowRecordBatch *record_batch, GError **error); GARROW_AVAILABLE_IN_14_0 gboolean gaflightsql_prepared_statement_set_record_batch_reader( GAFlightSQLPreparedStatement *statement, GArrowRecordBatchReader *reader, GError **error); GARROW_AVAILABLE_IN_14_0 gboolean gaflightsql_prepared_statement_close( GAFlightSQLPreparedStatement *statement, GAFlightCallOptions *options, GError **error); GARROW_AVAILABLE_IN_14_0 gboolean gaflightsql_prepared_statement_is_closed( GAFlightSQLPreparedStatement *statement); #define GAFLIGHTSQL_TYPE_CLIENT (gaflightsql_client_get_type()) G_DECLARE_DERIVABLE_TYPE(GAFlightSQLClient, gaflightsql_client, GAFLIGHTSQL, CLIENT, GObject) struct _GAFlightSQLClientClass { GObjectClass parent_class; }; GARROW_AVAILABLE_IN_9_0 GAFlightSQLClient * gaflightsql_client_new(GAFlightClient *client); GARROW_AVAILABLE_IN_9_0 GAFlightInfo * gaflightsql_client_execute(GAFlightSQLClient *client, const gchar *query, GAFlightCallOptions *options, GError **error); GARROW_AVAILABLE_IN_13_0 gint64 gaflightsql_client_execute_update(GAFlightSQLClient *client, const gchar *query, GAFlightCallOptions *options, GError **error); GARROW_AVAILABLE_IN_9_0 GAFlightStreamReader * gaflightsql_client_do_get(GAFlightSQLClient *client, GAFlightTicket *ticket, GAFlightCallOptions *options, GError **error); GARROW_AVAILABLE_IN_14_0 GAFlightSQLPreparedStatement * gaflightsql_client_prepare(GAFlightSQLClient *client, const gchar *query, GAFlightCallOptions *options, GError **error); G_END_DECLS
51933aeca0246105fa7856a8bbd6c91a1c509fdd
821128c7e0c6b41c08474e98dffc9dd5f72b8857
/estimator/cc_loss_stat.h
5d32e1d739aba97cb546fa9e2cdcdd0e9d8940e3
[ "MIT" ]
permissive
yuanrongxi/razor
304b9c5d5a9e011f212dbcb8c773f8e4b4133fef
b361d64ca3357226af3d6c9651bc235905066141
refs/heads/master
2023-07-19T07:47:49.092351
2023-07-16T07:17:50
2023-07-16T07:17:50
126,000,077
322
152
MIT
2021-09-07T10:49:37
2018-03-20T10:25:35
C++
GB18030
C
false
false
926
h
cc_loss_stat.h
/*- * Copyright (c) 2017-2018 Razor, Inc. * All rights reserved. * * See the file LICENSE for redistribution information. */ #ifndef __cc_loss_stat_h_ #define __cc_loss_stat_h_ #include <stdint.h> #include "cf_platform.h" #include "cf_skiplist.h" #include "cf_unwrapper.h" /*接收端统计丢包,没有采用webRTC中比较复杂的方式,而是采用了一种简单近似的方式来实现*/ typedef struct { int64_t stat_ts; int64_t max_id; /*接收到最大序号*/ skiplist_t* list; cf_unwrapper_t wrapper; /*id转换器*/ }cc_loss_statistics_t; void loss_statistics_init(cc_loss_statistics_t* loss_stat); void loss_statistics_destroy(cc_loss_statistics_t* loss_stat); int loss_statistics_calculate(cc_loss_statistics_t* loss_stat, int64_t now_ts, uint8_t* fraction_loss, int* num); void loss_statistics_incoming(cc_loss_statistics_t* loss_stat, uint16_t seq, int64_t now_ts); #endif
e03a82297a9ac7e327bd1e2e6c3909c629924255
5de3ec4e6c65e60da1ed32b03748f96de7ef0b95
/Pods/Headers/Private/Realm/RLMConstants.h
7f3eabc8186c189b3b128e9185cca3ce3767ab36
[ "MIT" ]
permissive
aaronpearce/DevSwitch
5154730f4f9eabcc14a6ad1222c6823b250b991e
98a1e6ded11907a02d21380ca93999d34b85b0b2
refs/heads/master
2021-06-10T22:56:56.239592
2021-06-04T21:25:40
2021-06-04T21:25:40
177,062,016
457
25
MIT
2019-03-24T22:37:41
2019-03-22T03:00:31
Swift
UTF-8
C
false
false
37
h
RLMConstants.h
../../../Realm/include/RLMConstants.h
d653953f3810ee0daec763d26caf779098975074
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/x68k/include/ieeefp.h
46bde4087371b5ff96502aa91285056617b0d0e8
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
128
h
ieeefp.h
/* $NetBSD: ieeefp.h,v 1.1 1996/05/05 12:17:14 oki Exp $ */ /* Just use the common m68k definition */ #include <m68k/ieeefp.h>
445279dd9ddb79fa3823e59a5121c06ac66a3e4c
03666e5f961946fc1a0ac67781ac1425562ef0d7
/src/databases/H5Nimrod/avtH5NimrodFileFormat.C
7a20af67a4206380ca8e94767ec47d3f6a7ade0b
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
visit-dav/visit
e9f81b4d4b9b9930a0db9d5282cd1bcabf465e2e
601ae46e0bef2e18425b482a755d03490ade0493
refs/heads/develop
2023-09-06T08:19:38.397058
2023-09-05T21:29:32
2023-09-05T21:29:32
165,565,988
335
120
BSD-3-Clause
2023-09-14T00:53:37
2019-01-13T23:27:26
C
UTF-8
C
false
false
20,963
c
avtH5NimrodFileFormat.C
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt // Project developers. See the top-level LICENSE file for dates and other // details. No copyright assignment is required to contribute to VisIt. // ************************************************************************* // // avtH5NimrodFileFormat.C // // ************************************************************************* // #include <avtH5NimrodFileFormat.h> #include <string> #include <vtkFloatArray.h> #include <vtkRectilinearGrid.h> #include <vtkStructuredGrid.h> #include <vtkUnstructuredGrid.h> #include <avtDatabaseMetaData.h> #include <Expression.h> #include <NonCompliantException.h> #include <InvalidFilesException.h> #include <InvalidVariableException.h> #include <vtkStructuredGrid.h> #include <vtkPoints.h> #include <vtkCellType.h> #include <vector> #include <DebugStream.h> #include <visit-hdf5.h> using std::string; using std::vector; // **************************************************************************** // Function: dbg_string_attrib // // Purpose: // Look up a string attribute from within the hdf5 file. Echo it's value to // our debug logs. // // Arguments: // id hdf5 identifier; should be the return value from an H5GOpen call. // str string to both lookup and include in the debug line. // // Programmer: Tom Fogal // Creation: Wed Apr 29 15:59:41 MDT 2009 // // Modifications: // // **************************************************************************** static void dbg_string_attrib(hid_t id, const std::string &str) { char *attrib = NULL; int h5err = H5NIMROD_read_string_attrib(id, str.c_str(), &attrib); if(h5err == H5NIMROD_ERR) { debug1 << "Reading '" << str << "' string in H5Nimrod gave an error!" << " Is this attribute guaranteed to exist for all H5Nimrod " "files?" << std::endl; } // The read_string_attrib call can fail, but failure doesn't give any // information about whether or not the string given in the 3rd argument // was actually allocated. Thus we set the string to NULL and check if it // got changed during the call. if(NULL != attrib) { debug5 << str << ": " << attrib << std::endl; free(attrib); } } // **************************************************************************** // Method: avtH5Nimrod constructor // // Programmer: cristina -- generated by xml2avt // Creation: Fri Feb 9 08:26:27 PDT 2007 // // Modifications: // Kathleen Bonnell, Wed Jul 2 08:43:22 PDT 2008 // Removed unreferenced variables. // // Tom Fogal, Wed Apr 29 16:11:41 MDT 2009 // Handle errors when reading string attributes. // // Jeremy Meredith, Thu Jan 7 15:36:19 EST 2010 // Close all open ids when returning an exception. Added error detection. // // **************************************************************************** avtH5NimrodFileFormat::avtH5NimrodFileFormat (const char *filename): avtMTSDFileFormat (&filename, 1) { // INITIALIZE DATA MEMBERS fname = filename; hid_t file_id, root_id, group_id = 0; /* TODO: check fix for uninitialized pointer */ char *string_attrib; float time; // Init HDF5 and turn off error message printing. H5open(); H5Eset_auto( NULL, NULL ); // Check for a valid H5NIMROD file if( H5Fis_hdf5( filename ) < 0 ) EXCEPTION1( InvalidFilesException, filename ); if ((file_id = H5Fopen(filename, H5F_ACC_RDONLY, H5P_DEFAULT)) < 0) EXCEPTION1( InvalidFilesException, filename ); hsize_t i, npoints; // Read attributes root_id = H5Gopen (file_id, "/"); if ( root_id < 0 ) { H5Fclose(file_id); EXCEPTION1( InvalidVariableException, "H5NIMROD Group Open - root group '/' was not found" ); } dbg_string_attrib(root_id, "Description"); dbg_string_attrib(root_id, "Source"); if (H5NIMROD_read_attrib (root_id, "time", &time) == H5NIMROD_ERR) { H5Gclose(root_id); H5Fclose(file_id); EXCEPTION1( InvalidVariableException, "H5NIMROD Read Attribute - 'time' was not found or was the wrong type." ); } debug5 << "time: " << time << std::endl; hid_t grid_id = H5Gopen (file_id, "/GRID"); if (grid_id < 0) { H5Gclose(root_id); H5Fclose(file_id); EXCEPTION1( InvalidVariableException, "H5NIMROD Group Open - '/GRID' was not found" ); } string_attrib = NULL; H5NIMROD_read_string_attrib (grid_id, "Coordinate System", &string_attrib); if(string_attrib != NULL) { debug5 << "Coordinate System: " << string_attrib << std::endl; if (strstr(string_attrib, "Cartesian - XYZ") == NULL) { debug5 << "Cannot handle non cartesian coordinates" << std::endl; H5Gclose(root_id); H5Gclose(grid_id); H5Fclose(file_id); EXCEPTION1( InvalidVariableException, "H5NIMROD Read Attribute - 'Cartesian - XYZ' was not found or was the wrong type." ); } free(string_attrib); } string_attrib = NULL; H5NIMROD_read_string_attrib (grid_id, "Topology", &string_attrib); if (string_attrib && strstr(string_attrib, "Structured") != NULL) { structured = 1; debug5 << "Grid is structured!" << std::endl; } else { structured = 0; debug5 << "Cannot handle unstructured mesh" << std::endl; H5Gclose(root_id); H5Gclose(grid_id); H5Fclose (file_id); EXCEPTION1( InvalidVariableException, "H5NIMROD Read Attribute - 'Topology' was not found or not 'Structured'" ); } if(string_attrib) { free (string_attrib); } dbg_string_attrib(grid_id, "Geometry"); H5NIMROD_read_dims (grid_id, "X", &ndims, grid_dims); if (ndims != 3) { debug5 << "Cannot handle other than 3 dimensional data" << std::endl; H5Gclose(root_id); H5Gclose(grid_id); H5Fclose (file_id); EXCEPTION1( InvalidVariableException, "H5NIMROD Read Dimensions - Grid dataset 'X' does not have three dimensions" ); } // points for (i = 0, npoints = 1; i < (hsize_t)ndims; i++) { debug5 << "ndims: " << ndims << " " << grid_dims[i] << std::endl; npoints *= grid_dims[i]; } npoints *= ndims; // connectivity is implicit // point vars int num_groups = H5NIMROD_get_num_objects_matching_pattern (root_id, "/", H5G_GROUP, NULL); debug5<< "num_groups = "<<num_groups <<endl; char name[MAXLENGTH], name1[MAXLENGTH], name2[MAXLENGTH], stepnumber[MAXLENGTH]; nsteps = 0; for (int idx = 0; idx < num_groups; idx++) { int len_of_name = MAXLENGTH; H5NIMROD_get_object_name (root_id, "/", H5G_GROUP, idx, name, len_of_name); debug5<<idx<<": name= "<<name<<endl; if (strncmp (name, "step_", strlen ("step_")) == 0) { sprintf (name1, "/%s", name); stepnames.push_back( name ); nsteps++; group_id = H5Gopen (root_id, name1); memset( stepnumber, 0, MAXLENGTH ); if (H5NIMROD_read_attrib (group_id, "Step number", &stepnumber) == H5NIMROD_ERR) { H5Gclose(group_id); H5Fclose(file_id); EXCEPTION1( InvalidVariableException, "H5NIMROD Read Attribute - 'Step number' was not found or wrong type" ); } cycles.push_back( atoi(stepnumber) ); debug5 << "step number: " << stepnumber << std::endl; if (H5NIMROD_read_attrib (group_id, "time", &time) == H5NIMROD_ERR) { H5Gclose(group_id); H5Fclose(file_id); EXCEPTION1( InvalidVariableException, "H5NIMROD Read Attribute - 'time' was not found or wrong type" ); } times.push_back( time ); debug5 << "time: " << time << std::endl; nvectorvars = H5NIMROD_get_num_objects_matching_pattern (group_id, name1, H5G_GROUP, NULL); vectorvars.resize (nvectorvars); vectorvarnames.resize (nvectorvars); vectorvardims.resize (nvectorvars); for (int kdx = 0; kdx < nvectorvars; kdx++) { H5NIMROD_get_object_name (group_id, name1, H5G_GROUP, kdx, name2, len_of_name); vectorvarnames[kdx] = name2; vectorvardims[kdx] = H5NIMROD_get_num_objects_matching_pattern (group_id, name2, H5G_DATASET, NULL); } nscalarvars = H5NIMROD_get_num_objects_matching_pattern (group_id, name1, H5G_DATASET, NULL); scalarvars.resize (nscalarvars); scalarvarnames.resize (nscalarvars); for (int kdx = 0; kdx < nscalarvars; kdx++) { H5NIMROD_get_object_name (group_id, name1, H5G_DATASET, kdx, name, len_of_name); scalarvarnames[kdx] = name; } H5Gclose (group_id); } } debug5 << "num scalarvars: " << nscalarvars << std::endl; debug5 << "num vectorvars: " << nvectorvars << std::endl; H5Gclose (grid_id); H5Gclose (root_id); H5Fclose (file_id); } // **************************************************************************** // Method: avtEMSTDFileFormat::GetNTimesteps // // Purpose: // Tells the rest of the code how many timesteps there are in this file. // // Programmer: cristina -- generated by xml2avt // Creation: Fri Feb 9 08:26:27 PDT 2007 // // **************************************************************************** int avtH5NimrodFileFormat::GetNTimesteps (void) { return nsteps; } // **************************************************************************** // Method: avtH5NimrodFileFormat::FreeUpResources // // Purpose: // When VisIt is done focusing on a particular timestep, it asks that // timestep to free up any resources (memory, file descriptors) that // it has associated with it. This method is the mechanism for doing // that. // // Programmer: cristina -- generated by xml2avt // Creation: Fri Feb 9 08:26:27 PDT 2007 // // **************************************************************************** void avtH5NimrodFileFormat::FreeUpResources (void) { } // **************************************************************************** // Method: avtH5NimrodFileFormat::PopulateDatabaseMetaData // // Purpose: // This database meta-data object is like a table of contents for the // file. By populating it, you are telling the rest of VisIt what // information it can request from you. // // Programmer: cristina -- generated by xml2avt // Creation: Fri Feb 9 08:26:27 PDT 2007 // // Modifications: // // Tom Fogal, Wed Apr 29 16:09:52 MDT 2009 // Removed an unused variable. // // **************************************************************************** void avtH5NimrodFileFormat::PopulateDatabaseMetaData (avtDatabaseMetaData * md, int timeState) { int nblocks = 1; // <-- this must be 1 for MTSD int block_origin = 0; int spatial_dimension = ndims; int topological_dimension = ndims; double *extents = NULL; int bounds[3]; bounds[0] = grid_dims[0]; bounds[1] = grid_dims[1]; bounds[2] = grid_dims[2]; AddMeshToMetaData (md, "Mesh", AVT_CURVILINEAR_MESH, extents, nblocks, block_origin, spatial_dimension, topological_dimension, bounds); for (int idx = 0; idx < nscalarvars; idx++) { string mesh_for_this_var = "Mesh"; // ??? -- could be multiple meshes string varname = scalarvarnames[idx]; // AVT_NODECENT, AVT_ZONECENT, AVT_UNKNOWN_CENT avtCentering cent = AVT_NODECENT; AddScalarVarToMetaData (md, varname, mesh_for_this_var, cent, extents); } for (int idx = 0; idx < nvectorvars; idx++) { string mesh_for_this_var = "Mesh"; // ??? -- could be multiple meshes string varname = vectorvarnames[idx]; // AVT_NODECENT, AVT_ZONECENT, AVT_UNKNOWN_CENT avtCentering cent = AVT_NODECENT; AddVectorVarToMetaData (md, varname, mesh_for_this_var, cent, vectorvardims[idx], extents); } md->SetCyclesAreAccurate(true); md->SetCycles( cycles ); md->SetTimesAreAccurate(true); md->SetTimes( times ); } // **************************************************************************** // Method: avtH5NimrodFileFormat::GetMesh // // Purpose: // Gets the mesh associated with this file. The mesh is returned as a // derived type of vtkDataSet (ie vtkRectilinearGrid, vtkStructuredGrid, // vtkUnstructuredGrid, etc). // // Arguments: // timestate The index of the timestate. If GetNTimesteps returned // 'N' time steps, this is guaranteed to be between 0 and N-1. // meshname The name of the mesh of interest. This can be ignored if // there is only one mesh. // // Programmer: cristina -- generated by xml2avt // Creation: Fri Feb 9 08:26:27 PDT 2007 // // **************************************************************************** vtkDataSet * avtH5NimrodFileFormat::GetMesh (int timestate, const char *meshname) { vtkStructuredGrid *dataset = vtkStructuredGrid::New (); vtkPoints *vtkpoints = vtkPoints::New (); vtkpoints->SetDataTypeToFloat (); int dims[3]; hsize_t npoints = 1; for (int i = 0; i < ndims; i++) { dims[i] = (int) grid_dims[i]; npoints *= grid_dims[i]; } dataset->SetDimensions (dims); hid_t file; file = H5Fopen (fname.c_str (), H5F_ACC_RDONLY, H5P_DEFAULT); if (file < 0) { EXCEPTION2( NonCompliantException, "H5NIMROD File Open", "File '" + fname + "' can not be opened" ); } hid_t grid_id = H5Gopen (file, "/GRID"); vtkpoints->SetNumberOfPoints (npoints); float *Xcoord; Xcoord = (float *) malloc (sizeof (float) * npoints); H5NIMROD_read_float32_array (grid_id, "X", NULL, ndims, NULL, Xcoord); _transpose_3D(Xcoord, grid_dims); float *Ycoord; Ycoord = (float *) malloc (sizeof (float) * npoints); H5NIMROD_read_float32_array (grid_id, "Y", NULL, ndims, NULL, Ycoord); _transpose_3D(Ycoord, grid_dims); float *Zcoord; Zcoord = (float *) malloc (sizeof (float) * npoints); H5NIMROD_read_float32_array (grid_id, "Z", NULL, ndims, NULL, Zcoord); _transpose_3D(Zcoord, grid_dims); float *pts = (float *) vtkpoints->GetVoidPointer (0); hsize_t idx = 0; for (hsize_t i = 0; i < npoints; i++) { pts[idx] = Xcoord[i]; pts[idx + 1] = Ycoord[i]; pts[idx + 2] = Zcoord[i]; idx += 3; } dataset->SetPoints (vtkpoints); free (Xcoord); free (Ycoord); free (Zcoord); vtkpoints->Delete(); H5Gclose (grid_id); H5Fclose (file); return dataset; } // **************************************************************************** // Method: avtH5NimrodFileFormat::GetVar // // Purpose: // Gets a scalar variable associated with this file. Although VTK has // support for many different types, the best bet is vtkFloatArray, since // that is supported everywhere through VisIt. // // Arguments: // timestate The index of the timestate. If GetNTimesteps returned // 'N' time steps, this is guaranteed to be between 0 and N-1. // varname The name of the variable requested. // // Programmer: cristina -- generated by xml2avt // Creation: Fri Feb 9 08:26:27 PDT 2007 // // **************************************************************************** vtkDataArray * avtH5NimrodFileFormat::GetVar (int timestate, const char *varname) { hid_t file; file = H5Fopen (fname.c_str (), H5F_ACC_RDONLY, H5P_DEFAULT); if (file < 0) { EXCEPTION2( NonCompliantException, "H5NIMROD File Open", "File '" + fname + "' can not be opened" ); } hid_t root_id, group_id; root_id = H5Gopen (file, "/"); group_id = H5Gopen (root_id, stepnames[timestate].c_str ()); float *var; hsize_t npoints = 1; for (hsize_t i = 0; i < (hsize_t)ndims; i++) { npoints *= grid_dims[i]; } var = (float *) malloc (sizeof (float) * npoints); H5NIMROD_read_float32_array (group_id, varname, NULL, ndims, NULL, var); _transpose_3D(var, grid_dims); hsize_t ntuples = npoints; vtkFloatArray *scalars = vtkFloatArray::New (); scalars->SetNumberOfTuples (ntuples); float *ptr = (float *) scalars->GetVoidPointer (0); memcpy (ptr, var, sizeof (float) * npoints); free (var); H5Gclose (group_id); H5Gclose (root_id); H5Fclose (file); return scalars; } // **************************************************************************** // Method: avtH5NimrodFileFormat::GetVectorVar // // Purpose: // Gets a vector variable associated with this file. Although VTK has // support for many different types, the best bet is vtkFloatArray, since // that is supported everywhere through VisIt. // // Arguments: // timestate The index of the timestate. If GetNTimesteps returned // 'N' time steps, this is guaranteed to be between 0 and N-1. // varname The name of the variable requested. // // Programmer: cristina -- generated by xml2avt // Creation: Fri Feb 9 08:26:27 PDT 2007 // // **************************************************************************** vtkDataArray * avtH5NimrodFileFormat::GetVectorVar (int timestate, const char *varname) { hid_t file; file = H5Fopen (fname.c_str (), H5F_ACC_RDONLY, H5P_DEFAULT); if (file < 0) { EXCEPTION2( NonCompliantException, "H5NIMROD File Open", "File '" + fname + "' can not be opened" ); } hid_t root_id, group_id; root_id = H5Gopen (file, "/"); group_id = H5Gopen (root_id, stepnames[timestate].c_str ()); int num_comp = H5NIMROD_get_num_objects_matching_pattern (group_id, varname, H5G_DATASET, NULL); hsize_t npoints = 1; for (hsize_t i = 0; i < (hsize_t)ndims; i++) { npoints *= grid_dims[i]; } float **comp; comp = (float **) malloc (sizeof (float *) * num_comp); for (int idx = 0; idx < num_comp; idx++) comp[idx] = (float *) malloc (sizeof (float) * npoints); hid_t vector_id = H5Gopen (group_id, varname); char name[MAXLENGTH]; int len_of_name = MAXLENGTH; for (int idx = 0; idx < num_comp; idx++) { H5NIMROD_get_object_name (group_id, varname, H5G_DATASET, idx, name, len_of_name); H5NIMROD_read_float32_array (vector_id, name, NULL, ndims, NULL, comp[idx]); _transpose_3D(comp[idx], grid_dims); } vtkFloatArray *vector = vtkFloatArray::New (); hsize_t ntuples = npoints; vector->SetNumberOfComponents (num_comp); vector->SetNumberOfTuples (ntuples); float *ptr = (float *) vector->GetVoidPointer (0); hsize_t count = 0; for (hsize_t idx = 0; idx < ntuples; idx++) { for (int jdx = 0; jdx < num_comp; jdx++) { ptr[count + jdx] = comp[jdx][idx]; } count += num_comp; } for (int idx = 0; idx < num_comp; idx++) { if (comp[idx] != NULL) free (comp[idx]); } if (comp != NULL) free (comp); return vector; H5Gclose (vector_id); H5Gclose (group_id); H5Gclose (root_id); H5Fclose (file); } // **************************************************************************** // Method: avtH5NimrodFileFormat::GetCycles // // Purpose: // Returns the cycles // // Arguments: // c the cycles // // Programmer: allen // Creation: // // **************************************************************************** void avtH5NimrodFileFormat::GetCycles(std::vector<int> &c) { c = cycles; } // **************************************************************************** // Method: avtH5NimrodFileFormat::GetTimes // // Purpose: // Returns the times // // Arguments: // t the times // // Programmer: allen // Creation: // // **************************************************************************** void avtH5NimrodFileFormat::GetTimes(std::vector<double> &t) { t = times; }
7546f97b4f1ea34302edfd41353713c8ed85d18e
b6fd3ebe265cc089f76391068f07d2e7ea361e76
/drivers/softrend/v1m_386.h
a89dfe37d886b4114178a4709dd143c5aaa419f2
[ "MIT" ]
permissive
foone/BRender-v1.3.2
55bbdba6470234e158f82247bb5e03c2c27b9e3e
d88d0ed41122664b9781015b517db64353e16f19
refs/heads/main
2022-05-05T22:39:56.191332
2022-05-05T22:33:54
2022-05-05T22:33:54
488,348,032
486
35
MIT
2022-05-03T23:06:16
2022-05-03T20:06:34
C
UTF-8
C
false
false
1,040
h
v1m_386.h
/* * Copyright (c) 1993-1995 Argonaut Technologies Limited. All rights reserved. * * $Id: v1m_386.h 1.3 1998/07/20 19:53:48 jon Exp $ * $Locker: $ * * Prototypes for 386 downcoded geometry support that is specific to V1 models */ #ifndef _V1M_386_H_ #define _V1M_386_H_ #ifdef __cplusplus extern "C" { #endif void GEOMETRY_CALL V1Face_CullOneSidedPerspective_A(struct br_geometry *self, struct br_renderer *renderer); void GEOMETRY_CALL V1Face_CullOneSidedPerspective_P6_A(struct br_geometry *self, struct br_renderer *renderer); void GEOMETRY_CALL V1Face_OS_CullOneSidedPerspective_A(struct br_geometry *self, struct br_renderer *renderer); #if BASED_FLOAT #define V1Face_CullOneSidedPerspective V1Face_CullOneSidedPerspective_A #define V1Face_CullOneSidedPerspective_P6 V1Face_CullOneSidedPerspective_P6_A #endif #if BASED_FIXED #define V1Face_CullOneSidedPerspective V1Face_CullOneSidedPerspective_A #define V1Face_OS_CullOneSidedPerspective V1Face_OS_CullOneSidedPerspective_A #endif #ifdef __cplusplus }; #endif #endif
7afc70c81a543f508f1caaeb5912bd87aa1f8f45
af9eabdb2ac240f9f2a2f3e92e6bc9044069362e
/sdk/csi_driver/wujian100_open/system.c
9a2fc5e7632f951c89c1dc298c32fe5e04170308
[ "MIT" ]
permissive
T-head-Semi/wujian100_open
9926f118867a08283004759d09af6631db2e92cf
83e297583bb3454b688f9f27d6bc20ff3276ad32
refs/heads/master
2022-07-27T05:13:57.608880
2021-12-31T09:23:38
2021-12-31T09:23:38
216,210,370
1,846
609
MIT
2019-12-15T10:41:08
2019-10-19T13:25:30
Verilog
UTF-8
C
false
false
1,560
c
system.c
/* * Copyright (C) 2017-2019 Alibaba Group Holding Limited */ /****************************************************************************** * @file system.c * @brief CSI Device System Source File * @version V1.0 * @date 02. Oct 2019 ******************************************************************************/ #include <csi_config.h> #include <soc.h> #include <csi_core.h> #include <drv_irq.h> #ifndef CONFIG_SYSTICK_HZ #define CONFIG_SYSTICK_HZ 100 #endif int g_system_clock = IHS_VALUE; extern int32_t g_top_irqstack; extern void irq_vectors_init(void); extern void mm_heap_initialize(void); #ifdef CONFIG_KERNEL_NONE static void _system_init_for_baremetal(void) { __enable_excp_irq(); csi_coret_config(drv_get_sys_freq() / CONFIG_SYSTICK_HZ, CORET_IRQn); //10ms mm_heap_initialize(); } #endif #ifndef CONFIG_KERNEL_NONE static void _system_init_for_kernel(void) { irq_vectors_init(); csi_coret_config(drv_get_sys_freq() / CONFIG_SYSTICK_HZ, CORET_IRQn); //10ms drv_irq_enable(CORET_IRQn); #ifndef CONFIG_KERNEL_RHINO #ifndef CONFIG_NUTTXMM_NONE mm_heap_initialize(); #endif #endif } #endif /** * @brief initialize the system * Initialize the psr and vbr. * @param None * @return None */ void SystemInit(void) { int i; CLIC->CLICCFG = 0x4UL; for (i = 0; i < 12; i++) { CLIC->INTIP[i] = 0; } drv_irq_enable(Machine_Software_IRQn); #ifdef CONFIG_KERNEL_NONE _system_init_for_baremetal(); #else _system_init_for_kernel(); #endif }
934b51f765a2aff33955a589cb33b6f38d43c70c
3afd7229cfff2da1b504cf33869f0397e7d72535
/src/include/signals.h
3fe8a2f74898a33cb3d877d0c87b75b95afda3d7
[ "MIT" ]
permissive
ptitSeb/box64
ed62db37d8dd328316fef259be24ff95b9d785e7
7cba83231a0ca05a18bb6a07735ba8d5f0a216b6
refs/heads/main
2023-08-31T06:25:22.053788
2023-08-30T19:53:29
2023-08-30T19:53:29
317,493,442
2,317
197
MIT
2023-09-13T13:51:23
2020-12-01T09:42:50
C
UTF-8
C
false
false
1,358
h
signals.h
#ifndef __SIGNALS_H__ #define __SIGNALS_H__ #include <signal.h> typedef void (*sighandler_t)(int); typedef struct x64_sigaction_s { union { sighandler_t _sa_handler; void (*_sa_sigaction)(int, siginfo_t *, void *); } _u; sigset_t sa_mask; uint32_t sa_flags; void (*sa_restorer)(void); } x64_sigaction_t; typedef struct x64_sigaction_restorer_s { union { sighandler_t _sa_handler; void (*_sa_sigaction)(int, siginfo_t *, void *); } _u; uint32_t sa_flags; void (*sa_restorer)(void); sigset_t sa_mask; } x64_sigaction_restorer_t; sighandler_t my_signal(x64emu_t* emu, int signum, sighandler_t handler); sighandler_t my___sysv_signal(x64emu_t* emu, int signum, sighandler_t handler); sighandler_t my_sysv_signal(x64emu_t* emu, int signum, sighandler_t handler); int my_sigaction(x64emu_t* emu, int signum, const x64_sigaction_t *act, x64_sigaction_t *oldact); int my___sigaction(x64emu_t* emu, int signum, const x64_sigaction_t *act, x64_sigaction_t *oldact); int my_syscall_rt_sigaction(x64emu_t* emu, int signum, const x64_sigaction_restorer_t *act, x64_sigaction_restorer_t *oldact, int sigsetsize); void init_signal_helper(box64context_t* context); void fini_signal_helper(void); void emit_signal(x64emu_t* emu, int sig, void* addr, int code); void emit_interruption(x64emu_t* emu, int num, void* addr); #endif //__SIGNALS_H__
050954f18220f88707c1276629e83b6fc7009025
dc5b5723f2aebc9abaa125e281b59cb88362996f
/sample/framework/vx_lut.c
2c2d6a545a27b767515f05da16e08137cb4c850e
[ "Apache-2.0" ]
permissive
KhronosGroup/OpenVX-sample-impl
cd3cc630b398a859ff83ce75ff02ff7f8dd45e64
9caba36a541fa6480f9d65d9a78dde208ebe96f9
refs/heads/openvx_1.3
2023-09-05T23:32:05.073687
2023-06-16T19:53:24
2023-06-16T19:53:24
157,795,699
134
55
Apache-2.0
2023-06-16T19:53:25
2018-11-16T01:33:06
C
UTF-8
C
false
false
11,571
c
vx_lut.c
/* * Copyright (c) 2012-2017 The Khronos Group 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. */ #include "vx_internal.h" #include "vx_lut.h" VX_API_ENTRY vx_lut VX_API_CALL vxCreateLUT(vx_context context, vx_enum data_type, vx_size count) { vx_lut_t *lut = NULL; if (ownIsValidContext(context) == vx_true_e) { if (data_type == VX_TYPE_UINT8) { #if defined(OPENVX_STRICT_1_0) if (count != 256) { VX_PRINT(VX_ZONE_ERROR, "Invalid parameter to LUT\n"); vxAddLogEntry(&context->base, VX_ERROR_INVALID_PARAMETERS, "Invalid parameter to LUT\n"); lut = (vx_lut_t *)ownGetErrorObject(context, VX_ERROR_INVALID_PARAMETERS); } else #endif { lut = (vx_lut_t *)ownCreateArrayInt(context, VX_TYPE_UINT8, count, vx_false_e, VX_TYPE_LUT); if (vxGetStatus((vx_reference)lut) == VX_SUCCESS && lut->base.type == VX_TYPE_LUT) { lut->num_items = count; lut->offset = 0; ownPrintArray(lut); } } } else if (data_type == VX_TYPE_INT16) { if (!(count <= 65536)) { VX_PRINT(VX_ZONE_ERROR, "Invalid parameter to LUT\n"); vxAddLogEntry(&context->base, VX_ERROR_INVALID_PARAMETERS, "Invalid parameter to LUT\n"); lut = (vx_lut_t *)ownGetErrorObject(context, VX_ERROR_INVALID_PARAMETERS); } else { lut = (vx_lut_t *)ownCreateArrayInt(context, VX_TYPE_INT16, count, vx_false_e, VX_TYPE_LUT); if (vxGetStatus((vx_reference)lut) == VX_SUCCESS && lut->base.type == VX_TYPE_LUT) { lut->num_items = count; lut->offset = (vx_uint32)(count/2); ownPrintArray(lut); } } } #if !defined(OPENVX_STRICT_1_0) else if (data_type == VX_TYPE_UINT16) { lut = (vx_lut_t *)ownCreateArrayInt(context, VX_TYPE_UINT16, count, vx_false_e, VX_TYPE_LUT); if (vxGetStatus((vx_reference)lut) == VX_SUCCESS && lut->base.type == VX_TYPE_LUT) { lut->num_items = count; lut->offset = 0; ownPrintArray(lut); } } #endif else { VX_PRINT(VX_ZONE_ERROR, "Invalid data type\n"); vxAddLogEntry(&context->base, VX_ERROR_INVALID_TYPE, "Invalid data type\n"); lut = (vx_lut_t *)ownGetErrorObject(context, VX_ERROR_INVALID_TYPE); } } return (vx_lut)lut; } VX_API_ENTRY vx_lut VX_API_CALL vxCreateVirtualLUT(vx_graph graph, vx_enum data_type, vx_size count) { vx_lut_t *lut = NULL; vx_reference_t *gref = (vx_reference_t *)graph; if (ownIsValidSpecificReference(gref, VX_TYPE_GRAPH) == vx_true_e) { lut = (vx_lut_t *)vxCreateLUT(gref->context, data_type, count); if (vxGetStatus((vx_reference)lut) == VX_SUCCESS && lut->base.type == VX_TYPE_LUT) { lut->base.scope = (vx_reference_t *)graph; lut->base.is_virtual = vx_true_e; } } return (vx_lut)lut; } void vxDestructLUT(vx_reference ref) { vx_lut_t *lut = (vx_lut_t *)ref; ownDestructArray((vx_reference_t *)lut); } VX_API_ENTRY vx_status VX_API_CALL vxReleaseLUT(vx_lut *l) { return ownReleaseReferenceInt((vx_reference *)l, VX_TYPE_LUT, VX_EXTERNAL, NULL); } VX_API_ENTRY vx_status VX_API_CALL vxQueryLUT(vx_lut l, vx_enum attribute, void *ptr, vx_size size) { vx_status status = VX_SUCCESS; vx_lut_t *lut = (vx_lut_t *)l; if (ownIsValidSpecificReference(&lut->base, VX_TYPE_LUT) == vx_false_e) return VX_ERROR_INVALID_REFERENCE; switch (attribute) { case VX_LUT_TYPE: if (VX_CHECK_PARAM(ptr, size, vx_enum, 0x3)) { *(vx_enum *)ptr = lut->item_type; } else { status = VX_ERROR_INVALID_PARAMETERS; } break; case VX_LUT_COUNT: if (VX_CHECK_PARAM(ptr, size, vx_size, 0x3)) { *(vx_size *)ptr = lut->num_items; } else { status = VX_ERROR_INVALID_PARAMETERS; } break; case VX_LUT_SIZE: if (VX_CHECK_PARAM(ptr, size, vx_size, 0x3)) { *(vx_size *)ptr = lut->num_items * lut->item_size; } else { status = VX_ERROR_INVALID_PARAMETERS; } break; case VX_LUT_OFFSET: if (VX_CHECK_PARAM(ptr, size, vx_uint32, 0x3)) { *(vx_uint32 *)ptr = lut->offset; } else { status = VX_ERROR_INVALID_PARAMETERS; } break; default: status = VX_ERROR_NOT_SUPPORTED; break; } return status; } VX_API_ENTRY vx_status VX_API_CALL vxAccessLUT(vx_lut l, void **ptr, vx_enum usage) { vx_status status = VX_FAILURE; vx_lut_t *lut = (vx_lut_t *)l; if (ownIsValidSpecificReference(&lut->base, VX_TYPE_LUT) == vx_true_e) { status = ownAccessArrayRangeInt((vx_array_t *)l, 0, lut->num_items, NULL, ptr, usage); } else { VX_PRINT(VX_ZONE_ERROR, "Not a valid object!\n"); } return status; } VX_API_ENTRY vx_status VX_API_CALL vxCommitLUT(vx_lut l, const void *ptr) { vx_status status = VX_FAILURE; vx_lut_t *lut = (vx_lut_t *)l; if (ownIsValidSpecificReference(&lut->base, VX_TYPE_LUT) == vx_true_e) { status = ownCommitArrayRangeInt((vx_array_t *)l, 0, lut->num_items, ptr); } else { VX_PRINT(VX_ZONE_ERROR, "Not a valid object!\n"); } return status; } VX_API_ENTRY vx_status VX_API_CALL vxCopyLUT(vx_lut l, void *user_ptr, vx_enum usage, vx_enum user_mem_type) { vx_status status = VX_FAILURE; vx_lut_t *lut = (vx_lut_t *)l; if (ownIsValidSpecificReference(&lut->base, VX_TYPE_LUT) == vx_true_e) { vx_size stride = lut->item_size; #ifdef OPENVX_USE_OPENCL_INTEROP void * user_ptr_given = user_ptr; vx_enum user_mem_type_given = user_mem_type; if (user_mem_type == VX_MEMORY_TYPE_OPENCL_BUFFER) { // get ptr from OpenCL buffer for HOST size_t size = 0; cl_mem opencl_buf = (cl_mem)user_ptr; cl_int cerr = clGetMemObjectInfo(opencl_buf, CL_MEM_SIZE, sizeof(size_t), &size, NULL); VX_PRINT(VX_ZONE_CONTEXT, "OPENCL: vxCopyLUT: clGetMemObjectInfo(%p) => (%d)\n", opencl_buf, cerr); if (cerr != CL_SUCCESS) { return VX_ERROR_INVALID_PARAMETERS; } user_ptr = clEnqueueMapBuffer(lut->base.context->opencl_command_queue, opencl_buf, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, size, 0, NULL, NULL, &cerr); VX_PRINT(VX_ZONE_CONTEXT, "OPENCL: vxCopyLUT: clEnqueueMapBuffer(%p,%d) => %p (%d)\n", opencl_buf, (int)size, user_ptr, cerr); if (cerr != CL_SUCCESS) { return VX_ERROR_INVALID_PARAMETERS; } user_mem_type = VX_MEMORY_TYPE_HOST; } #endif status = ownCopyArrayRangeInt((vx_array_t *)l, 0, lut->num_items, stride, user_ptr, usage, user_mem_type); #ifdef OPENVX_USE_OPENCL_INTEROP if (user_mem_type_given == VX_MEMORY_TYPE_OPENCL_BUFFER) { clEnqueueUnmapMemObject(lut->base.context->opencl_command_queue, (cl_mem)user_ptr_given, user_ptr, 0, NULL, NULL); clFinish(lut->base.context->opencl_command_queue); } #endif } else { VX_PRINT(VX_ZONE_ERROR, "Not a valid object!\n"); } return status; } VX_API_ENTRY vx_status VX_API_CALL vxMapLUT(vx_lut l, vx_map_id *map_id, void **ptr, vx_enum usage, vx_enum mem_type, vx_bitfield flags) { vx_status status = VX_FAILURE; vx_lut_t *lut = (vx_lut_t *)l; if (ownIsValidSpecificReference(&lut->base, VX_TYPE_LUT) == vx_true_e) { #ifdef OPENVX_USE_OPENCL_INTEROP vx_enum mem_type_requested = mem_type; if (mem_type == VX_MEMORY_TYPE_OPENCL_BUFFER) { mem_type = VX_MEMORY_TYPE_HOST; } #endif vx_size stride = lut->item_size; status = ownMapArrayRangeInt((vx_array_t *)lut, 0, lut->num_items, map_id, &stride, ptr, usage, mem_type, flags); #ifdef OPENVX_USE_OPENCL_INTEROP vx_size size = lut->num_items * stride; if ((status == VX_SUCCESS) && lut->base.context->opencl_context && (mem_type_requested == VX_MEMORY_TYPE_OPENCL_BUFFER) && (size > 0) && ptr && *ptr) { /* create OpenCL buffer using the host allocated pointer */ cl_int cerr = 0; cl_mem opencl_buf = clCreateBuffer(lut->base.context->opencl_context, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, size, *ptr, &cerr); VX_PRINT(VX_ZONE_CONTEXT, "OPENCL: vxMapLUT: clCreateBuffer(%u) => %p (%d)\n", (vx_uint32)size, opencl_buf, cerr); if (cerr == CL_SUCCESS) { lut->base.context->memory_maps[*map_id].opencl_buf = opencl_buf; *ptr = opencl_buf; } else { status = VX_FAILURE; } } #endif } else { VX_PRINT(VX_ZONE_ERROR, "Not a valid object!\n"); } return status; } VX_API_ENTRY vx_status VX_API_CALL vxUnmapLUT(vx_lut l, vx_map_id map_id) { vx_status status = VX_FAILURE; vx_lut_t *lut = (vx_lut_t *)l; if (ownIsValidSpecificReference(&lut->base, VX_TYPE_LUT) == vx_true_e) { #ifdef OPENVX_USE_OPENCL_INTEROP if (lut->base.context->opencl_context && lut->base.context->memory_maps[map_id].opencl_buf && lut->base.context->memory_maps[map_id].ptr) { clEnqueueUnmapMemObject(lut->base.context->opencl_command_queue, lut->base.context->memory_maps[map_id].opencl_buf, lut->base.context->memory_maps[map_id].ptr, 0, NULL, NULL); clFinish(lut->base.context->opencl_command_queue); cl_int cerr = clReleaseMemObject(lut->base.context->memory_maps[map_id].opencl_buf); VX_PRINT(VX_ZONE_CONTEXT, "OPENCL: vxUnmapLUT: clReleaseMemObject(%p) => (%d)\n", lut->base.context->memory_maps[map_id].opencl_buf, cerr); lut->base.context->memory_maps[map_id].opencl_buf = NULL; } #endif status = ownUnmapArrayRangeInt((vx_array_t *)l, map_id); } else { VX_PRINT(VX_ZONE_ERROR, "Not a valid object!\n"); } return status; }
aa8621b00a6c7490eac13457f01f5b1be988d15f
39568e19301a7a112398be542154950af25591de
/sw/device/lib/dif/autogen/dif_spi_host_autogen.h
52773b209606652efcefc32b6fe475a7c91b5fc2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lowRISC/opentitan
493995bc7cf7cb3aee486a5203af3fd62bba3bfc
51f6017b8425b14d5a4aa9abace8fe5a25ef08c8
refs/heads/master
2023-08-31T22:05:09.425796
2023-08-14T14:52:15
2023-08-31T20:31:13
204,516,692
2,077
634
Apache-2.0
2023-09-14T21:16:21
2019-08-26T16:30:16
SystemVerilog
UTF-8
C
false
false
7,550
h
dif_spi_host_autogen.h
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #ifndef OPENTITAN_SW_DEVICE_LIB_DIF_AUTOGEN_DIF_SPI_HOST_AUTOGEN_H_ #define OPENTITAN_SW_DEVICE_LIB_DIF_AUTOGEN_DIF_SPI_HOST_AUTOGEN_H_ // THIS FILE HAS BEEN GENERATED, DO NOT EDIT MANUALLY. COMMAND: // util/make_new_dif.py --mode=regen --only=autogen /** * @file * @brief <a href="/hw/ip/spi_host/doc/">SPI_HOST</a> Device Interface Functions */ #include <stdbool.h> #include <stdint.h> #include "sw/device/lib/base/macros.h" #include "sw/device/lib/base/mmio.h" #include "sw/device/lib/dif/dif_base.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus /** * A handle to spi_host. * * This type should be treated as opaque by users. */ typedef struct dif_spi_host { /** * The base address for the spi_host hardware registers. */ mmio_region_t base_addr; } dif_spi_host_t; /** * Creates a new handle for a(n) spi_host peripheral. * * This function does not actuate the hardware. * * @param base_addr The MMIO base address of the spi_host peripheral. * @param[out] spi_host Out param for the initialized handle. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_init(mmio_region_t base_addr, dif_spi_host_t *spi_host); /** * A spi_host alert type. */ typedef enum dif_spi_host_alert { /** * This fatal alert is triggered when a fatal TL-UL bus integrity fault is * detected. */ kDifSpiHostAlertFatalFault = 0, } dif_spi_host_alert_t; /** * Forces a particular alert, causing it to be escalated as if the hardware * had raised it. * * @param spi_host A spi_host handle. * @param alert The alert to force. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_alert_force(const dif_spi_host_t *spi_host, dif_spi_host_alert_t alert); /** * A spi_host interrupt request type. */ typedef enum dif_spi_host_irq { /** * Error-related interrupts, see !!ERROR_ENABLE register for more information. */ kDifSpiHostIrqError = 0, /** * Event-related interrupts, see !!EVENT_ENABLE register for more information. */ kDifSpiHostIrqSpiEvent = 1, } dif_spi_host_irq_t; /** * A snapshot of the state of the interrupts for this IP. * * This is an opaque type, to be used with the `dif_spi_host_irq_get_state()` * and `dif_spi_host_irq_acknowledge_state()` functions. */ typedef uint32_t dif_spi_host_irq_state_snapshot_t; /** * Returns the type of a given interrupt (i.e., event or status) for this IP. * * @param spi_host A spi_host handle. * @param irq An interrupt request. * @param[out] type Out-param for the interrupt type. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_irq_get_type(const dif_spi_host_t *spi_host, dif_spi_host_irq_t irq, dif_irq_type_t *type); /** * Returns the state of all interrupts (i.e., pending or not) for this IP. * * @param spi_host A spi_host handle. * @param[out] snapshot Out-param for interrupt state snapshot. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_irq_get_state( const dif_spi_host_t *spi_host, dif_spi_host_irq_state_snapshot_t *snapshot); /** * Returns whether a particular interrupt is currently pending. * * @param spi_host A spi_host handle. * @param irq An interrupt request. * @param[out] is_pending Out-param for whether the interrupt is pending. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_irq_is_pending(const dif_spi_host_t *spi_host, dif_spi_host_irq_t irq, bool *is_pending); /** * Acknowledges all interrupts that were pending at the time of the state * snapshot. * * @param spi_host A spi_host handle. * @param snapshot Interrupt state snapshot. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_irq_acknowledge_state( const dif_spi_host_t *spi_host, dif_spi_host_irq_state_snapshot_t snapshot); /** * Acknowledges all interrupts, indicating to the hardware that all * interrupts have been successfully serviced. * * @param spi_host A spi_host handle. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_irq_acknowledge_all(const dif_spi_host_t *spi_host); /** * Acknowledges a particular interrupt, indicating to the hardware that it has * been successfully serviced. * * @param spi_host A spi_host handle. * @param irq An interrupt request. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_irq_acknowledge(const dif_spi_host_t *spi_host, dif_spi_host_irq_t irq); /** * Forces a particular interrupt, causing it to be serviced as if hardware had * asserted it. * * @param spi_host A spi_host handle. * @param irq An interrupt request. * @param val Value to be set. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_irq_force(const dif_spi_host_t *spi_host, dif_spi_host_irq_t irq, const bool val); /** * A snapshot of the enablement state of the interrupts for this IP. * * This is an opaque type, to be used with the * `dif_spi_host_irq_disable_all()` and `dif_spi_host_irq_restore_all()` * functions. */ typedef uint32_t dif_spi_host_irq_enable_snapshot_t; /** * Checks whether a particular interrupt is currently enabled or disabled. * * @param spi_host A spi_host handle. * @param irq An interrupt request. * @param[out] state Out-param toggle state of the interrupt. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_irq_get_enabled(const dif_spi_host_t *spi_host, dif_spi_host_irq_t irq, dif_toggle_t *state); /** * Sets whether a particular interrupt is currently enabled or disabled. * * @param spi_host A spi_host handle. * @param irq An interrupt request. * @param state The new toggle state for the interrupt. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_irq_set_enabled(const dif_spi_host_t *spi_host, dif_spi_host_irq_t irq, dif_toggle_t state); /** * Disables all interrupts, optionally snapshotting all enable states for later * restoration. * * @param spi_host A spi_host handle. * @param[out] snapshot Out-param for the snapshot; may be `NULL`. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_irq_disable_all( const dif_spi_host_t *spi_host, dif_spi_host_irq_enable_snapshot_t *snapshot); /** * Restores interrupts from the given (enable) snapshot. * * @param spi_host A spi_host handle. * @param snapshot A snapshot to restore from. * @return The result of the operation. */ OT_WARN_UNUSED_RESULT dif_result_t dif_spi_host_irq_restore_all( const dif_spi_host_t *spi_host, const dif_spi_host_irq_enable_snapshot_t *snapshot); #ifdef __cplusplus } // extern "C" #endif // __cplusplus #endif // OPENTITAN_SW_DEVICE_LIB_DIF_AUTOGEN_DIF_SPI_HOST_AUTOGEN_H_
4ca5a64f7054b65cc337e2c4e745fb0bd3a6ad90
0ff5c3178e87a28a82165bfa908d9319cf7a2323
/10. Linked List/c lang/Linked List.c
224a992a5ce17aea45e043b174bf1a328321b38d
[ "MIT" ]
permissive
SR-Sunny-Raj/Hacktoberfest2021-DSA
40bf8385ed976fd81d27340514579b283c339c1f
116526c093ed1ac7907483d001859df63c902cb3
refs/heads/master
2023-01-31T07:46:26.016367
2023-01-26T12:45:32
2023-01-26T12:45:32
262,236,251
261
963
MIT
2023-03-25T14:22:10
2020-05-08T05:36:07
C++
UTF-8
C
false
false
10,701
c
Linked List.c
// 5. Practical : Linked List – 1 // Write a menu driven program to implement following operations on the singly linked list. Design a function create to create a link list (which is required to be called only for one time for a link list) // (a) create [ node * create() ] // (b) display [ void display(node *start) ] // (c) length [ int length (node *start) ] // (d) maximum [int maximum (node *start)] // (e) merge (to merge two link list in to the third one) [node * merge(node *start1, node *start2) // (f) sort [void sort(node *start) ] // (g) reverse [ node * reverse (node *start)] // (h) Insert a node at the front of the linked list. [ node * insert_front(node *start, int no) ] // (i) Insert a node at the end of the linked list. [ node * insert_end(node *start, int no) ] // (j) Insert a node such that linked list is in ascending order.(according to info. Field) [ node * insert_sort(node *start, int no) ] // (k) Delete a first node of the linked list. [ node * delete_first(node *start) ] // (l) Delete a node before specified position. [ node * delete_before(node *start, int pos) ] // (m) Delete a node after specified position. [ node * delete_after(node *, int pos) ] // (n) No search [ int search (node*, int x) ] #include <stdio.h> #include <stdlib.h> struct node{ int info; struct node *link; }; struct node *create(); void display(struct node *start); int length (struct node *start); int maximum (struct node *start); struct node * merge(struct node *start1, struct node *start2); void sort(struct node *start); struct node * reverse (struct node *start); struct node * insert_front(struct node *start, int no); struct node * insert_end(struct node *start, int no); struct node * insert_sort(struct node *start, int no); struct node * delete_first(struct node *start); struct node * delete_before(struct node *start, int pos); struct node * delete_after(struct node *start, int pos); int search (struct node *start, int x); int isNull(struct node *start); int isEmpty(); void push(int *stack, int *top, int value); int pop(int *stack, int *top); int main(){ int operation, value, ans; struct node *head = NULL, *head1; printf("\n Ahmed Aghadi 200420107043\n"); do{ printf("\n****************************\n"); printf("\nEnter operation value\n"); printf("\n1. Create"); printf("\n2. Display"); printf("\n3. Length"); printf("\n4. Maximum"); printf("\n5. Merge"); printf("\n6. Sort"); printf("\n7. Reverse"); printf("\n8. Insert at front"); printf("\n9. insert at end"); printf("\n10. Insert by sort"); printf("\n11. Delete first"); printf("\n12. Delete before"); printf("\n13. Delete after"); printf("\n14. Search"); printf("\n15. Exit"); printf("\n****************************\n"); printf("Operation = "); scanf("%d",&operation); printf("\n"); if(operation>1&&operation<15){ if(isNull(head)){ continue; } } switch(operation){ case 1: head = create(); break; case 2: display(head); break; case 3: ans = length(head); printf("Length = %d", ans); break; case 4: ans = maximum(head); printf("Maximum = %d", ans); break; case 5: printf("\nFor Second Linked List : \n"); head1 = create(); head = merge(head, head1); display(head); break; case 6: sort(head); break; case 7: head = reverse(head); display(head); break; case 8: printf("Enter value to be inserted : "); scanf("%d",&value); head = insert_front(head, value); break; case 9: printf("Enter value to be inserted : "); scanf("%d",&value); head = insert_end(head, value); break; case 10: printf("Enter value to be inserted : "); scanf("%d",&value); head = insert_sort(head, value); break; case 11: head = delete_first(head); break; case 12: printf("Enter position : "); scanf("%d",&value); head = delete_before(head,value); break; case 13: printf("Enter position : "); scanf("%d",&value); head = delete_after(head,value); case 14: printf("Enter value to be searched : "); scanf("%d",&value); ans = search(head, value); if(ans==-1){ printf("Value not found"); break; } printf("Value is found at position %d",ans); break; case 15: break; default: printf("\nEnter operation value between 1 and 15\n"); } }while(operation!=15); } struct node *create(){ int value; struct node *first; first = (struct node *)malloc(sizeof(struct node)); if(first == NULL){ printf("Memory not allocated"); } printf("Enter value of first node : "); scanf("%d",&value); first->info = value; first->link = NULL; return first; } void display(struct node *start){ while(start != NULL){ printf("\n%d",start->info); start = start->link; } } int length (struct node *start){ int len = 0; while(start!=NULL){ len++; start=start->link; } return len; } int maximum (struct node *start){ int max = start->info; start = start->link; while(start!=NULL){ if(start->info>max){ max = start->info; } start = start->link; } return max; } struct node * merge(struct node *start1, struct node *start2){ struct node *first; first = (struct node *)malloc(sizeof(struct node)); if(length(start1)==0){ return start2; } if(length(start2)==0){ return start1; } first = start1; while(start1->link!=NULL){ start1 = start1->link; } start1->link = start2; return first; } void sort(struct node *start){ int i,j,temp,len; struct node *current, *toCheck; len = length(start); current = start; for(i = 0; i< len-1; i++){ toCheck = current->link; for(j = i+1; j < len; j++){ if(toCheck->info<current->info){ temp = toCheck->info; toCheck->info = current->info; current->info = temp; } toCheck = toCheck->link; } current = current->link; } } struct node * reverse (struct node *start){ int *stack = (int*)calloc(length(start),sizeof(int)), top = 1, i = 0, j = 0; struct node *head = (struct node *)malloc(sizeof(struct node)), *temp; if(length(start)==1){ head = start; return head; } while(start!=NULL){ push(stack,&top,start->info); start = start->link; } // head->info = pop(stack,&top); temp = head; while(1){ temp->info=pop(stack,&top); if(top>1){ temp->link = (struct node *)malloc(sizeof(struct node)); temp = temp->link; } else{ temp->link = NULL; break; } } return head; } struct node * insert_front(struct node *start, int no){ struct node *first; first = (struct node *)malloc(sizeof(struct node)); if(first == NULL){ printf("Memory not allocated"); } first->info = no; first->link=start; return first; } struct node * insert_end(struct node *start, int no){ struct node *temp = start, *end; end = (struct node *)malloc(sizeof(struct node)); end->info = no; end->link = NULL; while(temp->link!=NULL){ temp = temp->link; } temp->link = end; return start; } struct node * insert_sort(struct node *start, int no){ struct node *toAdd, *temp = start; toAdd = (struct node *)malloc(sizeof(struct node)); toAdd->info = no; if(start->info>no){ toAdd->link = start; return toAdd; } while(temp->link!=NULL){ if(temp->link->info>no){ toAdd->link = temp->link; temp->link= toAdd; return start; } temp = temp->link; } temp->link = toAdd; toAdd->link = NULL; return start; } struct node * delete_first(struct node *start){ struct node *head = start->link; if(length(start)==1){ printf("\nLength of Linked List is 1 and thus first element can't be deleted.\n"); return start; } free(start); return head; } struct node * delete_before(struct node *start, int pos){ struct node *temp = start, *toDelete = temp->link; if(pos<2||pos>length(start)+1||length(start)==1){ printf("Invalid Position"); return start; } while(pos-->3){ temp = temp->link; } toDelete = temp->link; temp->link = toDelete->link; free(toDelete); return start; } struct node * delete_after(struct node *start, int pos){ struct node *temp = start, *toDelete = temp->link; if(pos<1||pos>length(start)-1||length(start)==1){ printf("Invalid Position"); return start; } while(pos-->1){ temp = temp->link; } toDelete = temp->link; temp->link = toDelete->link; free(toDelete); return start; } int search (struct node *start, int x){ int i = 1; while(start!=NULL){ if(start->info==x){ return i; } start = start->link; i++; } return -1; } int isNull(struct node *start){ if(start == NULL){ printf("\nLinked List not created.\n"); return 1; } return 0; } int isEmpty(int top){ if(top==-1){ return 1; }else{ return 0; } } void push(int *stack, int *top, int value){ (*top)++; stack[*top] = value; } int pop(int *stack, int *top){ if(isEmpty(*top)){ printf("Stack is Empty!"); exit(0); } (*top)--; return stack[(*top)+1]; }
69f18995a5fa503e77adddcf6fdeffe5186eea63
272ed2f127ad42b0cb2597bc44a27565a608d444
/hoult-primes.c
eaf5c691423fc2c12bac3f40c48a9af028f2ae99
[]
no_license
carlosedp/riscv-bringup
ccfb402fba7d22f8850864a17624c49f40ddf7b2
548b1de5a06c240f8c7dbe59959ecf35b53e5450
refs/heads/master
2023-07-26T13:09:30.791115
2022-10-31T23:29:52
2022-10-31T23:30:00
189,597,593
225
35
null
2023-07-07T19:11:06
2019-05-31T13:22:37
Shell
UTF-8
C
false
false
6,218
c
hoult-primes.c
// Copyright 2016-2020 Bruce hoult bruce@hoult.org // // 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. // // Program to count primes. I wanted something that could run in 16 KB but took enough // time to measure on a modern x86 and is not susceptible to optimizer tricks. // Code size is for just the countPrimes() function with gcc -O. // // Original x86&ARM data 2016, received user contributions 2019&2020 from eevblog members. // // SZ = 1000 -> 3713160 primes, all primes up to 7919^2 = 62710561 // 2.735 sec i7 8650U @ 4.2 GHz 242 bytes 11.5 billion clocks // 2.795 sec Mac Mini M1 @ 3.2 GHz 212 bytes 8.9 billion clocks // 2.810 sec Mac Mini M1 arm64 Ubuntu in VM 280 bytes 9.0 billion clocks // 2.872 sec i7 6700K @ 4.2 GHz 240 bytes 12.1 billion clocks // 2.925 sec Mac Mini M1 @ 3.2 GHz Rosetta 208 bytes 9.4 billion clocks // 3.448 sec Ryzen 5 4500U @ 4.0 GHz WSL2 242 bytes 13.8 billion clocks // 3.505 sec Xeon Plat 8151 @ 4.0 GHz (AWS z1d) 244 bytes 14.0 billion clocks // 3.515 sec Threadripper 2990WX @ 4.2 GHz 242 bytes 14.8 billion clocks // 3.836 sec i7 4700MQ @ 3.4 GHz 258 bytes 13.0 billion clocks // 3.972 sec i7 8650U @ 4.2 GHz webasm 277 bytes 16.7 billion clocks // 4.868 sec i7 3770 @ 3.9 GHz 240 bytes 19.0 billion clocks // 6.377 sec AWS C6g graviton2 A64 @ 2.5 GHz 276 bytes 15.9 billion clocks // 6.757 sec M1 Mini, qemu-riscv64 in UbuntuVM 216 bytes 23.0 billion clocks // 8.538 sec NXP LX2160A A72 @ 2 GHz 260 bytes 17.1 billion clocks // 9.692 sec RISC-V Fedora in qemu in VM on M1 208 bytes 31.0 billion clocks // 9.740 sec i7 6700K qemu-riscv32 178 bytes 40.9 billion clocks // 10.046 sec i7 8650U @ 4.2 GHz qemu-riscv32 190 bytes 42.2 billion clocks // 11.190 sec Pi4 Cortex A72 @ 1.5 GHz T32 232 bytes 16.8 billion clocks // 11.445 sec Odroid XU4 A15 @ 2 GHz 204 bytes 22.9 billion clocks // 12.115 sec Pi4 Cortex A72 @ 1.5 GHz A64 300 bytes 18.2 billion clocks // 12.605 sec Pi4 Cortex A72 @ 1.5 GHz A32 300 bytes 18.9 billion clocks // 13.721 sec RISC-V Fedora in qemu on 2990wx 208 bytes 57.6 billion clocks // 17.394 sec RISCV U74 @1500 MHz (est vs FPGA) 228 bytes 26.1 billion clocks // 19.500 sec Odroid C2 A53 @ 1.536 GHz A64 276 bytes 30.0 billion clocks // 23.940 sec Odroid C2 A53 @ 1.536 GHz T32 204 bytes 36.8 billion clocks // 24.636 sec i7 6700K qemu-arm 204 bytes 103.5 billion clocks // 25.060 sec i7 6700K qemu-aarch64 276 bytes 105.3 billion clocks // 27.196 sec Teensy 4.0 Cortex M7 @ 960 MHz 228 bytes 26.1 billion clocks // 27.480 sec HiFive Unl RISCV U54 @ 1.45 GHz 228 bytes 39.8 billion clocks // 30.420 sec Pi3 Cortex A53 @ 1.2 GHz T32 204 bytes 36.5 billion clocks // 39.840 sec HiFive Unl RISCV U54 @ 1.0 GHz 228 bytes 39.8 billion clocks // 43.516 sec Teensy 4.0 Cortex M7 @ 600 MHz 228 bytes 26.1 billion clocks // 47.910 sec Pi2 Cortex A7 @ 900 MHz T32 204 bytes 42.1 billion clocks // 48.206 sec Zynq-7010 Cortex A9 @ 650MHz 248 bytes 31.3 billion clocks // 112.163 sec HiFive1 RISCV E31 @ 320 MHz 178 bytes 35.9 billion clocks // 260.907 sec RISCV U74 @ 100 MHz FPGA 228 bytes 26.1 billion clocks // 261.068 sec esp32/Arduino @ 240 MHz ??? bytes 62.7 billion clocks // 294.749 sec chipKIT Pro MZ pic32 @ 200 MHz ??? bytes 58.9 billion clocks // 306.988 sec esp8266 @ 160 MHz ??? bytes 49.1 billion clocks // 309.251 sec BlackPill Cortex M4F @ 168 MHz 228 bytes 52.0 billion clocks // 927.547 sec BluePill Cortex M3 @ 72 MHz 228 bytes 66.8 billion clocks // 13449.513 sec AVR ATmega2560 @ 20 MHz 318 bytes 269.0 billion clocks #include <stdio.h> #include <time.h> #include <stdint.h> #define SZ 1000 int32_t primes[SZ], sieve[SZ]; int nSieve = 0; int32_t countPrimes(){ primes[0] = 2; sieve[0] = 4; ++nSieve; int32_t nPrimes = 1, trial = 3, sqr=2; while (1){ while (sqr*sqr <= trial) ++sqr; --sqr; for (int i=0; i<nSieve; ++i){ if (primes[i] > sqr) goto found_prime; while (sieve[i] < trial) sieve[i] += primes[i]; if (sieve[i] == trial) goto try_next; } break; found_prime: if (nSieve < SZ){ primes[nSieve] = trial; sieve[nSieve] = trial*trial; ++nSieve; // printf("Saved %d: %d\n", nSieve, trial); } ++nPrimes; try_next: trial+=1; } return nPrimes; } int main(){ printf("Starting run\n"); clock_t start = clock(); int res = countPrimes(); int ms = (clock() - start) / (CLOCKS_PER_SEC / 1000.0) + 0.5; // Size calculation does not work if opt >1 or if compiler or linker // otherwise reorders functions in the binary. int codeSz = (char*)main - (char*)countPrimes; printf("%d primes found in %d ms\n", res, ms); printf("%d bytes of code in countPrimes()\n", codeSz); return 0; }
021621b36d25100ce31f8b0644b425d8deda1624
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/third_party/python/Parser/tokenizer.c
559bd823565c591a288ac16d217e21e895dad892
[ "Python-2.0", "GPL-1.0-or-later", "LicenseRef-scancode-python-cwi", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-other-copyleft", "ISC" ]
permissive
jart/cosmopolitan
fb11b5658939023977060a7c6c71a74093d9cb44
0d748ad58e1063dd1f8560f18a0c75293b9415b7
refs/heads/master
2023-09-06T09:17:29.303607
2023-09-02T03:49:13
2023-09-02T03:50:18
272,457,606
11,887
435
ISC
2023-09-14T17:47:58
2020-06-15T14:16:13
C
UTF-8
C
false
false
58,199
c
tokenizer.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "third_party/python/Include/errcode.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Parser/tokenizer.h" #ifndef PGEN #include "libc/calls/weirdtypes.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/unicodeobject.h" #endif /* clang-format off */ /* Tokenizer implementation */ #define is_potential_identifier_start(c) (\ (c >= 'a' && c <= 'z')\ || (c >= 'A' && c <= 'Z')\ || c == '_'\ || (c >= 128)) #define is_potential_identifier_char(c) (\ (c >= 'a' && c <= 'z')\ || (c >= 'A' && c <= 'Z')\ || (c >= '0' && c <= '9')\ || c == '_'\ || (c >= 128)) extern char *PyOS_Readline(FILE *, FILE *, const char *); /* Return malloc'ed string including trailing \n; empty malloc'ed string for EOF; NULL if interrupted */ /* Don't ever change this -- it would break the portability of Python code */ #define TABSIZE 8 /* Forward */ static struct tok_state *tok_new(void); static int tok_nextc(struct tok_state *tok); static void tok_backup(struct tok_state *tok, int c); /* Token names */ const char *_PyParser_TokenNames[] = { "ENDMARKER", "NAME", "NUMBER", "STRING", "NEWLINE", "INDENT", "DEDENT", "LPAR", "RPAR", "LSQB", "RSQB", "COLON", "COMMA", "SEMI", "PLUS", "MINUS", "STAR", "SLASH", "VBAR", "AMPER", "LESS", "GREATER", "EQUAL", "DOT", "PERCENT", "LBRACE", "RBRACE", "EQEQUAL", "NOTEQUAL", "LESSEQUAL", "GREATEREQUAL", "TILDE", "CIRCUMFLEX", "LEFTSHIFT", "RIGHTSHIFT", "DOUBLESTAR", "PLUSEQUAL", "MINEQUAL", "STAREQUAL", "SLASHEQUAL", "PERCENTEQUAL", "AMPEREQUAL", "VBAREQUAL", "CIRCUMFLEXEQUAL", "LEFTSHIFTEQUAL", "RIGHTSHIFTEQUAL", "DOUBLESTAREQUAL", "DOUBLESLASH", "DOUBLESLASHEQUAL", "AT", "ATEQUAL", "RARROW", "ELLIPSIS", /* This table must match the #defines in token.h! */ "OP", "AWAIT", "ASYNC", "<ERRORTOKEN>", "<N_TOKENS>" }; /* Create and initialize a new tok_state structure */ static struct tok_state * tok_new(void) { struct tok_state *tok = (struct tok_state *)PyMem_MALLOC( sizeof(struct tok_state)); if (tok == NULL) return NULL; tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL; tok->done = E_OK; tok->fp = NULL; tok->input = NULL; tok->tabsize = TABSIZE; tok->indent = 0; tok->indstack[0] = 0; tok->atbol = 1; tok->pendin = 0; tok->prompt = tok->nextprompt = NULL; tok->lineno = 0; tok->level = 0; tok->altwarning = 1; tok->alterror = 1; tok->alttabsize = 1; tok->altindstack[0] = 0; tok->decoding_state = STATE_INIT; tok->decoding_erred = 0; tok->read_coding_spec = 0; tok->enc = NULL; tok->encoding = NULL; tok->cont_line = 0; #ifndef PGEN tok->filename = NULL; tok->decoding_readline = NULL; tok->decoding_buffer = NULL; #endif tok->async_def = 0; tok->async_def_indent = 0; tok->async_def_nl = 0; return tok; } static char * new_string(const char *s, Py_ssize_t len, struct tok_state *tok) { char* result = (char *)PyMem_MALLOC(len + 1); if (!result) { tok->done = E_NOMEM; return NULL; } memcpy(result, s, len); result[len] = '\0'; return result; } #ifdef PGEN static char * decoding_fgets(char *s, int size, struct tok_state *tok) { return fgets(s, size, tok->fp); } static int decoding_feof(struct tok_state *tok) { return feof(tok->fp); } static char * decode_str(const char *str, int exec_input, struct tok_state *tok) { return new_string(str, strlen(str), tok); } #else /* PGEN */ static char * error_ret(struct tok_state *tok) /* XXX */ { tok->decoding_erred = 1; if (tok->fp != NULL && tok->buf != NULL) /* see PyTokenizer_Free */ PyMem_FREE(tok->buf); tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL; tok->done = E_DECODE; return NULL; /* as if it were EOF */ } static const char * get_normal_name(const char *s) /* for utf-8 and latin-1 */ { char buf[13]; int i; for (i = 0; i < 12; i++) { int c = s[i]; if (c == '\0') break; else if (c == '_') buf[i] = '-'; else buf[i] = tolower(c); } buf[i] = '\0'; if (strcmp(buf, "utf-8") == 0 || strncmp(buf, "utf-8-", 6) == 0) return "utf-8"; else if (strcmp(buf, "latin-1") == 0 || strcmp(buf, "iso-8859-1") == 0 || strcmp(buf, "iso-latin-1") == 0 || strncmp(buf, "latin-1-", 8) == 0 || strncmp(buf, "iso-8859-1-", 11) == 0 || strncmp(buf, "iso-latin-1-", 12) == 0) return "iso-8859-1"; else return s; } /* Return the coding spec in S, or NULL if none is found. */ static int get_coding_spec(const char *s, char **spec, Py_ssize_t size, struct tok_state *tok) { Py_ssize_t i; *spec = NULL; /* Coding spec must be in a comment, and that comment must be * the only statement on the source code line. */ for (i = 0; i < size - 6; i++) { if (s[i] == '#') break; if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014') return 1; } for (; i < size - 6; i++) { /* XXX inefficient search */ const char* t = s + i; if (strncmp(t, "coding", 6) == 0) { const char* begin = NULL; t += 6; if (t[0] != ':' && t[0] != '=') continue; do { t++; } while (t[0] == '\x20' || t[0] == '\t'); begin = t; while (Py_ISALNUM(t[0]) || t[0] == '-' || t[0] == '_' || t[0] == '.') t++; if (begin < t) { char* r = new_string(begin, t - begin, tok); const char* q; if (!r) return 0; q = get_normal_name(r); if (r != q) { PyMem_FREE(r); r = new_string(q, strlen(q), tok); if (!r) return 0; } *spec = r; break; } } } return 1; } /* Check whether the line contains a coding spec. If it does, invoke the set_readline function for the new encoding. This function receives the tok_state and the new encoding. Return 1 on success, 0 on failure. */ static int check_coding_spec(const char* line, Py_ssize_t size, struct tok_state *tok, int set_readline(struct tok_state *, const char *)) { char *cs; int r = 1; if (tok->cont_line) { /* It's a continuation line, so it can't be a coding spec. */ tok->read_coding_spec = 1; return 1; } if (!get_coding_spec(line, &cs, size, tok)) return 0; if (!cs) { Py_ssize_t i; for (i = 0; i < size; i++) { if (line[i] == '#' || line[i] == '\n' || line[i] == '\r') break; if (line[i] != ' ' && line[i] != '\t' && line[i] != '\014') { /* Stop checking coding spec after a line containing * anything except a comment. */ tok->read_coding_spec = 1; break; } } return 1; } tok->read_coding_spec = 1; if (tok->encoding == NULL) { assert(tok->decoding_state == STATE_RAW); if (strcmp(cs, "utf-8") == 0) { tok->encoding = cs; } else { r = set_readline(tok, cs); if (r) { tok->encoding = cs; tok->decoding_state = STATE_NORMAL; } else { PyErr_Format(PyExc_SyntaxError, "encoding problem: %s", cs); PyMem_FREE(cs); } } } else { /* then, compare cs with BOM */ r = (strcmp(tok->encoding, cs) == 0); if (!r) PyErr_Format(PyExc_SyntaxError, "encoding problem: %s with BOM", cs); PyMem_FREE(cs); } return r; } /* See whether the file starts with a BOM. If it does, invoke the set_readline function with the new encoding. Return 1 on success, 0 on failure. */ static int check_bom(int get_char(struct tok_state *), void unget_char(int, struct tok_state *), int set_readline(struct tok_state *, const char *), struct tok_state *tok) { int ch1, ch2, ch3; ch1 = get_char(tok); tok->decoding_state = STATE_RAW; if (ch1 == EOF) { return 1; } else if (ch1 == 0xEF) { ch2 = get_char(tok); if (ch2 != 0xBB) { unget_char(ch2, tok); unget_char(ch1, tok); return 1; } ch3 = get_char(tok); if (ch3 != 0xBF) { unget_char(ch3, tok); unget_char(ch2, tok); unget_char(ch1, tok); return 1; } #if 0 /* Disable support for UTF-16 BOMs until a decision is made whether this needs to be supported. */ } else if (ch1 == 0xFE) { ch2 = get_char(tok); if (ch2 != 0xFF) { unget_char(ch2, tok); unget_char(ch1, tok); return 1; } if (!set_readline(tok, "utf-16-be")) return 0; tok->decoding_state = STATE_NORMAL; } else if (ch1 == 0xFF) { ch2 = get_char(tok); if (ch2 != 0xFE) { unget_char(ch2, tok); unget_char(ch1, tok); return 1; } if (!set_readline(tok, "utf-16-le")) return 0; tok->decoding_state = STATE_NORMAL; #endif } else { unget_char(ch1, tok); return 1; } if (tok->encoding != NULL) PyMem_FREE(tok->encoding); tok->encoding = new_string("utf-8", 5, tok); if (!tok->encoding) return 0; /* No need to set_readline: input is already utf-8 */ return 1; } /* Read a line of text from TOK into S, using the stream in TOK. Return NULL on failure, else S. On entry, tok->decoding_buffer will be one of: 1) NULL: need to call tok->decoding_readline to get a new line 2) PyUnicodeObject *: decoding_feof has called tok->decoding_readline and stored the result in tok->decoding_buffer 3) PyByteArrayObject *: previous call to fp_readl did not have enough room (in the s buffer) to copy entire contents of the line read by tok->decoding_readline. tok->decoding_buffer has the overflow. In this case, fp_readl is called in a loop (with an expanded buffer) until the buffer ends with a '\n' (or until the end of the file is reached): see tok_nextc and its calls to decoding_fgets. */ static char * fp_readl(char *s, int size, struct tok_state *tok) { PyObject* bufobj; const char *buf; Py_ssize_t buflen; /* Ask for one less byte so we can terminate it */ assert(size > 0); size--; if (tok->decoding_buffer) { bufobj = tok->decoding_buffer; Py_INCREF(bufobj); } else { bufobj = PyObject_CallObject(tok->decoding_readline, NULL); if (bufobj == NULL) goto error; } if (PyUnicode_CheckExact(bufobj)) { buf = PyUnicode_AsUTF8AndSize(bufobj, &buflen); if (buf == NULL) { goto error; } } else { buf = PyByteArray_AsString(bufobj); if (buf == NULL) { goto error; } buflen = PyByteArray_GET_SIZE(bufobj); } Py_XDECREF(tok->decoding_buffer); if (buflen > size) { /* Too many chars, the rest goes into tok->decoding_buffer */ tok->decoding_buffer = PyByteArray_FromStringAndSize(buf+size, buflen-size); if (tok->decoding_buffer == NULL) goto error; buflen = size; } else tok->decoding_buffer = NULL; memcpy(s, buf, buflen); s[buflen] = '\0'; if (buflen == 0) /* EOF */ s = NULL; Py_DECREF(bufobj); return s; error: Py_XDECREF(bufobj); return error_ret(tok); } /* Set the readline function for TOK to a StreamReader's readline function. The StreamReader is named ENC. This function is called from check_bom and check_coding_spec. ENC is usually identical to the future value of tok->encoding, except for the (currently unsupported) case of UTF-16. Return 1 on success, 0 on failure. */ static int fp_setreadl(struct tok_state *tok, const char* enc) { PyObject *readline, *io, *stream; _Py_IDENTIFIER(open); _Py_IDENTIFIER(readline); int fd; long pos; fd = fileno(tok->fp); /* Due to buffering the file offset for fd can be different from the file * position of tok->fp. If tok->fp was opened in text mode on Windows, * its file position counts CRLF as one char and can't be directly mapped * to the file offset for fd. Instead we step back one byte and read to * the end of line.*/ pos = ftell(tok->fp); if (pos == -1 || lseek(fd, (off_t)(pos > 0 ? pos - 1 : pos), SEEK_SET) == (off_t)-1) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, NULL); return 0; } io = PyImport_ImportModuleNoBlock("io"); if (io == NULL) return 0; stream = _PyObject_CallMethodId(io, &PyId_open, "isisOOO", fd, "r", -1, enc, Py_None, Py_None, Py_False); Py_DECREF(io); if (stream == NULL) return 0; readline = _PyObject_GetAttrId(stream, &PyId_readline); Py_DECREF(stream); if (readline == NULL) return 0; Py_XSETREF(tok->decoding_readline, readline); if (pos > 0) { PyObject *bufobj = PyObject_CallObject(readline, NULL); if (bufobj == NULL) return 0; Py_DECREF(bufobj); } return 1; } /* Fetch the next byte from TOK. */ static int fp_getc(struct tok_state *tok) { return getc(tok->fp); } /* Unfetch the last byte back into TOK. */ static void fp_ungetc(int c, struct tok_state *tok) { ungetc(c, tok->fp); } /* Check whether the characters at s start a valid UTF-8 sequence. Return the number of characters forming the sequence if yes, 0 if not. */ static int valid_utf8(const unsigned char* s) { int expected = 0; int length; if (*s < 0x80) /* single-byte code */ return 1; if (*s < 0xc0) /* following byte */ return 0; if (*s < 0xE0) expected = 1; else if (*s < 0xF0) expected = 2; else if (*s < 0xF8) expected = 3; else return 0; length = expected + 1; for (; expected; expected--) if (s[expected] < 0x80 || s[expected] >= 0xC0) return 0; return length; } /* Read a line of input from TOK. Determine encoding if necessary. */ static char * decoding_fgets(char *s, int size, struct tok_state *tok) { char *line = NULL; int badchar = 0; for (;;) { if (tok->decoding_state == STATE_NORMAL) { /* We already have a codec associated with this input. */ line = fp_readl(s, size, tok); break; } else if (tok->decoding_state == STATE_RAW) { /* We want a 'raw' read. */ line = Py_UniversalNewlineFgets(s, size, tok->fp, NULL); break; } else { /* We have not yet determined the encoding. If an encoding is found, use the file-pointer reader functions from now on. */ if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok)) return error_ret(tok); assert(tok->decoding_state != STATE_INIT); } } if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) { if (!check_coding_spec(line, strlen(line), tok, fp_setreadl)) { return error_ret(tok); } } #ifndef PGEN /* The default encoding is UTF-8, so make sure we don't have any non-UTF-8 sequences in it. */ if (line && !tok->encoding) { unsigned char *c; int length; for (c = (unsigned char *)line; *c; c += length) if (!(length = valid_utf8(c))) { badchar = *c; break; } } if (badchar) { /* Need to add 1 to the line number, since this line has not been counted, yet. */ PyErr_Format(PyExc_SyntaxError, "Non-UTF-8 code starting with '\\x%.2x' " "in file %U on line %i, " "but no encoding declared; " "see http://python.org/dev/peps/pep-0263/ for details", badchar, tok->filename, tok->lineno + 1); return error_ret(tok); } #endif return line; } static int decoding_feof(struct tok_state *tok) { if (tok->decoding_state != STATE_NORMAL) { return feof(tok->fp); } else { PyObject* buf = tok->decoding_buffer; if (buf == NULL) { buf = PyObject_CallObject(tok->decoding_readline, NULL); if (buf == NULL) { error_ret(tok); return 1; } else { tok->decoding_buffer = buf; } } return PyObject_Length(buf) == 0; } } /* Fetch a byte from TOK, using the string buffer. */ static int buf_getc(struct tok_state *tok) { return Py_CHARMASK(*tok->str++); } /* Unfetch a byte from TOK, using the string buffer. */ static void buf_ungetc(int c, struct tok_state *tok) { tok->str--; assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */ } /* Set the readline function for TOK to ENC. For the string-based tokenizer, this means to just record the encoding. */ static int buf_setreadl(struct tok_state *tok, const char* enc) { tok->enc = enc; return 1; } /* Return a UTF-8 encoding Python string object from the C byte string STR, which is encoded with ENC. */ static PyObject * translate_into_utf8(const char* str, const char* enc) { PyObject *utf8; PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL); if (buf == NULL) return NULL; utf8 = PyUnicode_AsUTF8String(buf); Py_DECREF(buf); return utf8; } static char * translate_newlines(const char *s, int exec_input, struct tok_state *tok) { int skip_next_lf = 0; size_t needed_length = strlen(s) + 2, final_length; char *buf, *current; char c = '\0'; buf = PyMem_MALLOC(needed_length); if (buf == NULL) { tok->done = E_NOMEM; return NULL; } for (current = buf; *s; s++, current++) { c = *s; if (skip_next_lf) { skip_next_lf = 0; if (c == '\n') { c = *++s; if (!c) break; } } if (c == '\r') { skip_next_lf = 1; c = '\n'; } *current = c; } /* If this is exec input, add a newline to the end of the string if there isn't one already. */ if (exec_input && c != '\n') { *current = '\n'; current++; } *current = '\0'; final_length = current - buf + 1; if (final_length < needed_length && final_length) /* should never fail */ buf = PyMem_REALLOC(buf, final_length); return buf; } /* Decode a byte string STR for use as the buffer of TOK. Look for encoding declarations inside STR, and record them inside TOK. */ static const char * decode_str(const char *input, int single, struct tok_state *tok) { PyObject* utf8 = NULL; const char *str; const char *s; const char *newl[2] = {NULL, NULL}; int lineno = 0; tok->input = str = translate_newlines(input, single, tok); if (str == NULL) return NULL; tok->enc = NULL; tok->str = str; if (!check_bom(buf_getc, buf_ungetc, buf_setreadl, tok)) return error_ret(tok); str = tok->str; /* string after BOM if any */ assert(str); if (tok->enc != NULL) { utf8 = translate_into_utf8(str, tok->enc); if (utf8 == NULL) return error_ret(tok); str = PyBytes_AsString(utf8); } for (s = str;; s++) { if (*s == '\0') break; else if (*s == '\n') { assert(lineno < 2); newl[lineno] = s; lineno++; if (lineno == 2) break; } } tok->enc = NULL; /* need to check line 1 and 2 separately since check_coding_spec assumes a single line as input */ if (newl[0]) { if (!check_coding_spec(str, newl[0] - str, tok, buf_setreadl)) return error_ret(tok); if (tok->enc == NULL && !tok->read_coding_spec && newl[1]) { if (!check_coding_spec(newl[0]+1, newl[1] - newl[0], tok, buf_setreadl)) return error_ret(tok); } } if (tok->enc != NULL) { assert(utf8 == NULL); utf8 = translate_into_utf8(str, tok->enc); if (utf8 == NULL) return error_ret(tok); str = PyBytes_AS_STRING(utf8); } assert(tok->decoding_buffer == NULL); tok->decoding_buffer = utf8; /* CAUTION */ return str; } #endif /* PGEN */ /* Set up tokenizer for string */ struct tok_state * PyTokenizer_FromString(const char *str, int exec_input) { struct tok_state *tok = tok_new(); if (tok == NULL) return NULL; str = decode_str(str, exec_input, tok); if (str == NULL) { PyTokenizer_Free(tok); return NULL; } /* XXX: constify members. */ tok->buf = tok->cur = tok->end = tok->inp = (char*)str; return tok; } struct tok_state * PyTokenizer_FromUTF8(const char *str, int exec_input) { struct tok_state *tok = tok_new(); if (tok == NULL) return NULL; #ifndef PGEN tok->input = str = translate_newlines(str, exec_input, tok); #endif if (str == NULL) { PyTokenizer_Free(tok); return NULL; } tok->decoding_state = STATE_RAW; tok->read_coding_spec = 1; tok->enc = NULL; tok->str = str; tok->encoding = (char *)PyMem_MALLOC(6); if (!tok->encoding) { PyTokenizer_Free(tok); return NULL; } strcpy(tok->encoding, "utf-8"); /* XXX: constify members. */ tok->buf = tok->cur = tok->end = tok->inp = (char*)str; return tok; } /* Set up tokenizer for file */ struct tok_state * PyTokenizer_FromFile(FILE *fp, const char* enc, const char *ps1, const char *ps2) { struct tok_state *tok = tok_new(); if (tok == NULL) return NULL; if ((tok->buf = (char *)PyMem_MALLOC(BUFSIZ)) == NULL) { PyTokenizer_Free(tok); return NULL; } tok->cur = tok->inp = tok->buf; tok->end = tok->buf + BUFSIZ; tok->fp = fp; tok->prompt = ps1; tok->nextprompt = ps2; if (enc != NULL) { /* Must copy encoding declaration since it gets copied into the parse tree. */ tok->encoding = PyMem_MALLOC(strlen(enc)+1); if (!tok->encoding) { PyTokenizer_Free(tok); return NULL; } strcpy(tok->encoding, enc); tok->decoding_state = STATE_NORMAL; } return tok; } /* Free a tok_state structure */ void PyTokenizer_Free(struct tok_state *tok) { if (tok->encoding != NULL) PyMem_FREE(tok->encoding); #ifndef PGEN Py_XDECREF(tok->decoding_readline); Py_XDECREF(tok->decoding_buffer); Py_XDECREF(tok->filename); #endif if (tok->fp != NULL && tok->buf != NULL) PyMem_FREE(tok->buf); if (tok->input) PyMem_FREE((char *)tok->input); PyMem_FREE(tok); } /* Get next char, updating state; error code goes into tok->done */ static int tok_nextc(struct tok_state *tok) { for (;;) { if (tok->cur != tok->inp) { return Py_CHARMASK(*tok->cur++); /* Fast path */ } if (tok->done != E_OK) return EOF; if (tok->fp == NULL) { char *end = strchr(tok->inp, '\n'); if (end != NULL) end++; else { end = strchr(tok->inp, '\0'); if (end == tok->inp) { tok->done = E_EOF; return EOF; } } if (tok->start == NULL) tok->buf = tok->cur; tok->line_start = tok->cur; tok->lineno++; tok->inp = end; return Py_CHARMASK(*tok->cur++); } if (tok->prompt != NULL) { char *newtok = PyOS_Readline(stdin, stdout, tok->prompt); #ifndef PGEN if (newtok != NULL) { char *translated = translate_newlines(newtok, 0, tok); PyMem_FREE(newtok); if (translated == NULL) return EOF; newtok = translated; } if (tok->encoding && newtok && *newtok) { /* Recode to UTF-8 */ Py_ssize_t buflen; const char* buf; PyObject *u = translate_into_utf8(newtok, tok->encoding); PyMem_FREE(newtok); if (!u) { tok->done = E_DECODE; return EOF; } buflen = PyBytes_GET_SIZE(u); buf = PyBytes_AS_STRING(u); newtok = PyMem_MALLOC(buflen+1); if (newtok == NULL) { Py_DECREF(u); tok->done = E_NOMEM; return EOF; } strcpy(newtok, buf); Py_DECREF(u); } #endif if (tok->nextprompt != NULL) tok->prompt = tok->nextprompt; if (newtok == NULL) tok->done = E_INTR; else if (*newtok == '\0') { PyMem_FREE(newtok); tok->done = E_EOF; } else if (tok->start != NULL) { size_t start = tok->start - tok->buf; size_t oldlen = tok->cur - tok->buf; size_t newlen = oldlen + strlen(newtok); char *buf = tok->buf; buf = (char *)PyMem_REALLOC(buf, newlen+1); tok->lineno++; if (buf == NULL) { PyMem_FREE(tok->buf); tok->buf = NULL; PyMem_FREE(newtok); tok->done = E_NOMEM; return EOF; } tok->buf = buf; tok->cur = tok->buf + oldlen; tok->line_start = tok->cur; strcpy(tok->buf + oldlen, newtok); PyMem_FREE(newtok); tok->inp = tok->buf + newlen; tok->end = tok->inp + 1; tok->start = tok->buf + start; } else { tok->lineno++; if (tok->buf != NULL) PyMem_FREE(tok->buf); tok->buf = newtok; tok->cur = tok->buf; tok->line_start = tok->buf; tok->inp = strchr(tok->buf, '\0'); tok->end = tok->inp + 1; } } else { int done = 0; Py_ssize_t cur = 0; char *pt; if (tok->start == NULL) { if (tok->buf == NULL) { tok->buf = (char *) PyMem_MALLOC(BUFSIZ); if (tok->buf == NULL) { tok->done = E_NOMEM; return EOF; } tok->end = tok->buf + BUFSIZ; } if (decoding_fgets(tok->buf, (int)(tok->end - tok->buf), tok) == NULL) { if (!tok->decoding_erred) tok->done = E_EOF; done = 1; } else { tok->done = E_OK; tok->inp = strchr(tok->buf, '\0'); done = tok->inp == tok->buf || tok->inp[-1] == '\n'; } } else { cur = tok->cur - tok->buf; if (decoding_feof(tok)) { tok->done = E_EOF; done = 1; } else tok->done = E_OK; } tok->lineno++; /* Read until '\n' or EOF */ while (!done) { Py_ssize_t curstart = tok->start == NULL ? -1 : tok->start - tok->buf; Py_ssize_t curvalid = tok->inp - tok->buf; Py_ssize_t newsize = curvalid + BUFSIZ; char *newbuf = tok->buf; newbuf = (char *)PyMem_REALLOC(newbuf, newsize); if (newbuf == NULL) { tok->done = E_NOMEM; tok->cur = tok->inp; return EOF; } tok->buf = newbuf; tok->cur = tok->buf + cur; tok->line_start = tok->cur; tok->inp = tok->buf + curvalid; tok->end = tok->buf + newsize; tok->start = curstart < 0 ? NULL : tok->buf + curstart; if (decoding_fgets(tok->inp, (int)(tok->end - tok->inp), tok) == NULL) { /* Break out early on decoding errors, as tok->buf will be NULL */ if (tok->decoding_erred) return EOF; /* Last line does not end in \n, fake one */ strcpy(tok->inp, "\n"); } tok->inp = strchr(tok->inp, '\0'); done = tok->inp[-1] == '\n'; } if (tok->buf != NULL) { tok->cur = tok->buf + cur; tok->line_start = tok->cur; /* replace "\r\n" with "\n" */ /* For Mac leave the \r, giving a syntax error */ pt = tok->inp - 2; if (pt >= tok->buf && *pt == '\r') { *pt++ = '\n'; *pt = '\0'; tok->inp = pt; } } } if (tok->done != E_OK) { if (tok->prompt != NULL) PySys_WriteStderr("\n"); tok->cur = tok->inp; return EOF; } } /*NOTREACHED*/ } /* Back-up one character */ static void tok_backup(struct tok_state *tok, int c) { if (c != EOF) { if (--tok->cur < tok->buf) Py_FatalError("tok_backup: beginning of buffer"); if (*tok->cur != c) *tok->cur = c; } } /* Return the token corresponding to a single character */ int PyToken_OneChar(int c) { switch (c) { case '(': return LPAR; case ')': return RPAR; case '[': return LSQB; case ']': return RSQB; case ':': return COLON; case ',': return COMMA; case ';': return SEMI; case '+': return PLUS; case '-': return MINUS; case '*': return STAR; case '/': return SLASH; case '|': return VBAR; case '&': return AMPER; case '<': return LESS; case '>': return GREATER; case '=': return EQUAL; case '.': return DOT; case '%': return PERCENT; case '{': return LBRACE; case '}': return RBRACE; case '^': return CIRCUMFLEX; case '~': return TILDE; case '@': return AT; default: return OP; } } int PyToken_TwoChars(int c1, int c2) { switch (c1) { case '=': switch (c2) { case '=': return EQEQUAL; } break; case '!': switch (c2) { case '=': return NOTEQUAL; } break; case '<': switch (c2) { case '>': return NOTEQUAL; case '=': return LESSEQUAL; case '<': return LEFTSHIFT; } break; case '>': switch (c2) { case '=': return GREATEREQUAL; case '>': return RIGHTSHIFT; } break; case '+': switch (c2) { case '=': return PLUSEQUAL; } break; case '-': switch (c2) { case '=': return MINEQUAL; case '>': return RARROW; } break; case '*': switch (c2) { case '*': return DOUBLESTAR; case '=': return STAREQUAL; } break; case '/': switch (c2) { case '/': return DOUBLESLASH; case '=': return SLASHEQUAL; } break; case '|': switch (c2) { case '=': return VBAREQUAL; } break; case '%': switch (c2) { case '=': return PERCENTEQUAL; } break; case '&': switch (c2) { case '=': return AMPEREQUAL; } break; case '^': switch (c2) { case '=': return CIRCUMFLEXEQUAL; } break; case '@': switch (c2) { case '=': return ATEQUAL; } break; } return OP; } int PyToken_ThreeChars(int c1, int c2, int c3) { switch (c1) { case '<': switch (c2) { case '<': switch (c3) { case '=': return LEFTSHIFTEQUAL; } break; } break; case '>': switch (c2) { case '>': switch (c3) { case '=': return RIGHTSHIFTEQUAL; } break; } break; case '*': switch (c2) { case '*': switch (c3) { case '=': return DOUBLESTAREQUAL; } break; } break; case '/': switch (c2) { case '/': switch (c3) { case '=': return DOUBLESLASHEQUAL; } break; } break; case '.': switch (c2) { case '.': switch (c3) { case '.': return ELLIPSIS; } break; } break; } return OP; } static int indenterror(struct tok_state *tok) { if (tok->alterror) { tok->done = E_TABSPACE; tok->cur = tok->inp; return 1; } if (tok->altwarning) { #ifdef PGEN PySys_WriteStderr("inconsistent use of tabs and spaces " "in indentation\n"); #else PySys_FormatStderr("%U: inconsistent use of tabs and spaces " "in indentation\n", tok->filename); #endif tok->altwarning = 0; } return 0; } #ifdef PGEN #define verify_identifier(tok) 1 #else /* Verify that the identifier follows PEP 3131. All identifier strings are guaranteed to be "ready" unicode objects. */ static int verify_identifier(struct tok_state *tok) { PyObject *s; int result; if (tok->decoding_erred) return 0; s = PyUnicode_DecodeUTF8(tok->start, tok->cur - tok->start, NULL); if (s == NULL || PyUnicode_READY(s) == -1) { if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) { PyErr_Clear(); tok->done = E_IDENTIFIER; } else { tok->done = E_ERROR; } return 0; } result = PyUnicode_IsIdentifier(s); Py_DECREF(s); if (result == 0) tok->done = E_IDENTIFIER; return result; } #endif static int tok_decimal_tail(struct tok_state *tok) { int c; while (1) { do { c = tok_nextc(tok); } while (isdigit(c)); if (c != '_') { break; } c = tok_nextc(tok); if (!isdigit(c)) { tok->done = E_TOKEN; tok_backup(tok, c); return 0; } } return c; } /* Get next token, after space stripping etc. */ static int tok_get(struct tok_state *tok, char **p_start, char **p_end) { int c; int blankline, nonascii; *p_start = *p_end = NULL; nextline: tok->start = NULL; blankline = 0; /* Get indentation level */ if (tok->atbol) { int col = 0; int altcol = 0; tok->atbol = 0; for (;;) { c = tok_nextc(tok); if (c == ' ') { col++, altcol++; } else if (c == '\t') { col = (col/tok->tabsize + 1) * tok->tabsize; altcol = (altcol/tok->alttabsize + 1) * tok->alttabsize; } else if (c == '\014') {/* Control-L (formfeed) */ col = altcol = 0; /* For Emacs users */ } else { break; } } tok_backup(tok, c); if (c == '#' || c == '\n') { /* Lines with only whitespace and/or comments shouldn't affect the indentation and are not passed to the parser as NEWLINE tokens, except *totally* empty lines in interactive mode, which signal the end of a command group. */ if (col == 0 && c == '\n' && tok->prompt != NULL) { blankline = 0; /* Let it through */ } else { blankline = 1; /* Ignore completely */ } /* We can't jump back right here since we still may need to skip to the end of a comment */ } if (!blankline && tok->level == 0) { if (col == tok->indstack[tok->indent]) { /* No change */ if (altcol != tok->altindstack[tok->indent]) { if (indenterror(tok)) { return ERRORTOKEN; } } } else if (col > tok->indstack[tok->indent]) { /* Indent -- always one */ if (tok->indent+1 >= MAXINDENT) { tok->done = E_TOODEEP; tok->cur = tok->inp; return ERRORTOKEN; } if (altcol <= tok->altindstack[tok->indent]) { if (indenterror(tok)) { return ERRORTOKEN; } } tok->pendin++; tok->indstack[++tok->indent] = col; tok->altindstack[tok->indent] = altcol; } else /* col < tok->indstack[tok->indent] */ { /* Dedent -- any number, must be consistent */ while (tok->indent > 0 && col < tok->indstack[tok->indent]) { tok->pendin--; tok->indent--; } if (col != tok->indstack[tok->indent]) { tok->done = E_DEDENT; tok->cur = tok->inp; return ERRORTOKEN; } if (altcol != tok->altindstack[tok->indent]) { if (indenterror(tok)) { return ERRORTOKEN; } } } } } tok->start = tok->cur; /* Return pending indents/dedents */ if (tok->pendin != 0) { if (tok->pendin < 0) { tok->pendin++; return DEDENT; } else { tok->pendin--; return INDENT; } } if (tok->async_def && !blankline && tok->level == 0 /* There was a NEWLINE after ASYNC DEF, so we're past the signature. */ && tok->async_def_nl /* Current indentation level is less than where the async function was defined */ && tok->async_def_indent >= tok->indent) { tok->async_def = 0; tok->async_def_indent = 0; tok->async_def_nl = 0; } again: tok->start = NULL; /* Skip spaces */ do { c = tok_nextc(tok); } while (c == ' ' || c == '\t' || c == '\014'); /* Set start of current token */ if (tok->cur) tok->start = tok->cur - 1; /* Skip comment */ if (c == '#') { while (c != EOF && c != '\n') { c = tok_nextc(tok); } } /* Check for EOF and errors now */ if (c == EOF) { return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; } /* Identifier (most frequent token!) */ nonascii = 0; if (is_potential_identifier_start(c)) { /* Process the various legal combinations of b"", r"", u"", and f"". */ int saw_b = 0, saw_r = 0, saw_u = 0, saw_f = 0; while (1) { if (!(saw_b || saw_u || saw_f) && (c == 'b' || c == 'B')) saw_b = 1; /* Since this is a backwards compatibility support literal we don't want to support it in arbitrary order like byte literals. */ else if (!(saw_b || saw_u || saw_r || saw_f) && (c == 'u'|| c == 'U')) { saw_u = 1; } /* ur"" and ru"" are not supported */ else if (!(saw_r || saw_u) && (c == 'r' || c == 'R')) { saw_r = 1; } else if (!(saw_f || saw_b || saw_u) && (c == 'f' || c == 'F')) { saw_f = 1; } else { break; } c = tok_nextc(tok); if (c == '"' || c == '\'') { goto letter_quote; } } while (is_potential_identifier_char(c)) { if (c >= 128) { nonascii = 1; } c = tok_nextc(tok); } tok_backup(tok, c); if (nonascii && !verify_identifier(tok)) { return ERRORTOKEN; } *p_start = tok->start; *p_end = tok->cur; /* async/await parsing block. */ if (tok->cur - tok->start == 5) { /* Current token length is 5. */ if (tok->async_def) { /* We're inside an 'async def' function. */ if (!bcmp(tok->start, "async", 5)) { return ASYNC; } if (!bcmp(tok->start, "await", 5)) { return AWAIT; } } else if (!bcmp(tok->start, "async", 5)) { /* The current token is 'async'. Look ahead one token.*/ int async_def_prev = tok->async_def; tok->async_def = 2; struct tok_state ahead_tok; char *ahead_tok_start = NULL, *ahead_tok_end = NULL; int ahead_tok_kind; memcpy(&ahead_tok, tok, sizeof(ahead_tok)); ahead_tok_kind = tok_get(&ahead_tok, &ahead_tok_start, &ahead_tok_end); if (ahead_tok_kind == NAME && ahead_tok.cur - ahead_tok.start == 3 && !bcmp(ahead_tok.start, "def", 3)) { /* The next token is going to be 'def', so instead of returning 'async' NAME token, we return ASYNC. */ tok->async_def_indent = tok->indent; tok->async_def = 1; return ASYNC; } else{ tok->async_def = async_def_prev; } } } return NAME; } /* Newline */ if (c == '\n') { tok->atbol = 1; if (blankline || tok->level > 0) { goto nextline; } *p_start = tok->start; *p_end = tok->cur - 1; /* Leave '\n' out of the string */ tok->cont_line = 0; if (tok->async_def) { /* We're somewhere inside an 'async def' function, and we've encountered a NEWLINE after its signature. */ tok->async_def_nl = 1; } return NEWLINE; } /* Period or number starting with period? */ if (c == '.') { c = tok_nextc(tok); if (isdigit(c)) { goto fraction; } else if (c == '.') { c = tok_nextc(tok); if (c == '.') { *p_start = tok->start; *p_end = tok->cur; return ELLIPSIS; } else { tok_backup(tok, c); } tok_backup(tok, '.'); } else { tok_backup(tok, c); } *p_start = tok->start; *p_end = tok->cur; return DOT; } /* Number */ if (isdigit(c)) { if (c == '0') { /* Hex, octal or binary -- maybe. */ c = tok_nextc(tok); if (c == 'x' || c == 'X') { /* Hex */ c = tok_nextc(tok); do { if (c == '_') { c = tok_nextc(tok); } if (!isxdigit(c)) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } do { c = tok_nextc(tok); } while (isxdigit(c)); } while (c == '_'); } else if (c == 'o' || c == 'O') { /* Octal */ c = tok_nextc(tok); do { if (c == '_') { c = tok_nextc(tok); } if (c < '0' || c >= '8') { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } do { c = tok_nextc(tok); } while ('0' <= c && c < '8'); } while (c == '_'); } else if (c == 'b' || c == 'B') { /* Binary */ c = tok_nextc(tok); do { if (c == '_') { c = tok_nextc(tok); } if (c != '0' && c != '1') { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } do { c = tok_nextc(tok); } while (c == '0' || c == '1'); } while (c == '_'); } else { int nonoctal = 0; /* maybe old-style octal; c is first char of it */ /* in any case, allow '0' as a literal */ while (1) { if (c == '_') { c = tok_nextc(tok); if (!isdigit(c)) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } } if (c != '0') { break; } c = tok_nextc(tok); } /* [jart] restore octal */ if ('1' <= c && c <= '7') { while (1) { if (c == '_') { c = tok_nextc(tok); if (!('0' <= c && c <= '7')) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } } if (!('0' <= c && c <= '7')) { break; } c = tok_nextc(tok); } } if (isdigit(c)) { nonoctal = 1; c = tok_decimal_tail(tok); if (c == 0) { return ERRORTOKEN; } } if (c == '.') { c = tok_nextc(tok); goto fraction; } else if (c == 'e' || c == 'E') { goto exponent; } else if (c == 'j' || c == 'J') { goto imaginary; } else if (nonoctal) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } } } else { /* Decimal */ c = tok_decimal_tail(tok); if (c == 0) { return ERRORTOKEN; } { /* Accept floating point numbers. */ if (c == '.') { c = tok_nextc(tok); fraction: /* Fraction */ if (isdigit(c)) { c = tok_decimal_tail(tok); if (c == 0) { return ERRORTOKEN; } } } if (c == 'e' || c == 'E') { int e; exponent: e = c; /* Exponent part */ c = tok_nextc(tok); if (c == '+' || c == '-') { c = tok_nextc(tok); if (!isdigit(c)) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } } else if (!isdigit(c)) { tok_backup(tok, c); tok_backup(tok, e); *p_start = tok->start; *p_end = tok->cur; return NUMBER; } c = tok_decimal_tail(tok); if (c == 0) { return ERRORTOKEN; } } if (c == 'j' || c == 'J') { /* Imaginary part */ imaginary: c = tok_nextc(tok); } } } tok_backup(tok, c); *p_start = tok->start; *p_end = tok->cur; return NUMBER; } letter_quote: /* String */ if (c == '\'' || c == '"') { int quote = c; int quote_size = 1; /* 1 or 3 */ int end_quote_size = 0; /* Find the quote size and start of string */ c = tok_nextc(tok); if (c == quote) { c = tok_nextc(tok); if (c == quote) { quote_size = 3; } else { end_quote_size = 1; /* empty string found */ } } if (c != quote) { tok_backup(tok, c); } /* Get rest of string */ while (end_quote_size != quote_size) { c = tok_nextc(tok); if (c == EOF) { if (quote_size == 3) { tok->done = E_EOFS; } else { tok->done = E_EOLS; } tok->cur = tok->inp; return ERRORTOKEN; } if (quote_size == 1 && c == '\n') { tok->done = E_EOLS; tok->cur = tok->inp; return ERRORTOKEN; } if (c == quote) { end_quote_size += 1; } else { end_quote_size = 0; if (c == '\\') { tok_nextc(tok); /* skip escaped char */ } } } *p_start = tok->start; *p_end = tok->cur; return STRING; } /* Line continuation */ if (c == '\\') { c = tok_nextc(tok); if (tok->async_def == 2) { tok->done = E_SYNTAX; return ERRORTOKEN; } if (c != '\n') { tok->done = E_LINECONT; tok->cur = tok->inp; return ERRORTOKEN; } tok->cont_line = 1; goto again; /* Read next line */ } /* Check for two-character token */ { int c2 = tok_nextc(tok); int token = PyToken_TwoChars(c, c2); if (token != OP) { int c3 = tok_nextc(tok); int token3 = PyToken_ThreeChars(c, c2, c3); if (token3 != OP) { token = token3; } else { tok_backup(tok, c3); } *p_start = tok->start; *p_end = tok->cur; return token; } tok_backup(tok, c2); } /* Keep track of parentheses nesting level */ switch (c) { case '(': case '[': case '{': tok->level++; break; case ')': case ']': case '}': tok->level--; break; } /* Punctuation character */ *p_start = tok->start; *p_end = tok->cur; return PyToken_OneChar(c); } int PyTokenizer_Get(struct tok_state *tok, char **p_start, char **p_end) { int result = tok_get(tok, p_start, p_end); if (tok->decoding_erred) { result = ERRORTOKEN; tok->done = E_DECODE; } return result; } /* Get the encoding of a Python file. Check for the coding cookie and check if the file starts with a BOM. PyTokenizer_FindEncodingFilename() returns NULL when it can't find the encoding in the first or second line of the file (in which case the encoding should be assumed to be UTF-8). The char* returned is malloc'ed via PyMem_MALLOC() and thus must be freed by the caller. */ char * PyTokenizer_FindEncodingFilename(int fd, PyObject *filename) { struct tok_state *tok; FILE *fp; char *p_start =NULL , *p_end =NULL , *encoding = NULL; #ifndef PGEN fd = _Py_dup(fd); #else fd = dup(fd); #endif if (fd < 0) { return NULL; } fp = fdopen(fd, "r"); if (fp == NULL) { return NULL; } tok = PyTokenizer_FromFile(fp, NULL, NULL, NULL); if (tok == NULL) { fclose(fp); return NULL; } #ifndef PGEN if (filename != NULL) { Py_INCREF(filename); tok->filename = filename; } else { tok->filename = PyUnicode_FromString("<string>"); if (tok->filename == NULL) { fclose(fp); PyTokenizer_Free(tok); return encoding; } } #endif while (tok->lineno < 2 && tok->done == E_OK) { PyTokenizer_Get(tok, &p_start, &p_end); } fclose(fp); if (tok->encoding) { encoding = (char *)PyMem_MALLOC(strlen(tok->encoding) + 1); if (encoding) strcpy(encoding, tok->encoding); } PyTokenizer_Free(tok); return encoding; } char * PyTokenizer_FindEncoding(int fd) { return PyTokenizer_FindEncodingFilename(fd, NULL); } #ifdef Py_DEBUG void tok_dump(int type, char *start, char *end) { printf("%s", _PyParser_TokenNames[type]); if (type == NAME || type == NUMBER || type == STRING || type == OP) printf("(%.*s)", (int)(end - start), start); } #endif
5ccc09ccf83f5777b67c5f5d33ae05ffb8165d77
35c04ea32351dc95bc18d46e5c70dda9c1e08668
/Examples/MCUXpresso/FRDM-KE02Z/FRDM-KE02Z_Blinky/device/fsl_device_registers.h
7e1ac0b91967c34cab96ecb4296c4faa25fb4bc0
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
ErichStyger/mcuoneclipse
0f8e7a2056a26ed79d9d4a0afd64777ff0b2b2fe
04ad311b11860ae5f8285316010961a87fa06d0c
refs/heads/master
2023-08-28T22:54:08.501719
2023-08-25T15:11:44
2023-08-25T15:11:44
7,446,094
620
1,191
NOASSERTION
2020-10-16T03:13:28
2013-01-04T19:38:12
Batchfile
UTF-8
C
false
false
1,148
h
fsl_device_registers.h
/* * Copyright 2014-2016 Freescale Semiconductor, Inc. * Copyright 2016-2018 NXP * * SPDX-License-Identifier: BSD-3-Clause * */ #ifndef __FSL_DEVICE_REGISTERS_H__ #define __FSL_DEVICE_REGISTERS_H__ /* * Include the cpu specific register header files. * * The CPU macro should be declared in the project or makefile. */ #if (defined(CPU_MKE02Z16VFM4) || defined(CPU_MKE02Z16VLC4) || defined(CPU_MKE02Z16VLD4) || \ defined(CPU_MKE02Z32VFM4) || defined(CPU_MKE02Z32VLC4) || defined(CPU_MKE02Z32VLD4) || \ defined(CPU_MKE02Z32VLH4) || defined(CPU_MKE02Z32VQH4) || defined(CPU_MKE02Z64VFM4) || \ defined(CPU_MKE02Z64VLC4) || defined(CPU_MKE02Z64VLD4) || defined(CPU_MKE02Z64VLH4) || \ defined(CPU_MKE02Z64VQH4)) #define KE02Z4_SERIES /* CMSIS-style register definitions */ #include "MKE02Z4.h" /* CPU specific feature definitions */ #include "MKE02Z4_features.h" #else #error "No valid CPU defined!" #endif #endif /* __FSL_DEVICE_REGISTERS_H__ */ /******************************************************************************* * EOF ******************************************************************************/
810305ae11cc5b1d90a169c10a950b89205a8d8f
bd720d657cfc9ad96d17e878e65d56096a11661a
/uif.h
666f8e05eb283a915e562706515c56bfeaf27695
[ "CC-BY-4.0" ]
permissive
jim17/memtype
b30b619b2f526dae811b6d7352a01106e811f849
6e88468e039159850c62700bbcd86e01276ab80e
refs/heads/master
2020-04-12T01:42:29.868907
2018-04-24T18:15:00
2018-04-24T18:15:00
44,481,649
141
23
null
2018-04-24T18:15:01
2015-10-18T14:38:58
C
UTF-8
C
false
false
514
h
uif.h
/** User Input Button api */ #ifndef _UIF_H_ #define _UIF_H_ #include <stdint.h> /* UIF MENU STATES */ enum { START = 0, CREDENTIALS, OPTIONS, USER_INPUT, } menuStates; /* Public vars */ extern uint8_t UIF_state; extern uint8_t UIF_credIndex; extern uint8_t UIF_optionsIndex; extern uint8_t UIF_userInputIndex; /* Public functions */ void UIF_Init(void); void UIF_Task(void); void UIF_increment(uint8_t* val, uint8_t max); void UIF_decrement(uint8_t* val, uint8_t max); #endif /* _UIF_H_*/
9c0f551080ff3f211442bf8fd1e23374dbfcefc4
43bf0bdbd65c8bc8bc99d0ed1d408a79aee2621a
/c/src/proactor/libuv.c
b2663fa335a1af2025765796585dec3cc80de892
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
apache/qpid-proton
51a6a61352cb206095aec75b27ebaa7fbf211d20
6b05c6d64ba04bad96745b1430ca17d436b6fd32
refs/heads/main
2023-09-01T14:06:34.221772
2023-08-09T21:38:18
2023-08-09T21:38:18
26,309,799
236
257
Apache-2.0
2023-08-31T14:37:43
2014-11-07T08:00:07
C++
UTF-8
C
false
false
45,715
c
libuv.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. * */ /* Enable POSIX features for uv.h */ #ifndef _POSIX_C_SOURCE #define _POSIX_C_SOURCE 200809L #endif #include "core/logger_private.h" #include "proactor-internal.h" #include <proton/condition.h> #include <proton/connection_driver.h> #include <proton/engine.h> #include <proton/listener.h> #include <proton/message.h> #include <proton/netaddr.h> #include <proton/proactor.h> #include <proton/raw_connection.h> #include <proton/transport.h> #include <uv.h> #include "netaddr-internal.h" /* Include after socket headers via uv.h */ /* All asserts are cheap and should remain in a release build for debuggability */ #undef NDEBUG #include <assert.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* libuv functions are thread unsafe, we use a"leader-worker-follower" model as follows: - At most one thread at a time is the "leader". The leader runs the UV loop till there are events to process and then becomes a "worker" - Concurrent "worker" threads process events for separate connections or listeners. When they run out of work they become "followers" - A "follower" is idle, waiting for work. When the leader becomes a worker, one follower takes over as the new leader. Any thread that calls pn_proactor_wait() or pn_proactor_get() can take on any of the roles as required at run-time. Monitored sockets (connections or listeners) are passed between threads on thread-safe queues. Function naming: - on_*() - libuv callbacks, called in leader thread via uv_run(). - leader_* - only called in leader thread from - *_lh - called with the relevant lock held */ const char *AMQP_PORT = "5672"; const char *AMQP_PORT_NAME = "amqp"; /* pn_proactor_t and pn_listener_t are plain C structs with normal memory management. CLASSDEF is for identification when used as a pn_event_t context. */ PN_STRUCT_CLASSDEF(pn_proactor) PN_STRUCT_CLASSDEF(pn_listener) /* ================ Queues ================ */ static int unqueued; /* Provide invalid address for _unqueued pointers */ #define QUEUE_DECL(T) \ typedef struct T##_queue_t { T##_t *front, *back; } T##_queue_t; \ \ static T##_t *T##_unqueued = (T##_t*)&unqueued; \ \ static void T##_push(T##_queue_t *q, T##_t *x) { \ assert(x->next == T##_unqueued); \ x->next = NULL; \ if (!q->front) { \ q->front = q->back = x; \ } else { \ q->back->next = x; \ q->back = x; \ } \ } \ \ static T##_t* T##_pop(T##_queue_t *q) { \ T##_t *x = q->front; \ if (x) { \ q->front = x->next; \ x->next = T##_unqueued; \ } \ return x; \ } /* All work structs and UV callback data structs start with a struct_type member */ typedef enum { T_CONNECTION, T_LISTENER, T_LSOCKET } struct_type; /* A stream of serialized work for the proactor */ typedef struct work_t { /* Immutable */ struct_type type; pn_proactor_t *proactor; /* Protected by proactor.lock */ struct work_t* next; bool working; /* Owned by a worker thread */ } work_t; QUEUE_DECL(work) static void work_init(work_t* w, pn_proactor_t* p, struct_type type) { w->proactor = p; w->next = work_unqueued; w->type = type; w->working = true; } /* ================ IO ================ */ /* A resolvable address */ typedef struct addr_t { char addr_buf[PN_MAX_ADDR]; const char *host, *port; uv_getaddrinfo_t getaddrinfo; /* UV getaddrinfo request, contains list of addrinfo */ struct addrinfo* addrinfo; /* The current addrinfo being tried */ } addr_t; /* A single listening socket, a listener can have more than one */ typedef struct lsocket_t { struct_type type; /* Always T_LSOCKET */ pn_listener_t *parent; uv_tcp_t tcp; struct lsocket_t *next; } lsocket_t; PN_STRUCT_CLASSDEF(pn_listener_socket) typedef enum { W_NONE, W_PENDING, W_CLOSED } wake_state; /* An incoming or outgoing connection. */ typedef struct pconnection_t { work_t work; /* Must be first to allow casting */ struct pconnection_t *next; /* For listener list */ /* Only used by owner thread */ pn_connection_driver_t driver; pn_event_batch_t batch; /* Only used by leader */ uv_tcp_t tcp; addr_t addr; uv_connect_t connect; /* Outgoing connection only */ int connected; /* 0: not connected, <0: connecting after error, 1 = connected ok */ lsocket_t *lsocket; /* Incoming connection only */ struct pn_netaddr_t local, remote; /* Actual addresses */ uv_timer_t timer; uv_write_t write; size_t writing; /* size of pending write request, 0 if none pending */ bool read_started; uv_shutdown_t shutdown; /* Locked for thread-safe access */ uv_mutex_t lock; wake_state wake; } pconnection_t; QUEUE_DECL(pconnection) typedef enum { L_UNINIT, /**<< Not yet listening */ L_LISTENING, /**<< Listening */ L_CLOSE, /**<< Close requested */ L_CLOSING, /**<< Socket close initiated, wait for all to close */ L_CLOSED /**<< User saw PN_LISTENER_CLOSED, all done */ } listener_state; /* A listener */ struct pn_listener_t { work_t work; /* Must be first to allow casting */ /* Only used by owner thread */ pn_event_batch_t batch; pn_record_t *attachments; void *context; size_t backlog; /* Only used by leader */ addr_t addr; lsocket_t *lsockets; int dynamic_port; /* Record dynamic port from first bind(0) */ /* Invariant listening addresses allocated during leader_listen_lh() */ struct pn_netaddr_t *addrs; int addrs_len; /* Locked for thread-safe access. uv_listen can't be stopped or cancelled so we can't * detach a listener from the UV loop to prevent concurrent access. */ uv_mutex_t lock; pn_condition_t *condition; pn_collector_t *collector; pconnection_queue_t accept; /* pconnection_t list for accepting */ listener_state state; }; typedef enum { TM_NONE, TM_REQUEST, TM_PENDING, TM_FIRED } timeout_state_t; struct pn_proactor_t { /* Notification */ uv_async_t notify; uv_async_t interrupt; /* Leader thread */ uv_cond_t cond; uv_loop_t loop; uv_timer_t timer; /* Owner thread: proactor collector and batch can belong to leader or a worker */ pn_collector_t *collector; pn_event_batch_t batch; /* Protected by lock */ uv_mutex_t lock; work_queue_t worker_q; /* ready for work, to be returned via pn_proactor_wait() */ work_queue_t leader_q; /* waiting for attention by the leader thread */ timeout_state_t timeout_state; pn_millis_t timeout; size_t active; /* connection/listener count for INACTIVE events */ pn_condition_t *disconnect_cond; /* disconnect condition */ bool has_leader; /* A thread is working as leader */ bool disconnect; /* disconnect requested */ bool batch_working; /* batch is being processed in a worker thread */ bool need_interrupt; /* Need a PN_PROACTOR_INTERRUPT event */ bool need_inactive; /* need INACTIVE event */ bool timeout_processed; }; /* Notify the leader thread that there is something to do outside of uv_run() */ static inline void notify(pn_proactor_t* p) { uv_async_send(&p->notify); } /* Set the interrupt flag in the leader thread to avoid race conditions. */ void on_interrupt(uv_async_t *async) { if (async->data) { pn_proactor_t *p = (pn_proactor_t*)async->data; p->need_interrupt = true; } } /* Notify that this work item needs attention from the leader at the next opportunity */ static void work_notify(work_t *w) { uv_mutex_lock(&w->proactor->lock); /* If the socket is in use by a worker or is already queued then leave it where it is. It will be processed in pn_proactor_done() or when the queue it is on is processed. */ if (!w->working && w->next == work_unqueued) { work_push(&w->proactor->leader_q, w); notify(w->proactor); } uv_mutex_unlock(&w->proactor->lock); } /* Notify the leader of a newly-created work item */ static void work_start(work_t *w) { uv_mutex_lock(&w->proactor->lock); if (w->next == work_unqueued) { /* No-op if already queued */ w->working = false; work_push(&w->proactor->leader_q, w); notify(w->proactor); uv_mutex_unlock(&w->proactor->lock); } } static void parse_addr(addr_t *addr, const char *str) { pni_parse_addr(str, addr->addr_buf, sizeof(addr->addr_buf), &addr->host, &addr->port); } /* Protect read/update of pn_connnection_t pointer to it's pconnection_t * * Global because pn_connection_wake()/pn_connection_proactor() navigate from * the pn_connection_t before we know the proactor or driver. Critical sections * are small: only get/set of the pn_connection_t driver pointer. * * TODO: replace mutex with atomic load/store */ static pthread_mutex_t driver_ptr_mutex; static uv_once_t global_init_once = UV_ONCE_INIT; static void global_init_fn(void) { /* Call via uv_once(&global_init_once, global_init_fn) */ uv_mutex_init(&driver_ptr_mutex); } static pconnection_t *get_pconnection(pn_connection_t* c) { if (!c) return NULL; uv_mutex_lock(&driver_ptr_mutex); pn_connection_driver_t *d = *pn_connection_driver_ptr(c); uv_mutex_unlock(&driver_ptr_mutex); if (!d) return NULL; return containerof(d, pconnection_t, driver); } static void set_pconnection(pn_connection_t* c, pconnection_t *pc) { uv_mutex_lock(&driver_ptr_mutex); *pn_connection_driver_ptr(c) = pc ? &pc->driver : NULL; uv_mutex_unlock(&driver_ptr_mutex); } static pn_event_t *pconnection_batch_next(pn_event_batch_t *batch); static pconnection_t *pconnection(pn_proactor_t *p, pn_connection_t *c, pn_transport_t *t, bool server) { pconnection_t *pc = (pconnection_t*)calloc(1, sizeof(*pc)); if (!pc || pn_connection_driver_init(&pc->driver, c, t) != 0) { return NULL; } work_init(&pc->work, p, T_CONNECTION); pc->batch.next_event = pconnection_batch_next; pc->next = pconnection_unqueued; pc->write.data = &pc->work; uv_mutex_init(&pc->lock); if (server) { pn_transport_set_server(pc->driver.transport); } set_pconnection(pc->driver.connection, pc); return pc; } static void pconnection_free(pconnection_t *pc) { pn_connection_t *c = pc->driver.connection; if (c) set_pconnection(c, NULL); pn_connection_driver_destroy(&pc->driver); if (pc->addr.getaddrinfo.addrinfo) { uv_freeaddrinfo(pc->addr.getaddrinfo.addrinfo); /* Interrupted after resolve */ } uv_mutex_destroy(&pc->lock); free(pc); } static pn_event_t *listener_batch_next(pn_event_batch_t *batch); static pn_event_t *proactor_batch_next(pn_event_batch_t *batch); static inline pn_proactor_t *batch_proactor(pn_event_batch_t *batch) { return (batch->next_event == proactor_batch_next) ? containerof(batch, pn_proactor_t, batch) : NULL; } static inline pn_listener_t *batch_listener(pn_event_batch_t *batch) { return (batch->next_event == listener_batch_next) ? containerof(batch, pn_listener_t, batch) : NULL; } static inline pconnection_t *batch_pconnection(pn_event_batch_t *batch) { return (batch->next_event == pconnection_batch_next) ? containerof(batch, pconnection_t, batch) : NULL; } pn_proactor_t *pn_event_batch_proactor(pn_event_batch_t *batch) { return batch_proactor(batch); } pn_listener_t *pn_event_batch_listener(pn_event_batch_t *batch) { return batch_listener(batch); } pn_connection_t *pn_event_batch_connection(pn_event_batch_t *batch) { pconnection_t *r = batch_pconnection(batch); return r ? r->driver.connection : NULL; } static inline work_t *batch_work(pn_event_batch_t *batch) { pconnection_t *pc = batch_pconnection(batch); if (pc) return &pc->work; pn_listener_t *l = batch_listener(batch); if (l) return &l->work; return NULL; } static void check_for_inactive(pn_proactor_t *p) { /* No future events: no active socket io, no pending timer, no current event processing. */ if (!p->batch_working && !p->active && !p->need_interrupt && p->timeout_state == TM_NONE) p->need_inactive = true; } /* Total count of listener and connections for PN_PROACTOR_INACTIVE */ static void add_active(pn_proactor_t *p) { uv_mutex_lock(&p->lock); ++p->active; uv_mutex_unlock(&p->lock); } static void remove_active_lh(pn_proactor_t *p) { assert(p->active > 0); if (--p->active == 0) { check_for_inactive(p); } } static void remove_active(pn_proactor_t *p) { uv_mutex_lock(&p->lock); remove_active_lh(p); uv_mutex_unlock(&p->lock); } /* Final close event for for a pconnection_t, disconnects from proactor */ static void on_close_pconnection_final(uv_handle_t *h) { /* Free resources associated with a pconnection_t. If the life of the pn_connection_t has been extended with reference counts we want the pconnection_t to have the same lifespan so calls to pn_connection_wake() will be valid, but no-ops. */ pconnection_t *pc = (pconnection_t*)h->data; remove_active(pc->work.proactor); pconnection_free(pc); } static void uv_safe_close(uv_handle_t *h, uv_close_cb cb) { /* Only close if h has been initialized and is not already closing */ if (h->type && !uv_is_closing(h)) { uv_close(h, cb); } } static void on_close_pconnection(uv_handle_t *h) { pconnection_t *pc = (pconnection_t*)h->data; /* Delay the free till the timer handle is also closed */ uv_timer_stop(&pc->timer); uv_safe_close((uv_handle_t*)&pc->timer, on_close_pconnection_final); } static void listener_close_lh(pn_listener_t* l) { if (l->state < L_CLOSE) { l->state = L_CLOSE; } work_notify(&l->work); } static void on_close_lsocket(uv_handle_t *h) { lsocket_t* ls = (lsocket_t*)h->data; pn_listener_t *l = ls->parent; if (l) { /* Remove from list */ lsocket_t **pp = &l->lsockets; for (; *pp != ls; pp = &(*pp)->next) ; *pp = ls->next; work_notify(&l->work); } free(ls); } /* Remember the first error code from a bad connect attempt. * This is not yet a full-blown error as we might succeed connecting * to a different address if there are several. */ static inline void pconnection_bad_connect(pconnection_t *pc, int err) { if (!pc->connected) { pc->connected = err; /* Remember first connect error in case they all fail */ } } /* Set the error condition, but don't close the driver. */ static void pconnection_set_error(pconnection_t *pc, int err, const char* what) { pn_connection_driver_t *driver = &pc->driver; pn_connection_driver_bind(driver); /* Make sure we are bound so errors will be reported */ pni_proactor_set_cond(pn_transport_condition(driver->transport), what, pc->addr.host , pc->addr.port, uv_strerror(err)); } /* Set the error condition and close the driver. */ static void pconnection_error(pconnection_t *pc, int err, const char* what) { assert(err); pconnection_bad_connect(pc, err); pconnection_set_error(pc, err, what); pn_connection_driver_close(&pc->driver); } static void listener_error_lh(pn_listener_t *l, int err, const char* what) { assert(err); if (!pn_condition_is_set(l->condition)) { pni_proactor_set_cond(l->condition, what, l->addr.host, l->addr.port, uv_strerror(err)); } listener_close_lh(l); } static void listener_error(pn_listener_t *l, int err, const char* what) { uv_mutex_lock(&l->lock); listener_error_lh(l, err, what); uv_mutex_unlock(&l->lock); } static int pconnection_init(pconnection_t *pc) { int err = 0; err = uv_tcp_init(&pc->work.proactor->loop, &pc->tcp); if (!err) { pc->tcp.data = pc; pc->connect.data = pc; err = uv_timer_init(&pc->work.proactor->loop, &pc->timer); if (!err) { pc->timer.data = pc; } else { uv_close((uv_handle_t*)&pc->tcp, NULL); } } if (err) { pconnection_error(pc, err, "initialization"); } return err; } static void try_connect(pconnection_t *pc); static void on_connect_fail(uv_handle_t *handle) { pconnection_t *pc = (pconnection_t*)handle->data; /* Create a new TCP socket, the current one is closed */ int err = uv_tcp_init(&pc->work.proactor->loop, &pc->tcp); if (err) { pc->connected = err; pc->addr.addrinfo = NULL; /* No point in trying anymore, we can't create a socket */ } else { try_connect(pc); } } static void pconnection_addresses(pconnection_t *pc) { int len; len = sizeof(pc->local.ss); uv_tcp_getsockname(&pc->tcp, (struct sockaddr*)&pc->local.ss, &len); len = sizeof(pc->remote.ss); uv_tcp_getpeername(&pc->tcp, (struct sockaddr*)&pc->remote.ss, &len); } /* Outgoing connection */ static void on_connect(uv_connect_t *connect, int err) { pconnection_t *pc = (pconnection_t*)connect->data; if (!err) { pc->connected = 1; pconnection_addresses(pc); work_notify(&pc->work); uv_freeaddrinfo(pc->addr.getaddrinfo.addrinfo); /* Done with address info */ pc->addr.getaddrinfo.addrinfo = NULL; } else { pconnection_bad_connect(pc, err); uv_safe_close((uv_handle_t*)&pc->tcp, on_connect_fail); /* Try the next addr if there is one */ } } /* Incoming connection ready to be accepted */ static void on_connection(uv_stream_t* server, int err) { /* Unlike most on_* functions, this can be called by the leader thread when the listener * is ON_WORKER or ON_LEADER, because * * 1. There's no way to stop libuv from calling on_connection(). * 2. There can be multiple lsockets per listener. * * Update the state of the listener and queue it for leader attention. */ lsocket_t *ls = (lsocket_t*)server->data; pn_listener_t *l = ls->parent; if (err) { listener_error(l, err, "on incoming connection"); } else { uv_mutex_lock(&l->lock); pn_collector_put(l->collector, PN_CLASSCLASS(pn_listener_socket), ls, PN_LISTENER_ACCEPT); uv_mutex_unlock(&l->lock); } work_notify(&l->work); } /* Common address resolution for leader_listen and leader_connect */ static int leader_resolve(pn_proactor_t *p, addr_t *addr, bool listen) { struct addrinfo hints = { 0 }; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_ADDRCONFIG; if (listen) { hints.ai_flags |= AI_PASSIVE | AI_ALL; } int err = uv_getaddrinfo(&p->loop, &addr->getaddrinfo, NULL, addr->host, addr->port, &hints); addr->addrinfo = addr->getaddrinfo.addrinfo; /* Start with the first addrinfo */ return err; } /* Try to connect to the current addrinfo. Called by leader and via callbacks for retry.*/ static void try_connect(pconnection_t *pc) { struct addrinfo *ai = pc->addr.addrinfo; if (!ai) { /* End of list, connect fails */ uv_freeaddrinfo(pc->addr.getaddrinfo.addrinfo); pc->addr.getaddrinfo.addrinfo = NULL; pconnection_bad_connect(pc, UV_EAI_NODATA); pconnection_error(pc, pc->connected, "connecting to"); work_notify(&pc->work); } else { pc->addr.addrinfo = ai->ai_next; /* Advance for next attempt */ int err = uv_tcp_connect(&pc->connect, &pc->tcp, ai->ai_addr, on_connect); if (err) { pconnection_bad_connect(pc, err); uv_close((uv_handle_t*)&pc->tcp, on_connect_fail); /* Queue up next attempt */ } } } static bool leader_connect(pconnection_t *pc) { int err = pconnection_init(pc); if (!err) err = leader_resolve(pc->work.proactor, &pc->addr, false); if (err) { pconnection_error(pc, err, "on connect resolving"); return true; } else { try_connect(pc); return false; } } static int lsocket(pn_listener_t *l, struct addrinfo *ai) { lsocket_t *ls = (lsocket_t*)calloc(1, sizeof(lsocket_t)); ls->type = T_LSOCKET; ls->tcp.data = ls; ls->parent = NULL; ls->next = NULL; int err = uv_tcp_init(&l->work.proactor->loop, &ls->tcp); if (err) { free(ls); /* Will never be closed */ } else { if (l->dynamic_port) set_port(ai->ai_addr, l->dynamic_port); int flags = (ai->ai_family == AF_INET6) ? UV_TCP_IPV6ONLY : 0; err = uv_tcp_bind(&ls->tcp, ai->ai_addr, flags); if (!err) err = uv_listen((uv_stream_t*)&ls->tcp, l->backlog, on_connection); if (!err) { /* Get actual listening address */ pn_netaddr_t *na = &l->addrs[l->addrs_len++]; int len = sizeof(na->ss); uv_tcp_getsockname(&ls->tcp, (struct sockaddr*)(&na->ss), &len); if (na == l->addrs) { /* First socket, check for dynamic port bind */ l->dynamic_port = check_dynamic_port(ai->ai_addr, pn_netaddr_sockaddr(na)); } else { (na-1)->next = na; /* Link into list */ } /* Add to l->lsockets list */ ls->parent = l; ls->next = l->lsockets; l->lsockets = ls; } else { uv_close((uv_handle_t*)&ls->tcp, on_close_lsocket); /* Freed by on_close_lsocket */ } } return err; } #define ARRAY_LEN(A) (sizeof(A)/sizeof(*(A))) /* Listen on all available addresses */ static void leader_listen_lh(pn_listener_t *l) { int err = leader_resolve(l->work.proactor, &l->addr, true); if (!err) { /* Allocate enough space for the pn_netaddr_t addresses */ size_t len = 0; for (struct addrinfo *ai = l->addr.getaddrinfo.addrinfo; ai; ai = ai->ai_next) { ++len; } l->addrs = (pn_netaddr_t*)calloc(len, sizeof(pn_netaddr_t)); /* Find the working addresses */ for (struct addrinfo *ai = l->addr.getaddrinfo.addrinfo; ai; ai = ai->ai_next) { int err2 = lsocket(l, ai); if (err2) { err = err2; } } uv_freeaddrinfo(l->addr.getaddrinfo.addrinfo); l->addr.getaddrinfo.addrinfo = NULL; if (l->lsockets) { /* Ignore errors if we got at least one good listening socket */ err = 0; } } if (err) { listener_error_lh(l, err, "listening on"); } else { pn_collector_put(l->collector, PN_CLASSCLASS(pn_listener), l, PN_LISTENER_OPEN); } } void pn_listener_free(pn_listener_t *l) { if (l) { if (l->addrs) free(l->addrs); if (l->addr.getaddrinfo.addrinfo) { /* Interrupted after resolve */ uv_freeaddrinfo(l->addr.getaddrinfo.addrinfo); } if (l->collector) pn_collector_free(l->collector); if (l->condition) pn_condition_free(l->condition); if (l->attachments) pn_free(l->attachments); while (l->lsockets) { lsocket_t *ls = l->lsockets; l->lsockets = ls->next; free(ls); } assert(!l->accept.front); uv_mutex_destroy(&l->lock); free(l); } } /* Process a listener, return true if it has events for a worker thread */ static bool leader_process_listener(pn_listener_t *l) { /* NOTE: l may be concurrently accessed by on_connection() */ bool closed = false; uv_mutex_lock(&l->lock); /* Process accepted connections */ for (pconnection_t *pc = pconnection_pop(&l->accept); pc; pc = pconnection_pop(&l->accept)) { int err = pconnection_init(pc); if (!err) err = uv_accept((uv_stream_t*)&pc->lsocket->tcp, (uv_stream_t*)&pc->tcp); if (!err) { pconnection_addresses(pc); } else { listener_error(l, err, "accepting from"); pconnection_error(pc, err, "accepting from"); } work_start(&pc->work); /* Process events for the accepted/failed connection */ } switch (l->state) { case L_UNINIT: l->state = L_LISTENING; leader_listen_lh(l); break; case L_LISTENING: break; case L_CLOSE: /* Close requested, start closing lsockets */ l->state = L_CLOSING; for (lsocket_t *ls = l->lsockets; ls; ls = ls->next) { uv_safe_close((uv_handle_t*)&ls->tcp, on_close_lsocket); } /* NOTE: Fall through in case we have 0 sockets - e.g. resolver error */ case L_CLOSING: /* Closing - can we send PN_LISTENER_CLOSE? */ if (!l->lsockets) { l->state = L_CLOSED; pn_collector_put(l->collector, PN_CLASSCLASS(pn_listener), l, PN_LISTENER_CLOSE); } break; case L_CLOSED: /* Closed, has LISTENER_CLOSE has been processed? */ if (!pn_collector_peek(l->collector)) { remove_active(l->work.proactor); closed = true; } } bool has_work = !closed && pn_collector_peek(l->collector); uv_mutex_unlock(&l->lock); if (closed) { pn_listener_free(l); } return has_work; } /* Generate tick events and return millis till next tick or 0 if no tick is required */ static pn_millis_t leader_tick(pconnection_t *pc) { uint64_t now = uv_now(pc->timer.loop); uint64_t next = pn_transport_tick(pc->driver.transport, now); return next ? next - now : 0; } static void on_tick(uv_timer_t *timer) { pconnection_t *pc = (pconnection_t*)timer->data; leader_tick(pc); work_notify(&pc->work); } static void on_read(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) { pconnection_t *pc = (pconnection_t*)stream->data; if (nread > 0) { pn_connection_driver_read_done(&pc->driver, nread); } else if (nread < 0) { if (nread != UV_EOF) { /* hangup */ pconnection_set_error(pc, nread, "on read from"); } pn_connection_driver_close(&pc->driver); } work_notify(&pc->work); } static void on_write(uv_write_t* write, int err) { pconnection_t *pc = (pconnection_t*)write->data; size_t size = pc->writing; pc->writing = 0; if (err) { pconnection_set_error(pc, err, "on write to"); pn_connection_driver_write_close(&pc->driver); } else if (!pn_connection_driver_write_closed(&pc->driver)) { pn_connection_driver_write_done(&pc->driver, size); } work_notify(&pc->work); } static void on_timeout(uv_timer_t *timer) { pn_proactor_t *p = (pn_proactor_t*)timer->data; uv_mutex_lock(&p->lock); if (p->timeout_state == TM_PENDING) { /* Only fire if still pending */ p->timeout_state = TM_FIRED; } uv_stop(&p->loop); /* UV does not always stop after on_timeout without this */ uv_mutex_unlock(&p->lock); } /* Read buffer allocation function for uv, just returns the transports read buffer. */ static void alloc_read_buffer(uv_handle_t* stream, size_t size, uv_buf_t* buf) { pconnection_t *pc = (pconnection_t*)stream->data; pn_rwbytes_t rbuf = pn_connection_driver_read_buffer(&pc->driver); *buf = uv_buf_init(rbuf.start, rbuf.size); } /* Set the event in the proactor's batch */ static pn_event_batch_t *proactor_batch_lh(pn_proactor_t *p, pn_event_type_t t) { pn_collector_put(p->collector, PN_CLASSCLASS(pn_proactor), p, t); p->batch_working = true; return &p->batch; } static pn_event_t *listener_batch_next(pn_event_batch_t *batch) { pn_listener_t *l = batch_listener(batch); uv_mutex_lock(&l->lock); pn_event_t *e = pn_collector_next(l->collector); uv_mutex_unlock(&l->lock); return pni_log_event(l, e); } static pn_event_t *proactor_batch_next(pn_event_batch_t *batch) { pn_proactor_t *p = batch_proactor(batch); assert(p->batch_working); return pni_log_event(p, pn_collector_next(p->collector)); } static pn_event_t *pconnection_batch_next(pn_event_batch_t *batch) { pconnection_t *pc = batch_pconnection(batch); return pn_connection_driver_next_event(&pc->driver); } /* Return the next event batch or NULL if no events are available */ static pn_event_batch_t *get_batch_lh(pn_proactor_t *p) { if (!p->batch_working) { /* Can generate proactor events */ if (p->need_inactive) { p->need_inactive = false; return proactor_batch_lh(p, PN_PROACTOR_INACTIVE); } if (p->need_interrupt) { p->need_interrupt = false; return proactor_batch_lh(p, PN_PROACTOR_INTERRUPT); } if (p->timeout_state == TM_FIRED) { p->timeout_state = TM_NONE; p->timeout_processed = true; return proactor_batch_lh(p, PN_PROACTOR_TIMEOUT); } } for (work_t *w = work_pop(&p->worker_q); w; w = work_pop(&p->worker_q)) { assert(w->working); switch (w->type) { case T_CONNECTION: return &((pconnection_t*)w)->batch; case T_LISTENER: return &((pn_listener_t*)w)->batch; default: break; } } return NULL; } /* Check wake state and generate WAKE event if needed */ static void check_wake(pconnection_t *pc) { uv_mutex_lock(&pc->lock); if (pc->wake == W_PENDING) { pn_connection_t *c = pc->driver.connection; pn_collector_put_object(pn_connection_collector(c), c, PN_CONNECTION_WAKE); pc->wake = W_NONE; } uv_mutex_unlock(&pc->lock); } /* Process a pconnection, return true if it has events for a worker thread */ static bool leader_process_pconnection(pconnection_t *pc) { /* Important to do the following steps in order */ if (!pc->connected) { return leader_connect(pc); } if (pc->writing) { /* We can't do anything while a write request is pending */ return false; } /* Must process INIT and BOUND events before we do any IO-related stuff */ if (pn_connection_driver_has_event(&pc->driver)) { return true; } if (pn_connection_driver_finished(&pc->driver)) { uv_mutex_lock(&pc->lock); pc->wake = W_CLOSED; /* wake() is a no-op from now on */ uv_mutex_unlock(&pc->lock); uv_safe_close((uv_handle_t*)&pc->tcp, on_close_pconnection); } else { /* Check for events that can be generated without blocking for IO */ check_wake(pc); pn_millis_t next_tick = leader_tick(pc); pn_rwbytes_t rbuf = pn_connection_driver_read_buffer(&pc->driver); pn_bytes_t wbuf = pn_connection_driver_write_buffer(&pc->driver); /* If we still have no events, make async UV requests */ if (!pn_connection_driver_has_event(&pc->driver)) { int err = 0; const char *what = NULL; if (!err && next_tick) { what = "connection timer start"; err = uv_timer_start(&pc->timer, on_tick, next_tick, 0); } if (!err) { what = "write"; if (wbuf.size > 0) { uv_buf_t buf = uv_buf_init((char*)wbuf.start, wbuf.size); err = uv_write(&pc->write, (uv_stream_t*)&pc->tcp, &buf, 1, on_write); if (!err) { pc->writing = wbuf.size; } } else if (pn_connection_driver_write_closed(&pc->driver)) { uv_shutdown(&pc->shutdown, (uv_stream_t*)&pc->tcp, NULL); } } if (!err && !pc->read_started && rbuf.size > 0) { what = "read"; err = uv_read_start((uv_stream_t*)&pc->tcp, alloc_read_buffer, on_read); if (!err) { pc->read_started = true; } } if (err) { /* Some IO requests failed, generate the error events */ pconnection_error(pc, err, what); } } } return pn_connection_driver_has_event(&pc->driver); } /* Detach a connection from the UV loop so it can be used safely by a worker */ void pconnection_detach(pconnection_t *pc) { if (pc->connected && !pc->writing) { /* Can't detach while a write is pending */ if (pc->read_started) { uv_read_stop((uv_stream_t*)&pc->tcp); pc->read_started = false; } uv_timer_stop(&pc->timer); } } static void on_proactor_disconnect(uv_handle_t* h, void* v) { if (h->type == UV_TCP) { switch (*(struct_type*)h->data) { case T_CONNECTION: { pconnection_t *pc = (pconnection_t*)h->data; pn_condition_t *cond = pc->work.proactor->disconnect_cond; if (cond) { pn_condition_copy(pn_transport_condition(pc->driver.transport), cond); } pn_connection_driver_close(&pc->driver); work_notify(&pc->work); break; } case T_LSOCKET: { pn_listener_t *l = ((lsocket_t*)h->data)->parent; if (l) { pn_condition_t *cond = l->work.proactor->disconnect_cond; if (cond) { pn_condition_copy(pn_listener_condition(l), cond); } pn_listener_close(l); } break; } default: break; } } } /* Process the leader_q and the UV loop, in the leader thread */ static pn_event_batch_t *leader_lead_lh(pn_proactor_t *p, uv_run_mode mode) { /* Set timeout timer if there was a request, let it count down while we process work */ if (p->timeout_state == TM_REQUEST) { p->timeout_state = TM_PENDING; uv_timer_stop(&p->timer); uv_timer_start(&p->timer, on_timeout, p->timeout, 0); } /* If disconnect was requested, walk the socket list */ if (p->disconnect) { p->disconnect = false; if (p->active) { uv_mutex_unlock(&p->lock); uv_walk(&p->loop, on_proactor_disconnect, NULL); uv_mutex_lock(&p->lock); } else { p->need_inactive = true; /* Send INACTIVE right away, nothing to do. */ } } pn_event_batch_t *batch = NULL; for (work_t *w = work_pop(&p->leader_q); w; w = work_pop(&p->leader_q)) { assert(!w->working); uv_mutex_unlock(&p->lock); /* Unlock to process each item, may add more items to leader_q */ bool has_work = false; switch (w->type) { case T_CONNECTION: has_work = leader_process_pconnection((pconnection_t*)w); break; case T_LISTENER: has_work = leader_process_listener((pn_listener_t*)w); break; default: break; } uv_mutex_lock(&p->lock); if (has_work && !w->working && w->next == work_unqueued) { if (w->type == T_CONNECTION) { pconnection_detach((pconnection_t*)w); } w->working = true; work_push(&p->worker_q, w); } } batch = get_batch_lh(p); /* Check for work */ if (!batch) { /* No work, run the UV loop */ uv_mutex_unlock(&p->lock); /* Unlock to run UV loop */ uv_run(&p->loop, mode); uv_mutex_lock(&p->lock); batch = get_batch_lh(p); } return batch; } /**** public API ****/ pn_event_batch_t *pn_proactor_get(struct pn_proactor_t* p) { uv_mutex_lock(&p->lock); pn_event_batch_t *batch = get_batch_lh(p); if (batch == NULL && !p->has_leader) { /* Try a non-blocking lead to generate some work */ p->has_leader = true; batch = leader_lead_lh(p, UV_RUN_NOWAIT); p->has_leader = false; uv_cond_broadcast(&p->cond); /* Signal followers for possible work */ } uv_mutex_unlock(&p->lock); return batch; } pn_event_batch_t *pn_proactor_wait(struct pn_proactor_t* p) { uv_mutex_lock(&p->lock); pn_event_batch_t *batch = get_batch_lh(p); while (!batch && p->has_leader) { uv_cond_wait(&p->cond, &p->lock); /* Follow the leader */ batch = get_batch_lh(p); } if (!batch) { /* Become leader */ p->has_leader = true; do { batch = leader_lead_lh(p, UV_RUN_ONCE); } while (!batch); p->has_leader = false; uv_cond_broadcast(&p->cond); /* Signal a followers. One takes over, many can work. */ } uv_mutex_unlock(&p->lock); return batch; } void pn_proactor_done(pn_proactor_t *p, pn_event_batch_t *batch) { if (!batch) return; uv_mutex_lock(&p->lock); work_t *w = batch_work(batch); if (w) { assert(w->working); assert(w->next == work_unqueued); w->working = false; work_push(&p->leader_q, w); } pn_proactor_t *bp = batch_proactor(batch); /* Proactor events */ if (bp == p) { p->batch_working = false; if (p->timeout_processed) { p->timeout_processed = false; check_for_inactive(p); } } uv_mutex_unlock(&p->lock); notify(p); } pn_listener_t *pn_event_listener(pn_event_t *e) { if (pn_event_class(e) == PN_CLASSCLASS(pn_listener)) { return (pn_listener_t*)pn_event_context(e); } else if (pn_event_class(e) == PN_CLASSCLASS(pn_listener_socket)) { return ((lsocket_t*)pn_event_context(e))->parent; } else { return NULL; } } pn_proactor_t *pn_event_proactor(pn_event_t *e) { if (pn_event_class(e) == PN_CLASSCLASS(pn_proactor)) { return (pn_proactor_t*)pn_event_context(e); } pn_listener_t *l = pn_event_listener(e); if (l) { return l->work.proactor; } pn_connection_t *c = pn_event_connection(e); if (c) { return pn_connection_proactor(pn_event_connection(e)); } return NULL; } void pn_proactor_interrupt(pn_proactor_t *p) { /* NOTE: pn_proactor_interrupt must be async-signal-safe so we cannot use locks to update shared proactor state here. Instead we use a dedicated uv_async, the on_interrupt() callback will set the interrupt flag in the safety of the leader thread. */ uv_async_send(&p->interrupt); } void pn_proactor_disconnect(pn_proactor_t *p, pn_condition_t *cond) { uv_mutex_lock(&p->lock); if (!p->disconnect) { p->disconnect = true; if (cond) { pn_condition_copy(p->disconnect_cond, cond); } else { pn_condition_clear(p->disconnect_cond); } notify(p); } uv_mutex_unlock(&p->lock); } void pn_proactor_set_timeout(pn_proactor_t *p, pn_millis_t t) { uv_mutex_lock(&p->lock); p->timeout = t; // This timeout *replaces* any existing timeout p->timeout_state = TM_REQUEST; uv_mutex_unlock(&p->lock); notify(p); } void pn_proactor_cancel_timeout(pn_proactor_t *p) { uv_mutex_lock(&p->lock); if (p->timeout_state != TM_NONE) { p->timeout_state = TM_NONE; check_for_inactive(p); notify(p); } uv_mutex_unlock(&p->lock); } void pn_proactor_connect2(pn_proactor_t *p, pn_connection_t *c, pn_transport_t *t, const char *addr) { pconnection_t *pc = pconnection(p, c, t, false); assert(pc); /* TODO aconway 2017-03-31: memory safety */ add_active(p); pn_connection_open(pc->driver.connection); /* Auto-open */ parse_addr(&pc->addr, addr); work_start(&pc->work); } void pn_proactor_listen(pn_proactor_t *p, pn_listener_t *l, const char *addr, int backlog) { work_init(&l->work, p, T_LISTENER); parse_addr(&l->addr, addr); l->backlog = backlog; add_active(l->work.proactor); /* Owned by proactor. Track it for PN_PROACTOR_INACTIVE. */; work_start(&l->work); } static void on_proactor_free(uv_handle_t* h, void* v) { uv_safe_close(h, NULL); /* Close the handle */ if (h->type == UV_TCP) { /* Put the corresponding work item on the leader_q for cleanup */ work_t *w = NULL; switch (*(struct_type*)h->data) { case T_CONNECTION: w = (work_t*)h->data; break; case T_LSOCKET: w = &((lsocket_t*)h->data)->parent->work; break; default: break; } if (w && w->next == work_unqueued) { work_push(&w->proactor->leader_q, w); /* Save to be freed after all closed */ } } } static void work_free(work_t *w) { switch (w->type) { case T_CONNECTION: pconnection_free((pconnection_t*)w); break; case T_LISTENER: pn_listener_free((pn_listener_t*)w); break; default: break; } } pn_proactor_t *pn_proactor(void) { uv_once(&global_init_once, global_init_fn); pn_proactor_t *p = (pn_proactor_t*)calloc(1, sizeof(pn_proactor_t)); p->collector = pn_collector(); if (!p->collector) { free(p); return NULL; } p->batch.next_event = &proactor_batch_next; uv_loop_init(&p->loop); uv_mutex_init(&p->lock); uv_cond_init(&p->cond); uv_async_init(&p->loop, &p->notify, NULL); uv_async_init(&p->loop, &p->interrupt, on_interrupt); p->interrupt.data = p; uv_timer_init(&p->loop, &p->timer); p->timer.data = p; p->disconnect_cond = pn_condition(); return p; } void pn_proactor_free(pn_proactor_t *p) { /* Close all open handles */ uv_walk(&p->loop, on_proactor_free, NULL); while (uv_loop_alive(&p->loop)) { uv_run(&p->loop, UV_RUN_DEFAULT); /* Finish closing the proactor handles */ } /* Free all work items */ for (work_t *w = work_pop(&p->leader_q); w; w = work_pop(&p->leader_q)) { work_free(w); } for (work_t *w = work_pop(&p->worker_q); w; w = work_pop(&p->worker_q)) { work_free(w); } uv_loop_close(&p->loop); uv_mutex_destroy(&p->lock); uv_cond_destroy(&p->cond); pn_collector_free(p->collector); pn_condition_free(p->disconnect_cond); free(p); } pn_proactor_t *pn_connection_proactor(pn_connection_t* c) { pconnection_t *pc = get_pconnection(c); return pc ? pc->work.proactor : NULL; } void pn_connection_wake(pn_connection_t* c) { /* May be called from any thread */ pconnection_t *pc = get_pconnection(c); if (pc) { bool notify = false; uv_mutex_lock(&pc->lock); if (pc->wake == W_NONE) { pc->wake = W_PENDING; notify = true; } uv_mutex_unlock(&pc->lock); if (notify) { work_notify(&pc->work); } } } void pn_proactor_release_connection(pn_connection_t *c) { pconnection_t *pc = get_pconnection(c); if (pc) { set_pconnection(c, NULL); pn_connection_driver_release_connection(&pc->driver); } } pn_listener_t *pn_listener(void) { pn_listener_t *l = (pn_listener_t*)calloc(1, sizeof(pn_listener_t)); if (l) { l->batch.next_event = listener_batch_next; l->collector = pn_collector(); l->condition = pn_condition(); l->attachments = pn_record(); if (!l->condition || !l->collector || !l->attachments) { pn_listener_free(l); return NULL; } uv_mutex_init(&l->lock); } return l; } void pn_listener_close(pn_listener_t* l) { /* May be called from any thread */ uv_mutex_lock(&l->lock); listener_close_lh(l); uv_mutex_unlock(&l->lock); } pn_proactor_t *pn_listener_proactor(pn_listener_t* l) { return l ? l->work.proactor : NULL; } pn_condition_t* pn_listener_condition(pn_listener_t* l) { return l->condition; } void *pn_listener_get_context(pn_listener_t *l) { return l->context; } void pn_listener_set_context(pn_listener_t *l, void *context) { l->context = context; } pn_record_t *pn_listener_attachments(pn_listener_t *l) { return l->attachments; } void pn_listener_accept2(pn_listener_t *l, pn_connection_t *c, pn_transport_t *t) { pconnection_t *pc = pconnection(l->work.proactor, c, t, true); assert(pc); add_active(l->work.proactor); uv_mutex_lock(&l->lock); /* Get the socket from the accept event that we are processing */ pn_event_t *e = pn_collector_prev(l->collector); assert(pn_event_type(e) == PN_LISTENER_ACCEPT); assert(pn_event_listener(e) == l); pc->lsocket = (lsocket_t*)pn_event_context(e); pc->connected = 1; /* Don't need to connect() */ pconnection_push(&l->accept, pc); uv_mutex_unlock(&l->lock); work_notify(&l->work); } const pn_netaddr_t *pn_transport_local_addr(pn_transport_t *t) { pconnection_t *pc = get_pconnection(pn_transport_connection(t)); return pc? &pc->local : NULL; } const pn_netaddr_t *pn_transport_remote_addr(pn_transport_t *t) { pconnection_t *pc = get_pconnection(pn_transport_connection(t)); return pc ? &pc->remote : NULL; } const pn_netaddr_t *pn_listener_addr(pn_listener_t *l) { return l->addrs ? &l->addrs[0] : NULL; } pn_millis_t pn_proactor_now(void) { return (pn_millis_t) pn_proactor_now_64(); } int64_t pn_proactor_now_64(void) { return uv_hrtime() / 1000000; // uv_hrtime returns time in nanoseconds } // Empty stub for pending write flush functionality. void pn_connection_write_flush(pn_connection_t *connection) {} // Empty stubs for raw connection code pn_raw_connection_t *pn_raw_connection(void) { return NULL; } void pn_proactor_raw_connect(pn_proactor_t *p, pn_raw_connection_t *rc, const char *addr) {} void pn_listener_raw_accept(pn_listener_t *l, pn_raw_connection_t *rc) {} void pn_raw_connection_wake(pn_raw_connection_t *conn) {} void pn_raw_connection_close(pn_raw_connection_t *conn) {} void pn_raw_connection_read_close(pn_raw_connection_t *conn) {} void pn_raw_connection_write_close(pn_raw_connection_t *conn) {} const struct pn_netaddr_t *pn_raw_connection_local_addr(pn_raw_connection_t *connection) { return NULL; } const struct pn_netaddr_t *pn_raw_connection_remote_addr(pn_raw_connection_t *connection) { return NULL; } pn_raw_connection_t *pn_event_batch_raw_connection(pn_event_batch_t* batch) { return NULL; }
781ecea5007ef8d4c20bb3e0dd319501d0490f16
c013cf150a7ae728caa1468125f0d42f7a5a52eb
/src/chiabls/contrib/relic/src/eb/relic_eb_mul.c
cd3cdb02ced27a70404ef10f440f2f00e066264c
[ "Apache-2.0", "ISC", "LGPL-3.0-only", "MIT", "LGPL-2.1-only", "LGPL-2.0-or-later", "LGPL-2.1-or-later", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
PIVX-Project/PIVX
c9d209ea7b8cee627f5ccc1cb63d334b68c454de
7488a2721da8a4defc08d145dadd3c3065e2735d
refs/heads/master
2023-08-19T10:18:31.494805
2023-08-17T03:38:56
2023-08-17T03:40:09
50,740,659
663
1,520
MIT
2023-09-13T06:26:34
2016-01-30T19:20:24
C++
UTF-8
C
false
false
22,241
c
relic_eb_mul.c
/* * RELIC is an Efficient LIbrary for Cryptography * Copyright (c) 2009 RELIC Authors * * This file is part of RELIC. RELIC is legal property of its developers, * whose names are not listed here. Please refer to the COPYRIGHT file * for contact information. * * RELIC is free software; you can redistribute it and/or modify it under the * terms of the version 2.1 (or later) of the GNU Lesser General Public License * as published by the Free Software Foundation; or version 2.0 of the Apache * License as published by the Apache Software Foundation. See the LICENSE files * for more details. * * RELIC 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 LICENSE files for more details. * * You should have received a copy of the GNU Lesser General Public or the * Apache License along with RELIC. If not, see <https://www.gnu.org/licenses/> * or <https://www.apache.org/licenses/>. */ /** * @file * * Implementation of point multiplication on binary elliptic curves. * * @ingroup eb */ #include "relic_core.h" #include "relic_fb_low.h" /*============================================================================*/ /* Private definitions */ /*============================================================================*/ #if EB_MUL == LWNAF || !defined(STRIP) #if defined(EB_KBLTZ) /** * Multiplies a binary elliptic curve point by an integer using the w-TNAF * method. * * @param[out] r - the result. * @param[in] p - the point to multiply. * @param[in] k - the integer. */ static void eb_mul_ltnaf_imp(eb_t r, const eb_t p, const bn_t k) { int i, l, n; int8_t tnaf[RLC_FB_BITS + 8], u; eb_t t[1 << (EB_WIDTH - 2)]; if (eb_curve_opt_a() == RLC_ZERO) { u = -1; } else { u = 1; } RLC_TRY { /* Prepare the precomputation table. */ for (i = 0; i < (1 << (EB_WIDTH - 2)); i++) { eb_null(t[i]); eb_new(t[i]); } /* Compute the precomputation table. */ eb_tab(t, p, EB_WIDTH); /* Compute the w-TNAF representation of k. */ l = sizeof(tnaf); bn_rec_tnaf(tnaf, &l, k, u, RLC_FB_BITS, EB_WIDTH); n = tnaf[l - 1]; if (n > 0) { eb_copy(r, t[n / 2]); } else { eb_neg(r, t[-n / 2]); } for (i = l - 2; i >= 0; i--) { eb_frb(r, r); n = tnaf[i]; if (n > 0) { eb_add(r, r, t[n / 2]); } if (n < 0) { eb_sub(r, r, t[-n / 2]); } } /* Convert r to affine coordinates. */ eb_norm(r, r); if (bn_sign(k) == RLC_NEG) { eb_neg(r, r); } } RLC_CATCH_ANY { RLC_THROW(ERR_CAUGHT); } RLC_FINALLY { /* Free the precomputation table. */ for (i = 0; i < (1 << (EB_WIDTH - 2)); i++) { eb_free(t[i]); } } } #endif #if defined(EB_PLAIN) /** * Multiplies a binary elliptic curve point by an integer using the * left-to-right w-NAF method. * * @param[out] r - the result. * @param[in] p - the point to multiply. * @param[in] k - the integer. */ static void eb_mul_lnaf_imp(eb_t r, const eb_t p, const bn_t k) { int i, l, n; int8_t naf[RLC_FB_BITS + 1]; eb_t t[1 << (EB_WIDTH - 2)]; RLC_TRY { /* Prepare the precomputation table. */ for (i = 0; i < (1 << (EB_WIDTH - 2)); i++) { eb_null(t[i]); eb_new(t[i]); eb_set_infty(t[i]); fb_set_dig(t[i]->z, 1); t[i]->coord = BASIC; } /* Compute the precomputation table. */ eb_tab(t, p, EB_WIDTH); /* Compute the w-NAF representation of k. */ l = sizeof(naf); bn_rec_naf(naf, &l, k, EB_WIDTH); n = naf[l - 1]; if (n > 0) { eb_copy(r, t[n / 2]); } for (i = l - 2; i >= 0; i--) { eb_dbl(r, r); n = naf[i]; if (n > 0) { eb_add(r, r, t[n / 2]); } if (n < 0) { eb_sub(r, r, t[-n / 2]); } } /* Convert r to affine coordinates. */ eb_norm(r, r); if (bn_sign(k) == RLC_NEG) { eb_neg(r, r); } } RLC_CATCH_ANY { RLC_THROW(ERR_CAUGHT); } RLC_FINALLY { /* Free the precomputation table. */ for (i = 0; i < (1 << (EB_WIDTH - 2)); i++) { eb_free(t[i]); } } } #endif /* EB_PLAIN */ #endif /* EB_MUL == LWNAF */ #if EB_MUL == RWNAF || !defined(STRIP) #if defined(EB_KBLTZ) /** * Multiplies a binary elliptic curve point by an integer using the w-TNAF * method. * * @param[out] r - the result. * @param[in] p - the point to multiply. * @param[in] k - the integer. */ static void eb_mul_rtnaf_imp(eb_t r, const eb_t p, const bn_t k) { int i, l, n; int8_t tnaf[RLC_FB_BITS + 8], u; eb_t t[1 << (EB_WIDTH - 2)]; if (eb_curve_opt_a() == RLC_ZERO) { u = -1; } else { u = 1; } RLC_TRY { /* Prepare the precomputation table. */ for (i = 0; i < (1 << (EB_WIDTH - 2)); i++) { eb_null(t[i]); eb_new(t[i]); eb_set_infty(t[i]); } /* Compute the w-TNAF representation of k. */ l = sizeof(tnaf); bn_rec_tnaf(tnaf, &l, k, u, RLC_FB_BITS, EB_WIDTH); eb_copy(r, p); for (i = 0; i < l; i++) { n = tnaf[i]; if (n > 0) { eb_add(t[n / 2], t[n / 2], r); } if (n < 0) { eb_sub(t[-n / 2], t[-n / 2], r); } /* We can avoid a function call here. */ fb_sqr(r->x, r->x); fb_sqr(r->y, r->y); } eb_copy(r, t[0]); #if defined(EB_MIXED) && defined(STRIP) && (EB_WIDTH > 2) eb_norm_sim(t + 1, (const eb_t *)t + 1, (1 << (EB_WIDTH - 2)) - 1); #endif #if EB_WIDTH == 3 eb_frb(t[0], t[1]); if (u == 1) { eb_sub(t[1], t[1], t[0]); } else { eb_add(t[1], t[1], t[0]); } #endif #if EB_WIDTH == 4 eb_frb(t[0], t[3]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); if (u == 1) { eb_neg(t[0], t[0]); } eb_sub(t[3], t[0], t[3]); eb_frb(t[0], t[1]); eb_frb(t[0], t[0]); eb_sub(t[1], t[0], t[1]); eb_frb(t[0], t[2]); eb_frb(t[0], t[0]); eb_add(t[2], t[0], t[2]); #endif #if EB_WIDTH == 5 eb_frb(t[0], t[3]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); if (u == 1) { eb_neg(t[0], t[0]); } eb_sub(t[3], t[0], t[3]); eb_frb(t[0], t[1]); eb_frb(t[0], t[0]); eb_sub(t[1], t[0], t[1]); eb_frb(t[0], t[2]); eb_frb(t[0], t[0]); eb_add(t[2], t[0], t[2]); eb_frb(t[0], t[4]); eb_frb(t[0], t[0]); eb_add(t[0], t[0], t[4]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); if (u == 1) { eb_neg(t[0], t[0]); } eb_add(t[4], t[0], t[4]); eb_frb(t[0], t[5]); eb_frb(t[0], t[0]); eb_add(t[0], t[0], t[5]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_neg(t[0], t[0]); eb_sub(t[5], t[0], t[5]); eb_frb(t[0], t[6]); eb_frb(t[0], t[0]); eb_add(t[0], t[0], t[6]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_neg(t[0], t[0]); eb_add(t[6], t[0], t[6]); eb_frb(t[0], t[7]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_sub(t[7], t[0], t[7]); #endif #if EB_WIDTH == 6 eb_frb(t[0], t[1]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); if (u == -1) { eb_neg(t[0], t[0]); } eb_add(t[0], t[0], t[1]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_sub(t[1], t[0], t[1]); eb_frb(t[0], t[2]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); if (u == -1) { eb_neg(t[0], t[0]); } eb_add(t[0], t[0], t[2]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_add(t[2], t[0], t[2]); eb_frb(t[0], t[3]); eb_frb(t[0], t[0]); eb_add(t[0], t[0], t[3]); eb_neg(t[0], t[0]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); if (u == -1) { eb_neg(t[0], t[0]); } eb_sub(t[3], t[0], t[3]); eb_frb(t[0], t[4]); eb_frb(t[0], t[0]); eb_add(t[0], t[0], t[4]); eb_neg(t[0], t[0]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); if (u == -1) { eb_neg(t[0], t[0]); } eb_add(t[4], t[0], t[4]); eb_frb(t[0], t[5]); eb_frb(t[0], t[0]); eb_add(t[0], t[0], t[5]); eb_neg(t[0], t[0]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_sub(t[5], t[0], t[5]); eb_frb(t[0], t[6]); eb_frb(t[0], t[0]); eb_add(t[0], t[0], t[6]); eb_neg(t[0], t[0]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_add(t[6], t[0], t[6]); eb_frb(t[0], t[7]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_sub(t[7], t[0], t[7]); eb_frb(t[0], t[8]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_add(t[8], t[0], t[8]); eb_frb(t[0], t[9]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); if (u == -1) { eb_neg(t[0], t[0]); } eb_add(t[0], t[0], t[9]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_sub(t[0], t[0], t[9]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_add(t[0], t[0], t[9]); eb_neg(t[9], t[0]); eb_frb(t[0], t[10]); eb_frb(t[0], t[0]); eb_neg(t[0], t[0]); eb_add(t[0], t[0], t[10]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_add(t[10], t[0], t[10]); eb_frb(t[0], t[11]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); if (u == -1) { eb_neg(t[0], t[0]); } eb_sub(t[11], t[0], t[11]); eb_frb(t[0], t[12]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); if (u == -1) { eb_neg(t[0], t[0]); } eb_add(t[12], t[0], t[12]); eb_frb(t[0], t[13]); eb_frb(t[0], t[0]); eb_add(t[0], t[0], t[13]); eb_neg(t[13], t[0]); eb_frb(t[0], t[14]); eb_frb(t[0], t[0]); eb_neg(t[0], t[0]); eb_add(t[14], t[0], t[14]); eb_frb(t[0], t[15]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); eb_frb(t[0], t[0]); if (u == -1) { eb_neg(t[0], t[0]); } eb_sub(t[15], t[0], t[15]); #endif #if defined(EB_MIXED) && defined(STRIP) && (EB_WIDTH > 2) eb_norm_sim(t + 1, (const eb_t *)t + 1, (1 << (EB_WIDTH - 2)) - 1); #endif /* Add accumulators */ for (i = 1; i < (1 << (EB_WIDTH - 2)); i++) { if (r->coord == BASIC) { eb_add(r, t[i], r); } else { eb_add(r, r, t[i]); } } /* Convert r to affine coordinates. */ eb_norm(r, r); if (bn_sign(k) == RLC_NEG) { eb_neg(r, r); } } RLC_CATCH_ANY { RLC_THROW(ERR_CAUGHT); } RLC_FINALLY { /* Free the precomputation table. */ for (i = 0; i < (1 << (EB_WIDTH - 2)); i++) { eb_free(t[i]); } } } #endif /* EB_KBLTZ */ #if defined(EB_PLAIN) /** * Multiplies a binary elliptic curve point by an integer using the * right-to-left w-NAF method. * * @param[out] r - the result. * @param[in] p - the point to multiply. * @param[in] k - the integer. */ static void eb_mul_rnaf_imp(eb_t r, const eb_t p, const bn_t k) { int i, l, n; int8_t naf[RLC_FB_BITS + 1]; eb_t t[1 << (EB_WIDTH - 2)]; RLC_TRY { /* Prepare the accumulator table. */ for (i = 0; i < (1 << (EB_WIDTH - 2)); i++) { eb_null(t[i]); eb_new(t[i]); eb_set_infty(t[i]); } /* Compute the w-NAF representation of k. */ l = sizeof(naf); bn_rec_naf(naf, &l, k, EB_WIDTH); eb_copy(r, p); for (i = 0; i < l; i++) { n = naf[i]; if (n > 0) { eb_add(t[n / 2], t[n / 2], r); } if (n < 0) { eb_sub(t[-n / 2], t[-n / 2], r); } eb_dbl(r, r); } eb_copy(r, t[0]); #if EB_WIDTH >= 3 /* Compute 3 * T[1]. */ eb_dbl(t[0], t[1]); eb_add(t[1], t[0], t[1]); #endif #if EB_WIDTH >= 4 /* Compute 5 * T[2]. */ eb_dbl(t[0], t[2]); eb_dbl(t[0], t[0]); eb_add(t[2], t[0], t[2]); /* Compute 7 * T[3]. */ eb_dbl(t[0], t[3]); eb_dbl(t[0], t[0]); eb_dbl(t[0], t[0]); eb_sub(t[3], t[0], t[3]); #endif #if EB_WIDTH >= 5 /* Compute 9 * T[4]. */ eb_dbl(t[0], t[4]); eb_dbl(t[0], t[0]); eb_dbl(t[0], t[0]); eb_add(t[4], t[0], t[4]); /* Compute 11 * T[5]. */ eb_dbl(t[0], t[5]); eb_dbl(t[0], t[0]); eb_add(t[0], t[0], t[5]); eb_dbl(t[0], t[0]); eb_add(t[5], t[0], t[5]); /* Compute 13 * T[6]. */ eb_dbl(t[0], t[6]); eb_add(t[0], t[0], t[6]); eb_dbl(t[0], t[0]); eb_dbl(t[0], t[0]); eb_add(t[6], t[0], t[6]); /* Compute 15 * T[7]. */ eb_dbl(t[0], t[7]); eb_dbl(t[0], t[0]); eb_dbl(t[0], t[0]); eb_dbl(t[0], t[0]); eb_sub(t[7], t[0], t[7]); #endif #if EB_WIDTH == 6 for (i = 8; i < 15; i++) { eb_mul_dig(t[i], t[i], 2 * i + 1); } eb_dbl(t[0], t[15]); eb_dbl(t[0], t[0]); eb_dbl(t[0], t[0]); eb_dbl(t[0], t[0]); eb_dbl(t[0], t[0]); eb_sub(t[15], t[0], t[15]); #endif /* Add accumulators */ for (i = 1; i < (1 << (EB_WIDTH - 2)); i++) { if (r->coord == BASIC) { eb_add(r, t[i], r); } else { eb_add(r, r, t[i]); } } /* Convert r to affine coordinates. */ eb_norm(r, r); if (bn_sign(k) == RLC_NEG) { eb_neg(r, r); } } RLC_CATCH_ANY { RLC_THROW(ERR_CAUGHT); } RLC_FINALLY { /* Free the accumulator table. */ for (i = 0; i < (1 << (EB_WIDTH - 2)); i++) { eb_free(t[i]); } } } #endif /* EB_PLAIN */ #endif /* EB_MUL == RWNAF */ /*============================================================================*/ /* Public definitions */ /*============================================================================*/ #if EB_MUL == BASIC || !defined(STRIP) void eb_mul_basic(eb_t r, const eb_t p, const bn_t k) { eb_t t; if (bn_is_zero(k) || eb_is_infty(p)) { eb_set_infty(r); return; } eb_null(t); RLC_TRY { eb_new(t); eb_copy(t, p); for (int i = bn_bits(k) - 2; i >= 0; i--) { eb_dbl(t, t); if (bn_get_bit(k, i)) { eb_add(t, t, p); } } eb_norm(r, t); if (bn_sign(k) == RLC_NEG) { eb_neg(r, r); } } RLC_CATCH_ANY { RLC_THROW(ERR_CAUGHT); } RLC_FINALLY { eb_free(t); } } #endif #if EB_MUL == LODAH || !defined(STRIP) void eb_mul_lodah(eb_t r, const eb_t p, const bn_t k) { int bits, i, j; dv_t x1, z1, x2, z2, r1, r2, r3, r4, r5; const dig_t *b; bn_t t, n; if (bn_is_zero(k)) { eb_set_infty(r); return; } bn_null(n); bn_null(t); dv_null(x1); dv_null(z1); dv_null(x2); dv_null(z2); dv_null(r1); dv_null(r2); dv_null(r3); dv_null(r4); dv_null(r5); RLC_TRY { bn_new(n); bn_new(t); dv_new(x1); dv_new(z1); dv_new(x2); dv_new(z2); dv_new(r1); dv_new(r2); dv_new(r3); dv_new(r4); dv_new(r5); fb_sqr(z2, p->x); fb_sqr(x2, z2); dv_zero(r5, 2 * RLC_FB_DIGS); b = eb_curve_get_b(); eb_curve_get_ord(n); bits = bn_bits(n); bn_abs(t, k); bn_add(t, t, n); bn_add(n, t, n); dv_swap_cond(t->dp, n->dp, RLC_MAX(t->used, n->used), bn_get_bit(t, bits) == 0); t->used = RLC_SEL(t->used, n->used, bn_get_bit(t, bits) == 0); switch (eb_curve_opt_b()) { case RLC_ZERO: break; case RLC_ONE: fb_add_dig(x2, x2, (dig_t)1); break; case RLC_TINY: fb_add_dig(x2, x2, b[0]); break; default: fb_addn_low(x2, x2, b); break; } /* Blind both points independently. */ fb_rand(z1); fb_mul(x1, z1, p->x); fb_rand(r1); fb_mul(z2, z2, r1); fb_mul(x2, x2, r1); for (i = bits - 1; i >= 0; i--) { j = bn_get_bit(t, i); fb_mul(r1, x1, z2); fb_mul(r2, x2, z1); fb_add(r3, r1, r2); fb_muln_low(r4, r1, r2); dv_swap_cond(x1, x2, RLC_FB_DIGS, j ^ 1); dv_swap_cond(z1, z2, RLC_FB_DIGS, j ^ 1); fb_sqr(z1, r3); fb_muln_low(r1, z1, p->x); fb_addd_low(x1, r1, r4, 2 * RLC_FB_DIGS); fb_rdcn_low(x1, x1); fb_sqr(r1, z2); fb_sqr(r2, x2); fb_mul(z2, r1, r2); switch (eb_curve_opt_b()) { case RLC_ZERO: fb_sqr(x2, r2); break; case RLC_ONE: fb_add(r1, r1, r2); fb_sqr(x2, r1); break; case RLC_TINY: fb_sqr(r1, r1); fb_sqrl_low(x2, r2); fb_mul1_low(r5, r1, b[0]); fb_addd_low(x2, x2, r5, RLC_FB_DIGS + 1); fb_rdcn_low(x2, x2); break; default: fb_sqr(r1, r1); fb_sqrl_low(x2, r2); fb_muln_low(r5, r1, b); fb_addd_low(x2, x2, r5, 2 * RLC_FB_DIGS); fb_rdcn_low(x2, x2); break; } dv_swap_cond(x1, x2, RLC_FB_DIGS, j ^ 1); dv_swap_cond(z1, z2, RLC_FB_DIGS, j ^ 1); } if (fb_is_zero(z1)) { /* The point q is at infinity. */ eb_set_infty(r); } else { if (fb_is_zero(z2)) { fb_copy(r->x, p->x); fb_add(r->y, p->x, p->y); fb_set_dig(r->z, 1); } else { /* r3 = z1 * z2. */ fb_mul(r3, z1, z2); /* z1 = (x1 + x * z1). */ fb_mul(z1, z1, p->x); fb_add(z1, z1, x1); /* z2 = x * z2. */ fb_mul(z2, z2, p->x); /* x1 = x1 * z2. */ fb_mul(x1, x1, z2); /* z2 = (x2 + x * z2)(x1 + x * z1). */ fb_add(z2, z2, x2); fb_mul(z2, z2, z1); /* r4 = (x^2 + y) * z1 * z2 + (x2 + x * z2)(x1 + x * z1). */ fb_sqr(r4, p->x); fb_add(r4, r4, p->y); fb_mul(r4, r4, r3); fb_add(r4, r4, z2); /* r3 = (z1 * z2 * x)^{-1}. */ fb_mul(r3, r3, p->x); fb_inv(r3, r3); /* r4 = (x^2 + y) * z1 * z2 + (x2 + x * z2)(x1 + x * z1) * r3. */ fb_mul(r4, r4, r3); /* x2 = x1 * x * z2 * (z1 * z2 * x)^{-1} = x1/z1. */ fb_mul(x2, x1, r3); /* z2 = x + x1/z1. */ fb_add(z2, x2, p->x); /* z2 = z2 * r4 + y. */ fb_mul(z2, z2, r4); fb_add(z2, z2, p->y); fb_copy(r->x, x2); fb_copy(r->y, z2); fb_set_dig(r->z, 1); } } r->coord = BASIC; if (bn_sign(k) == RLC_NEG) { eb_neg(r, r); } } RLC_CATCH_ANY { RLC_THROW(ERR_CAUGHT); } RLC_FINALLY { bn_free(n); bn_free(t); dv_free(x1); dv_free(z1); dv_free(x2); dv_free(z2); dv_free(r1); dv_free(r2); dv_free(r3); dv_free(r4); dv_free(r5); } } #endif /* EB_MUL == LODAH */ #if EB_MUL == LWNAF || !defined(STRIP) void eb_mul_lwnaf(eb_t r, const eb_t p, const bn_t k) { if (bn_is_zero(k) || eb_is_infty(p)) { eb_set_infty(r); return; } #if defined(EB_KBLTZ) if (eb_curve_is_kbltz()) { eb_mul_ltnaf_imp(r, p, k); return; } #endif #if defined(EB_PLAIN) eb_mul_lnaf_imp(r, p, k); #endif } #endif #if EB_MUL == RWNAF || !defined(STRIP) void eb_mul_rwnaf(eb_t r, const eb_t p, const bn_t k) { if (bn_is_zero(k) || eb_is_infty(p)) { eb_set_infty(r); return; } #if defined(EB_KBLTZ) if (eb_curve_is_kbltz()) { eb_mul_rtnaf_imp(r, p, k); return; } #endif #if defined(EB_PLAIN) #if defined(EB_MIXED) && defined(STRIP) /* It is impossible to run a right-to-left algorithm using ordinary curves * and only mixed additions. */ RLC_THROW(ERR_NO_CONFIG); #else eb_mul_rnaf_imp(r, p, k); #endif #endif } #endif #if EB_MUL == HALVE || !defined(STRIP) void eb_mul_halve(eb_t r, const eb_t p, const bn_t k) { int i, j, l, trc, cof; int8_t naf[RLC_FB_BITS + 1], *_k; eb_t q, s, t[1 << (EB_WIDTH - 2)]; bn_t n, m; fb_t u, v, w, z; if (bn_is_zero(k) || eb_is_infty(p)) { eb_set_infty(r); return; } bn_null(m); bn_null(n); eb_null(q); eb_null(s); for (i = 0; i < (1 << (EB_WIDTH - 2)); i++) { eb_null(t[i]); } fb_null(u); fb_null(v); fb_null(w); fb_null(z); RLC_TRY { bn_new(n); bn_new(m); eb_new(q); eb_new(s); fb_new(u); fb_new(v); fb_new(w); fb_new(z); /* Prepare the precomputation table. */ for (i = 0; i < (1 << (EB_WIDTH - 2)); i++) { eb_new(t[i]); eb_set_infty(t[i]); } /* Convert k to alternate representation k' = (2^{t-1}k mod n). */ eb_curve_get_ord(n); bn_lsh(m, k, bn_bits(n) - 1); bn_mod(m, m, n); /* Compute the w-NAF representation of k'. */ l = sizeof(naf); bn_rec_naf(naf, &l, m, EB_WIDTH); if (naf[bn_bits(n)] == 1) { eb_dbl(t[0], p); } l = bn_bits(n); _k = naf + l - 1; eb_copy(q, p); eb_curve_get_cof(n); /* Test if curve has a cofactor bigger than 2. */ if (bn_cmp_dig(n, 2) == RLC_GT) { cof = 1; } else { cof = 0; } trc = fb_trc(eb_curve_get_a()); if (cof) { /* Curves with cofactor > 2, u = sqrt(a), v = Solve(u). */ fb_srt(u, eb_curve_get_a()); fb_slv(v, u); bn_rand(n, RLC_POS, l); for (i = l - 1; i >= 0; i--, _k--) { j = *_k; if (j > 0) { eb_norm(s, q); eb_add(t[j / 2], t[j / 2], s); } if (j < 0) { eb_norm(s, q); eb_sub(t[-j / 2], t[-j / 2], s); } /* T = 1/2(Q). */ eb_hlv(s, q); /* If Tr(x_T) != Tr(a). */ if (fb_trc(s->x) != 0) { /* z = l_t, w = sqrt(l_Q), l_T = l_T + sqrt(l_Q) + v. */ fb_copy(z, s->y); fb_srt(w, q->y); fb_add(s->y, s->y, w); fb_add(s->y, s->y, v); /* z = (z + x_Q + v + sqrt(a)). */ fb_add(z, z, q->x); fb_add(z, z, v); fb_add(z, z, u); /* w = sqrt(w + x_Q + l_Q + sqrt(a)). */ fb_add(w, w, q->x); fb_add(w, w, q->y); fb_add(w, w, u); /* x_T = sqrt(w * z), . */ fb_mul(w, w, z); fb_srt(s->x, w); fb_set_dig(s->z, 1); s->coord = HALVE; } eb_copy(q, s); } } else { for (i = l - 1; i >= 0; i--, _k--) { j = *_k; if (j > 0) { eb_norm(q, q); eb_add(t[j / 2], t[j / 2], q); } if (j < 0) { eb_norm(q, q); eb_sub(t[-j / 2], t[-j / 2], q); } eb_hlv(q, q); } } #if EB_WIDTH == 2 eb_norm(r, t[0]); #else /* Compute Q_i = Q_i + Q_{i+2} for i from 2^{w-1}-3 to 1. */ for (i = (1 << (EB_WIDTH - 1)) - 3; i >= 1; i -= 2) { eb_add(t[i / 2], t[i / 2], t[(i + 2) / 2]); } /* Compute R = Q_1 + 2 * sum_{i != 1}Q_i. */ eb_copy(r, t[1]); for (i = 2; i < (1 << (EB_WIDTH - 2)); i++) { eb_add(r, r, t[i]); } eb_dbl(r, r); eb_add(r, r, t[0]); eb_norm(r, r); #endif /* We may need to fix an error of a 2-torsion point if the curve has a * 4-cofactor. */ if (cof) { eb_hlv(s, r); if (fb_trc(s->x) != trc) { fb_zero(s->x); fb_srt(s->y, eb_curve_get_b()); fb_set_dig(s->z, 1); eb_add(r, r, s); eb_norm(r, r); } } } RLC_CATCH_ANY { RLC_THROW(ERR_CAUGHT); } RLC_FINALLY { /* Free the precomputation table. */ for (i = 0; i < (1 << (EB_WIDTH - 2)); i++) { eb_free(t[i]); } bn_free(n); bn_free(m); eb_free(q); eb_free(s); fb_free(u); fb_free(v); fb_free(w); fb_free(z); } } #endif void eb_mul_gen(eb_t r, const bn_t k) { #ifdef EB_PRECO eb_mul_fix(r, eb_curve_get_tab(), k); #else eb_t g; eb_null(g); RLC_TRY { eb_new(g); eb_curve_get_gen(g); eb_mul(r, g, k); } RLC_CATCH_ANY { RLC_THROW(ERR_CAUGHT); } RLC_FINALLY { eb_free(g); } #endif } void eb_mul_dig(eb_t r, const eb_t p, dig_t k) { eb_t t; if (k == 0 || eb_is_infty(p)) { eb_set_infty(r); return; } eb_null(t); RLC_TRY { eb_new(t); eb_copy(t, p); for (int i = util_bits_dig(k) - 2; i >= 0; i--) { eb_dbl(t, t); if (k & ((dig_t)1 << i)) { eb_add(t, t, p); } } eb_norm(r, t); } RLC_CATCH_ANY { RLC_THROW(ERR_CAUGHT); } RLC_FINALLY { eb_free(t); } }
2a6ff48f43203cdfe85159fd22411b8fad50c8a9
0744dcc5394cebf57ebcba343747af6871b67017
/os/board/rtl8730e/src/component/file_system/vfs2.0/vfs_fatfs_flash.c
b62fd1eb50a8062d31c0a43d36646ea31ce63275
[ "Apache-2.0", "GPL-1.0-or-later", "BSD-3-Clause", "ISC", "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive" ]
permissive
Samsung/TizenRT
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
refs/heads/master
2023-08-31T08:59:33.327998
2023-08-08T06:09:20
2023-08-31T04:38:20
82,517,252
590
719
Apache-2.0
2023-09-14T06:54:49
2017-02-20T04:38:30
C
UTF-8
C
false
false
3,858
c
vfs_fatfs_flash.c
/* * Routines to associate Flash driver with FatFs * * Copyright (c) 2014 Realtek Semiconductor Corp. * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. */ #include "integer.h" #include "stdint.h" #include "vfs.h" #include "vfs_fatfs.h" #include "device_lock.h" #include "osdep_service.h" #include "platform_opts.h" #include "flash_api.h" // Flash interface #define FLASH_BLOCK_SIZE 512 // not passing any #define SECTOR_SIZE_FLASH 512 #define SECTOR_NUM 8 #ifndef FLASH_APP_BASE u32 FLASH_APP_BASE; #endif u32 FLASH_SECTOR_COUNT; flash_t flash; DRESULT interpret_flash_result(int out) { DRESULT res; if (out) { res = RES_OK; } else { res = RES_ERROR; } return res; } DSTATUS FLASH_disk_status(void) { DRESULT res; res = RES_OK; return res; } DSTATUS FLASH_disk_initialize(void) { DRESULT res; res = RES_OK; return res; } DSTATUS FLASH_disk_deinitialize(void) { DRESULT res; res = RES_OK; return res; } /* Read sector(s) --------------------------------------------*/ DRESULT FLASH_disk_read(BYTE *buff, DWORD sector, UINT count) { DRESULT res; char retry_cnt = 0; device_mutex_lock(RT_DEV_LOCK_FLASH); do { res = interpret_flash_result(flash_stream_read(&flash, FLASH_APP_BASE + sector * SECTOR_SIZE_FLASH, count * SECTOR_SIZE_FLASH, (uint8_t *) buff)); if (++retry_cnt >= 3) { break; } } while (res != RES_OK); device_mutex_unlock(RT_DEV_LOCK_FLASH); return res; } /* Write sector(s) --------------------------------------------*/ #if _USE_WRITE == 1 DRESULT FLASH_disk_write(const BYTE *buff, DWORD sector, UINT count) { DRESULT res = RES_OK; u8 sector_index = sector % SECTOR_NUM; u8 *flash_sector_buffer = (u8 *)rtw_malloc(4096); device_mutex_lock(RT_DEV_LOCK_FLASH); //deal with fisrt flash sector flash_stream_read(&flash, FLASH_APP_BASE + (sector / SECTOR_NUM) * 4096, 4096, flash_sector_buffer); rtw_memcpy(flash_sector_buffer + (sector_index * SECTOR_SIZE_FLASH), (BYTE *)buff, ((count + sector_index <= SECTOR_NUM) ? count : (u32)(SECTOR_NUM - sector_index))*SECTOR_SIZE_FLASH); flash_erase_sector(&flash, FLASH_APP_BASE + (sector / SECTOR_NUM) * 4096); flash_stream_write(&flash, FLASH_APP_BASE + (sector / SECTOR_NUM) * 4096, 4096, flash_sector_buffer); rtw_free(flash_sector_buffer); flash_sector_buffer = NULL; device_mutex_unlock(RT_DEV_LOCK_FLASH); return res; } #endif /* IOCTL sector(s) --------------------------------------------*/ #if _USE_IOCTL == 1 DRESULT FLASH_disk_ioctl(BYTE cmd, void *buff) { DRESULT res = RES_ERROR; // FLASH_RESULT result; switch (cmd) { /* Generic command (used by FatFs) */ /* Make sure that no pending write process in the physical drive */ case CTRL_SYNC: /* Flush disk cache (for write functions) */ res = RES_OK; break; case GET_SECTOR_COUNT: /* Get media size (for only f_mkfs()) */ *(DWORD *)buff = FLASH_SECTOR_COUNT; res = RES_OK; break; /* for case _MAX_SS != _MIN_SS */ case GET_SECTOR_SIZE: /* Get sector size (for multiple sector size (_MAX_SS >= 1024)) */ *(WORD *)buff = SECTOR_SIZE_FLASH; //4096 or 2048 or 1024 res = RES_OK; break; case GET_BLOCK_SIZE: /* Get erase block size (for only f_mkfs()) */ *(DWORD *)buff = FLASH_BLOCK_SIZE; res = RES_ERROR; break; case CTRL_ERASE_SECTOR:/* Force erased a block of sectors (for only _USE_ERASE) */ res = RES_OK; break; default: res = RES_PARERR; break; } return res; } #endif ll_diskio_drv FLASH_disk_Driver = { .disk_initialize = FLASH_disk_initialize, .disk_status = FLASH_disk_status, .disk_read = FLASH_disk_read, .disk_deinitialize = FLASH_disk_deinitialize, #if _USE_WRITE == 1 .disk_write = FLASH_disk_write, #endif #if _USE_IOCTL == 1 .disk_ioctl = FLASH_disk_ioctl, #endif .TAG = (unsigned char *)"FLASH" };
e437981aeb32c44105d8bc912ea9859c5fa7140f
d64d35fb4a29b689e494aa5cb322d542449b6c7a
/AppDevPods/AppDevListViewKit/include/ADKTableViewDynamicSizeCell.h
74bee759c1480ca6a947cdce254769f0ea9d8be2
[ "BSD-3-Clause" ]
permissive
yahoo/AppDevKit
07ec20f01160fbb54c31d6b03e25abde274d354c
b07a2f54242037a16de8a5a6debb3eb34a469972
refs/heads/master
2023-08-17T07:25:21.535270
2023-05-10T02:59:36
2023-05-10T02:59:36
60,286,702
1,608
192
NOASSERTION
2023-05-10T02:59:37
2016-06-02T18:11:56
Objective-C
UTF-8
C
false
false
32
h
ADKTableViewDynamicSizeCell.h
../ADKTableViewDynamicSizeCell.h
ec7055913f8c85cdea606d49338768b2f1db5847
5f86fc385c7dcfcb5b166cdea7c8b13057b8bb5f
/tests/mixed_c_cpp/enc/foo.c
6e955d6ce5baa7c48296e74044604ed457895243
[ "MIT" ]
permissive
openenclave/openenclave
54a38e12d9aa73357d9f438a07cd8c07ffe5e6df
cdeb95c1ec163117de409295333b6b2702013e08
refs/heads/master
2023-08-14T16:43:32.049533
2023-07-21T15:58:54
2023-07-21T15:58:54
101,804,230
800
372
MIT
2023-09-12T20:26:02
2017-08-29T20:31:38
C
UTF-8
C
false
false
315
c
foo.c
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #include <stddef.h> #include <stdint.h> #include "mixed_t.h" // This file exists to test that C includes can be successfully included even // when the cmake executable depends on oelibcxx void foo_c(int a) { OE_UNUSED(a); }
77ff99609b613c00384d91e8fd8f074b7b79464d
00caa507194cf76befb4253d90ad0da64893e244
/erpc_c/setup/erpc_server_setup.h
c9216c0d17916ea0b2184200dcd9720711609e17
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
EmbeddedRPC/erpc
26fae8a4ea340c68120a8c5b962713ff903016bc
b3951d834d446b87e6e9a3b47dca71c36f5b37cf
refs/heads/develop
2023-08-18T15:51:52.062159
2023-08-10T11:51:35
2023-08-10T11:51:35
66,159,204
604
196
NOASSERTION
2023-09-06T14:36:55
2016-08-20T17:26:03
C++
UTF-8
C
false
false
4,979
h
erpc_server_setup.h
/* * Copyright (c) 2014-2016, Freescale Semiconductor, Inc. * Copyright 2016-2017 NXP * Copyright 2020 ACRIOS Systems s.r.o. * All rights reserved. * * * SPDX-License-Identifier: BSD-3-Clause */ #ifndef _EMBEDDED_RPC__SERVER_SETUP_H_ #define _EMBEDDED_RPC__SERVER_SETUP_H_ #include "erpc_common.h" #include "erpc_config_internal.h" #include "erpc_mbf_setup.h" #include "erpc_transport_setup.h" #if ERPC_PRE_POST_ACTION #include "erpc_pre_post_action.h" #endif /*! * @addtogroup server_setup * @{ * @file */ //////////////////////////////////////////////////////////////////////////////// // API //////////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> #include <stdint.h> //! @brief Opaque server object type. typedef struct ServerType *erpc_server_t; //! @name Server setup //@{ /*! * @brief This function initializes server. * * This function initializes server with all components necessary for running server. * * @param[in] transport Initiated transport. * @param[in] message_buffer_factory Initiated message buffer factory. * * @return erpc_server_t Pointer to server structure. */ erpc_server_t erpc_server_init(erpc_transport_t transport, erpc_mbf_t message_buffer_factory); /*! * @brief This function de-initializes server. * * This function de-initializes server and all components which it own. * * @param[in] server Pointer to server structure. */ void erpc_server_deinit(erpc_server_t server); /*! * @brief This function adds service to server. * * Services contain implementations of functions called from client to server. * * @param[in] server Pointer to server structure. * @param[in] service Service which contains implementations of functions called from client to server. */ void erpc_add_service_to_server(erpc_server_t server, void *service); /*! * @brief This function removes service from server. * * @param[in] server Pointer to server structure. * @param[in] service Service which contains implementations of functions called from client to server. */ void erpc_remove_service_from_server(erpc_server_t server, void *service); /*! * @brief Can be used to set own crcStart number. * * For example can be used generated crc from erpcgen * which is providing when @crc annotation is used. * Accessed can be through 'extern const uint32_t erpc_generated_crc;' * * @param[in] server Pointer to server structure. * @param[in] crcStart Set start number for crc. */ void erpc_server_set_crc(erpc_server_t server, uint32_t crcStart); //@} //! @name Server control //@{ /*! * @brief This function calls server implementation until it is stopped. * * This is blocking method, where server is trying read (and if it is requested also send) message * until it is stopped. * * @param[in] server Pointer to server structure. * * @return Return one of status from erpc_common.h */ erpc_status_t erpc_server_run(erpc_server_t server); /*! * @brief This function calls server implementation only once. * * This is non-blocking method, where server is trying read (and if it is requested also send) message only once. * * @param[in] server Pointer to server structure. * * @return Return one of status from erpc_common.h */ erpc_status_t erpc_server_poll(erpc_server_t server); /*! * @brief This functions should be used when client is calling quit server. * * This method sets server from On to OFF. When the server returns from its implementation, * erpc_server_deinit() function should be called. * * @param[in] server Pointer to server structure. */ void erpc_server_stop(erpc_server_t server); #if ERPC_MESSAGE_LOGGING /*! * @brief This function adds transport object for logging send/receive messages. * * @param[in] server Pointer to server structure. * @param[in] transport Initiated transport. * * @retval True When transport was successfully added. * @retval False When transport wasn't added. */ bool erpc_server_add_message_logger(erpc_server_t server, erpc_transport_t transport); #endif #if ERPC_PRE_POST_ACTION /*! * @brief This function set callback function executed at the beginning of eRPC call. * * @param[in] server Pointer to server structure. * @param[in] preCB Callback used at the beginning of eRPC call. When NULL and ERPC_PRE_POST_ACTION_DEFAULT * is enabled then default function will be set. */ void erpc_server_add_pre_cb_action(erpc_server_t server, pre_post_action_cb preCB); /*! * @brief This function set callback function executed at the end of eRPC call. * * @param[in] server Pointer to server structure. * @param[in] postCB Callback used at the end of eRPC call. When NULL and ERPC_PRE_POST_ACTION_DEFAULT * is enabled then default function will be set. */ void erpc_server_add_post_cb_action(erpc_server_t server, pre_post_action_cb postCB); #endif //@} #ifdef __cplusplus } #endif /*! @} */ #endif // _EMBEDDED_RPC__SERVER_SETUP_H_
724b1d7008d232dc236daecd4360aac582b7aac5
e5ec9a33aaca93a653df46e7d3c351ece1b4abc5
/ZQCNN/ZQ_CNN_Tensor4D_Interface.h
15c5c012aee7bb4e662abbe28eef2678e74bdb37
[ "MIT" ]
permissive
zuoqing1988/ZQCNN
0b0dbe79acf3094c252e6016dca0dbf37134ce37
9c89e94debaa9a241d2ac0cbc7d32c7bb8436490
refs/heads/master
2022-08-28T08:09:58.698706
2022-08-22T04:20:27
2022-08-22T04:20:27
132,091,868
2,152
487
MIT
2020-10-23T07:37:06
2018-05-04T05:30:54
Objective-C
UTF-8
C
false
false
132
h
ZQ_CNN_Tensor4D_Interface.h
#ifndef _ZQ_CNN_TENSOR_4D_INTERFACE_H_ #define _ZQ_CNN_TENSOR_4D_INTERFACE_H_ #pragma once #include "ZQ_CNN_Tensor4D.h" #endif
87d7d88657501ba9f4935d18ae07687eccd3bf26
f5d5356e629ee8704993136dac098dec2fd228ef
/firmware/components/spi_manager/spi_quad_packet.c
67003284e973d3eb94ef1bacef8af27d833b9104
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
open-dynamic-robot-initiative/master-board
3466929a27485d79f1d5b82d48b4bad95ba0a737
361f44689c1223a00426a96b2f7d1bcaf5b2bed2
refs/heads/master
2023-07-21T08:46:31.783111
2023-06-27T08:49:56
2023-06-27T08:49:56
198,817,879
104
41
BSD-2-Clause
2023-09-11T19:02:19
2019-07-25T11:22:35
C++
UTF-8
C
false
false
497
c
spi_quad_packet.c
#include "spi_quad_packet.h" #include "driver/spi_master.h" #include "quad_crc.h" uint32_t packet_compute_CRC(uint16_t *packet) { return CRC_compute((uint8_t*) packet, SPI_TOTAL_CRC*2); } bool packet_check_CRC(uint16_t *packet) { return (packet_compute_CRC(packet) == packet_get_CRC(packet)); } uint32_t packet_get_CRC(uint16_t *packet) { return SPI_SWAP_DATA_RX(SPI_REG_u16(packet, SPI_TOTAL_CRC), 16) + (((uint32_t) SPI_SWAP_DATA_RX(SPI_REG_u16(packet, SPI_TOTAL_CRC+1), 16)) << 16); }
4d5b6d7e8fa2a5985186eadf90339d0abd29529e
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/xnnpack/src/src/qu8-gavgpool/gen/qu8-gavgpool-7p7x-minmax-fp32-neonv8-c24.c
b5d7882c5b7b79ab1e66152d322c93a608e179ce
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C
false
false
20,823
c
qu8-gavgpool-7p7x-minmax-fp32-neonv8-c24.c
// Auto-generated file. Do not edit! // Template: src/qs8-gavgpool/multipass-neon.c.in // Generator: tools/xngen // // Copyright 2020 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <assert.h> #include <arm_neon.h> #include <xnnpack/gavgpool.h> #include <xnnpack/intrinsics-polyfill.h> #include <xnnpack/math.h> void xnn_qu8_gavgpool_minmax_fp32_ukernel_7p7x__neonv8_c24( size_t rows, size_t channels, const uint8_t* input, size_t input_stride, const uint8_t* zero, int32_t* buffer, uint8_t* output, const union xnn_qu8_avgpool_minmax_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS { assert(rows > 7); assert(channels != 0); const uint8_t* i0 = input; const uint8_t* i1 = (const uint8_t*) ((uintptr_t) i0 + input_stride); const uint8_t* i2 = (const uint8_t*) ((uintptr_t) i1 + input_stride); const uint8_t* i3 = (const uint8_t*) ((uintptr_t) i2 + input_stride); const uint8_t* i4 = (const uint8_t*) ((uintptr_t) i3 + input_stride); const uint8_t* i5 = (const uint8_t*) ((uintptr_t) i4 + input_stride); const uint8_t* i6 = (const uint8_t*) ((uintptr_t) i5 + input_stride); const size_t input_increment = 7 * input_stride - round_up_po2(channels, 8) * sizeof(uint8_t); const int32x4_t vinit_bias = vld1q_dup_s32(&params->fp32_neonv8.init_bias); int32_t* b = buffer; size_t c = channels; for (; c >= 24; c -= 24) { const uint8x8_t vi0x01234567 = vld1_u8(i0); i0 += 8; const uint8x8_t vi0x89ABCDEF = vld1_u8(i0); i0 += 8; const uint8x8_t vi0xGHIJKLMN = vld1_u8(i0); i0 += 8; const uint8x8_t vi1x01234567 = vld1_u8(i1); i1 += 8; const uint8x8_t vi1x89ABCDEF = vld1_u8(i1); i1 += 8; const uint8x8_t vi1xGHIJKLMN = vld1_u8(i1); i1 += 8; const uint8x8_t vi2x01234567 = vld1_u8(i2); i2 += 8; uint16x8_t vsum01234567 = vaddl_u8(vi0x01234567, vi1x01234567); const uint8x8_t vi2x89ABCDEF = vld1_u8(i2); i2 += 8; uint16x8_t vsum89ABCDEF = vaddl_u8(vi0x89ABCDEF, vi1x89ABCDEF); const uint8x8_t vi2xGHIJKLMN = vld1_u8(i2); i2 += 8; uint16x8_t vsumGHIJKLMN = vaddl_u8(vi0xGHIJKLMN, vi1xGHIJKLMN); const uint8x8_t vi3x01234567 = vld1_u8(i3); i3 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi2x01234567); const uint8x8_t vi3x89ABCDEF = vld1_u8(i3); i3 += 8; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi2x89ABCDEF); const uint8x8_t vi3xGHIJKLMN = vld1_u8(i3); i3 += 8; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi2xGHIJKLMN); const uint8x8_t vi4x01234567 = vld1_u8(i4); i4 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi3x01234567); const uint8x8_t vi4x89ABCDEF = vld1_u8(i4); i4 += 8; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi3x89ABCDEF); const uint8x8_t vi4xGHIJKLMN = vld1_u8(i4); i4 += 8; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi3xGHIJKLMN); const uint8x8_t vi5x01234567 = vld1_u8(i5); i5 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi4x01234567); const uint8x8_t vi5x89ABCDEF = vld1_u8(i5); i5 += 8; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi4x89ABCDEF); const uint8x8_t vi5xGHIJKLMN = vld1_u8(i5); i5 += 8; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi4xGHIJKLMN); const uint8x8_t vi6x01234567 = vld1_u8(i6); i6 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi5x01234567); const uint8x8_t vi6x89ABCDEF = vld1_u8(i6); i6 += 8; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi5x89ABCDEF); const uint8x8_t vi6xGHIJKLMN = vld1_u8(i6); i6 += 8; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi5xGHIJKLMN); vsum01234567 = vaddw_u8(vsum01234567, vi6x01234567); vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi6x89ABCDEF); vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi6xGHIJKLMN); const int32x4_t vacc0123 = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vinit_bias), vget_low_u16(vsum01234567))); const int32x4_t vacc4567 = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vinit_bias), vget_high_u16(vsum01234567))); const int32x4_t vacc89AB = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vinit_bias), vget_low_u16(vsum89ABCDEF))); const int32x4_t vaccCDEF = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vinit_bias), vget_high_u16(vsum89ABCDEF))); const int32x4_t vaccGHIJ = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vinit_bias), vget_low_u16(vsumGHIJKLMN))); const int32x4_t vaccKLMN = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vinit_bias), vget_high_u16(vsumGHIJKLMN))); vst1q_s32(b, vacc0123); b += 4; vst1q_s32(b, vacc4567); b += 4; vst1q_s32(b, vacc89AB); b += 4; vst1q_s32(b, vaccCDEF); b += 4; vst1q_s32(b, vaccGHIJ); b += 4; vst1q_s32(b, vaccKLMN); b += 4; } if XNN_UNLIKELY(c != 0) { do { const uint8x8_t vi0x01234567 = vld1_u8(i0); i0 += 8; const uint8x8_t vi1x01234567 = vld1_u8(i1); i1 += 8; const uint8x8_t vi2x01234567 = vld1_u8(i2); i2 += 8; uint16x8_t vsum01234567 = vaddl_u8(vi0x01234567, vi1x01234567); const uint8x8_t vi3x01234567 = vld1_u8(i3); i3 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi2x01234567); const uint8x8_t vi4x01234567 = vld1_u8(i4); i4 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi3x01234567); const uint8x8_t vi5x01234567 = vld1_u8(i5); i5 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi4x01234567); const uint8x8_t vi6x01234567 = vld1_u8(i6); i6 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi5x01234567); vsum01234567 = vaddw_u8(vsum01234567, vi6x01234567); const int32x4_t vacc0123 = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vinit_bias), vget_low_u16(vsum01234567))); const int32x4_t vacc4567 = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vinit_bias), vget_high_u16(vsum01234567))); vst1q_s32(b, vacc0123); b += 4; vst1q_s32(b, vacc4567); b += 4; c = doz(c, 8); } while (c != 0); } for (rows -= 7; rows > 7; rows -= 7) { i0 = (const uint8_t*) ((uintptr_t) i0 + input_increment); i1 = (const uint8_t*) ((uintptr_t) i1 + input_increment); i2 = (const uint8_t*) ((uintptr_t) i2 + input_increment); i3 = (const uint8_t*) ((uintptr_t) i3 + input_increment); i4 = (const uint8_t*) ((uintptr_t) i4 + input_increment); i5 = (const uint8_t*) ((uintptr_t) i5 + input_increment); i6 = (const uint8_t*) ((uintptr_t) i6 + input_increment); int32_t* b = buffer; size_t c = channels; for (; c >= 24; c -= 24) { const uint8x8_t vi0x01234567 = vld1_u8(i0); i0 += 8; const uint8x8_t vi0x89ABCDEF = vld1_u8(i0); i0 += 8; const uint8x8_t vi0xGHIJKLMN = vld1_u8(i0); i0 += 8; const uint8x8_t vi1x01234567 = vld1_u8(i1); i1 += 8; const uint8x8_t vi1x89ABCDEF = vld1_u8(i1); i1 += 8; const uint8x8_t vi1xGHIJKLMN = vld1_u8(i1); i1 += 8; const uint8x8_t vi2x01234567 = vld1_u8(i2); i2 += 8; uint16x8_t vsum01234567 = vaddl_u8(vi0x01234567, vi1x01234567); const uint8x8_t vi2x89ABCDEF = vld1_u8(i2); i2 += 8; uint16x8_t vsum89ABCDEF = vaddl_u8(vi0x89ABCDEF, vi1x89ABCDEF); const uint8x8_t vi2xGHIJKLMN = vld1_u8(i2); i2 += 8; uint16x8_t vsumGHIJKLMN = vaddl_u8(vi0xGHIJKLMN, vi1xGHIJKLMN); const uint8x8_t vi3x01234567 = vld1_u8(i3); i3 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi2x01234567); const uint8x8_t vi3x89ABCDEF = vld1_u8(i3); i3 += 8; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi2x89ABCDEF); const uint8x8_t vi3xGHIJKLMN = vld1_u8(i3); i3 += 8; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi2xGHIJKLMN); const uint8x8_t vi4x01234567 = vld1_u8(i4); i4 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi3x01234567); const uint8x8_t vi4x89ABCDEF = vld1_u8(i4); i4 += 8; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi3x89ABCDEF); const uint8x8_t vi4xGHIJKLMN = vld1_u8(i4); i4 += 8; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi3xGHIJKLMN); const uint8x8_t vi5x01234567 = vld1_u8(i5); i5 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi4x01234567); const uint8x8_t vi5x89ABCDEF = vld1_u8(i5); i5 += 8; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi4x89ABCDEF); const uint8x8_t vi5xGHIJKLMN = vld1_u8(i5); i5 += 8; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi4xGHIJKLMN); const uint8x8_t vi6x01234567 = vld1_u8(i6); i6 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi5x01234567); const uint8x8_t vi6x89ABCDEF = vld1_u8(i6); i6 += 8; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi5x89ABCDEF); const uint8x8_t vi6xGHIJKLMN = vld1_u8(i6); i6 += 8; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi5xGHIJKLMN); int32x4_t vacc0123 = vld1q_s32(b); int32x4_t vacc4567 = vld1q_s32(b + 4); vsum01234567 = vaddw_u8(vsum01234567, vi6x01234567); int32x4_t vacc89AB = vld1q_s32(b + 8); int32x4_t vaccCDEF = vld1q_s32(b + 12); vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi6x89ABCDEF); int32x4_t vaccGHIJ = vld1q_s32(b + 16); int32x4_t vaccKLMN = vld1q_s32(b + 20); vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi6xGHIJKLMN); vacc0123 = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vacc0123), vget_low_u16(vsum01234567))); vacc4567 = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vacc4567), vget_high_u16(vsum01234567))); vacc89AB = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vacc89AB), vget_low_u16(vsum89ABCDEF))); vaccCDEF = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vaccCDEF), vget_high_u16(vsum89ABCDEF))); vaccGHIJ = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vaccGHIJ), vget_low_u16(vsumGHIJKLMN))); vaccKLMN = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vaccKLMN), vget_high_u16(vsumGHIJKLMN))); vst1q_s32(b, vacc0123); b += 4; vst1q_s32(b, vacc4567); b += 4; vst1q_s32(b, vacc89AB); b += 4; vst1q_s32(b, vaccCDEF); b += 4; vst1q_s32(b, vaccGHIJ); b += 4; vst1q_s32(b, vaccKLMN); b += 4; } if XNN_UNLIKELY(c != 0) { do { const uint8x8_t vi0x01234567 = vld1_u8(i0); i0 += 8; const uint8x8_t vi1x01234567 = vld1_u8(i1); i1 += 8; const uint8x8_t vi2x01234567 = vld1_u8(i2); i2 += 8; uint16x8_t vsum01234567 = vaddl_u8(vi0x01234567, vi1x01234567); const uint8x8_t vi3x01234567 = vld1_u8(i3); i3 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi2x01234567); const uint8x8_t vi4x01234567 = vld1_u8(i4); i4 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi3x01234567); const uint8x8_t vi5x01234567 = vld1_u8(i5); i5 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi4x01234567); const uint8x8_t vi6x01234567 = vld1_u8(i6); i6 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi5x01234567); int32x4_t vacc0123 = vld1q_s32(b); int32x4_t vacc4567 = vld1q_s32(b + 4); vsum01234567 = vaddw_u8(vsum01234567, vi6x01234567); vacc0123 = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vacc0123), vget_low_u16(vsum01234567))); vacc4567 = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vacc4567), vget_high_u16(vsum01234567))); vst1q_s32(b, vacc0123); b += 4; vst1q_s32(b, vacc4567); b += 4; c = doz(c, 8); } while (c != 0); } } i0 = (const uint8_t*) ((uintptr_t) i0 + input_increment); i1 = (const uint8_t*) ((uintptr_t) i1 + input_increment); if XNN_UNPREDICTABLE(rows < 2) { i1 = zero; } i2 = (const uint8_t*) ((uintptr_t) i2 + input_increment); if XNN_UNPREDICTABLE(rows <= 2) { i2 = zero; } i3 = (const uint8_t*) ((uintptr_t) i3 + input_increment); if XNN_UNPREDICTABLE(rows < 4) { i3 = zero; } i4 = (const uint8_t*) ((uintptr_t) i4 + input_increment); if XNN_UNPREDICTABLE(rows <= 4) { i4 = zero; } i5 = (const uint8_t*) ((uintptr_t) i5 + input_increment); if XNN_UNPREDICTABLE(rows < 6) { i5 = zero; } i6 = (const uint8_t*) ((uintptr_t) i6 + input_increment); if XNN_UNPREDICTABLE(rows <= 6) { i6 = zero; } const float32x4_t vscale = vld1q_dup_f32(&params->fp32_neonv8.scale); const int16x8_t voutput_zero_point = vld1q_dup_s16(&params->fp32_neonv8.output_zero_point); const uint8x16_t voutput_min = vld1q_dup_u8(&params->fp32_neonv8.output_min); const uint8x16_t voutput_max = vld1q_dup_u8(&params->fp32_neonv8.output_max); for (; channels >= 24; channels -= 24) { const uint8x8_t vi0x01234567 = vld1_u8(i0); i0 += 8; const uint8x8_t vi0x89ABCDEF = vld1_u8(i0); i0 += 8; const uint8x8_t vi0xGHIJKLMN = vld1_u8(i0); i0 += 8; const uint8x8_t vi1x01234567 = vld1_u8(i1); i1 += 8; const uint8x8_t vi1x89ABCDEF = vld1_u8(i1); i1 += 8; const uint8x8_t vi1xGHIJKLMN = vld1_u8(i1); i1 += 8; const uint8x8_t vi2x01234567 = vld1_u8(i2); i2 += 8; uint16x8_t vsum01234567 = vaddl_u8(vi0x01234567, vi1x01234567); const uint8x8_t vi2x89ABCDEF = vld1_u8(i2); i2 += 8; uint16x8_t vsum89ABCDEF = vaddl_u8(vi0x89ABCDEF, vi1x89ABCDEF); const uint8x8_t vi2xGHIJKLMN = vld1_u8(i2); i2 += 8; uint16x8_t vsumGHIJKLMN = vaddl_u8(vi0xGHIJKLMN, vi1xGHIJKLMN); const uint8x8_t vi3x01234567 = vld1_u8(i3); i3 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi2x01234567); const uint8x8_t vi3x89ABCDEF = vld1_u8(i3); i3 += 8; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi2x89ABCDEF); const uint8x8_t vi3xGHIJKLMN = vld1_u8(i3); i3 += 8; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi2xGHIJKLMN); const uint8x8_t vi4x01234567 = vld1_u8(i4); i4 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi3x01234567); const uint8x8_t vi4x89ABCDEF = vld1_u8(i4); i4 += 8; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi3x89ABCDEF); const uint8x8_t vi4xGHIJKLMN = vld1_u8(i4); i4 += 8; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi3xGHIJKLMN); const uint8x8_t vi5x01234567 = vld1_u8(i5); i5 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi4x01234567); const uint8x8_t vi5x89ABCDEF = vld1_u8(i5); i5 += 8; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi4x89ABCDEF); const uint8x8_t vi5xGHIJKLMN = vld1_u8(i5); i5 += 8; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi4xGHIJKLMN); const uint8x8_t vi6x01234567 = vld1_u8(i6); i6 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi5x01234567); const uint8x8_t vi6x89ABCDEF = vld1_u8(i6); i6 += 8; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi5x89ABCDEF); const uint8x8_t vi6xGHIJKLMN = vld1_u8(i6); i6 += 8; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi5xGHIJKLMN); int32x4_t vacc0123 = vld1q_s32(buffer); buffer += 4; int32x4_t vacc4567 = vld1q_s32(buffer); buffer += 4; vsum01234567 = vaddw_u8(vsum01234567, vi6x01234567); int32x4_t vacc89AB = vld1q_s32(buffer); buffer += 4; int32x4_t vaccCDEF = vld1q_s32(buffer); buffer += 4; vsum89ABCDEF = vaddw_u8(vsum89ABCDEF, vi6x89ABCDEF); int32x4_t vaccGHIJ = vld1q_s32(buffer); buffer += 4; int32x4_t vaccKLMN = vld1q_s32(buffer); buffer += 4; vsumGHIJKLMN = vaddw_u8(vsumGHIJKLMN, vi6xGHIJKLMN); vacc0123 = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vacc0123), vget_low_u16(vsum01234567))); vacc4567 = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vacc4567), vget_high_u16(vsum01234567))); vacc89AB = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vacc89AB), vget_low_u16(vsum89ABCDEF))); vaccCDEF = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vaccCDEF), vget_high_u16(vsum89ABCDEF))); vaccGHIJ = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vaccGHIJ), vget_low_u16(vsumGHIJKLMN))); vaccKLMN = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vaccKLMN), vget_high_u16(vsumGHIJKLMN))); float32x4_t vfpacc0123 = vcvtq_f32_s32(vacc0123); float32x4_t vfpacc4567 = vcvtq_f32_s32(vacc4567); float32x4_t vfpacc89AB = vcvtq_f32_s32(vacc89AB); float32x4_t vfpaccCDEF = vcvtq_f32_s32(vaccCDEF); float32x4_t vfpaccGHIJ = vcvtq_f32_s32(vaccGHIJ); float32x4_t vfpaccKLMN = vcvtq_f32_s32(vaccKLMN); vfpacc0123 = vmulq_f32(vfpacc0123, vscale); vfpacc4567 = vmulq_f32(vfpacc4567, vscale); vfpacc89AB = vmulq_f32(vfpacc89AB, vscale); vfpaccCDEF = vmulq_f32(vfpaccCDEF, vscale); vfpaccGHIJ = vmulq_f32(vfpaccGHIJ, vscale); vfpaccKLMN = vmulq_f32(vfpaccKLMN, vscale); vacc0123 = vcvtnq_s32_f32(vfpacc0123); vacc4567 = vcvtnq_s32_f32(vfpacc4567); vacc89AB = vcvtnq_s32_f32(vfpacc89AB); vaccCDEF = vcvtnq_s32_f32(vfpaccCDEF); vaccGHIJ = vcvtnq_s32_f32(vfpaccGHIJ); vaccKLMN = vcvtnq_s32_f32(vfpaccKLMN); #if XNN_ARCH_ARM64 int16x8_t vacc01234567 = vqmovn_high_s32(vqmovn_s32(vacc0123), vacc4567); int16x8_t vacc89ABCDEF = vqmovn_high_s32(vqmovn_s32(vacc89AB), vaccCDEF); int16x8_t vaccGHIJKLMN = vqmovn_high_s32(vqmovn_s32(vaccGHIJ), vaccKLMN); #else // !XNN_ARCH_ARM64 int16x8_t vacc01234567 = vcombine_s16(vqmovn_s32(vacc0123), vqmovn_s32(vacc4567)); int16x8_t vacc89ABCDEF = vcombine_s16(vqmovn_s32(vacc89AB), vqmovn_s32(vaccCDEF)); int16x8_t vaccGHIJKLMN = vcombine_s16(vqmovn_s32(vaccGHIJ), vqmovn_s32(vaccKLMN)); #endif // !XNN_ARCH_ARM64 vacc01234567 = vqaddq_s16(vacc01234567, voutput_zero_point); vacc89ABCDEF = vqaddq_s16(vacc89ABCDEF, voutput_zero_point); vaccGHIJKLMN = vqaddq_s16(vaccGHIJKLMN, voutput_zero_point); #if XNN_ARCH_ARM64 uint8x16_t vout0123456789ABCDEF = vqmovun_high_s16(vqmovun_s16(vacc01234567), vacc89ABCDEF); uint8x8_t voutGHIJKLMN = vqmovun_s16(vaccGHIJKLMN); #else // !XNN_ARCH_ARM64 uint8x16_t vout0123456789ABCDEF = vcombine_u8(vqmovun_s16(vacc01234567), vqmovun_s16(vacc89ABCDEF)); uint8x8_t voutGHIJKLMN = vqmovun_s16(vaccGHIJKLMN); #endif // !XNN_ARCH_ARM64 vout0123456789ABCDEF = vmaxq_u8(vout0123456789ABCDEF, voutput_min); voutGHIJKLMN = vmax_u8(voutGHIJKLMN, vget_low_u8(voutput_min)); vout0123456789ABCDEF = vminq_u8(vout0123456789ABCDEF, voutput_max); voutGHIJKLMN = vmin_u8(voutGHIJKLMN, vget_low_u8(voutput_max)); vst1q_u8(output, vout0123456789ABCDEF); output += 16; vst1_u8(output, voutGHIJKLMN); output += 8; } if XNN_UNLIKELY(channels != 0) { do { const uint8x8_t vi0x01234567 = vld1_u8(i0); i0 += 8; const uint8x8_t vi1x01234567 = vld1_u8(i1); i1 += 8; const uint8x8_t vi2x01234567 = vld1_u8(i2); i2 += 8; uint16x8_t vsum01234567 = vaddl_u8(vi0x01234567, vi1x01234567); const uint8x8_t vi3x01234567 = vld1_u8(i3); i3 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi2x01234567); const uint8x8_t vi4x01234567 = vld1_u8(i4); i4 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi3x01234567); const uint8x8_t vi5x01234567 = vld1_u8(i5); i5 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi4x01234567); const uint8x8_t vi6x01234567 = vld1_u8(i6); i6 += 8; vsum01234567 = vaddw_u8(vsum01234567, vi5x01234567); int32x4_t vacc0123 = vld1q_s32(buffer); buffer += 4; int32x4_t vacc4567 = vld1q_s32(buffer); buffer += 4; vsum01234567 = vaddw_u8(vsum01234567, vi6x01234567); vacc0123 = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vacc0123), vget_low_u16(vsum01234567))); vacc4567 = vreinterpretq_s32_u32(vaddw_u16(vreinterpretq_u32_s32(vacc4567), vget_high_u16(vsum01234567))); float32x4_t vfpacc0123 = vcvtq_f32_s32(vacc0123); float32x4_t vfpacc4567 = vcvtq_f32_s32(vacc4567); vfpacc0123 = vmulq_f32(vfpacc0123, vscale); vfpacc4567 = vmulq_f32(vfpacc4567, vscale); vacc0123 = vcvtnq_s32_f32(vfpacc0123); vacc4567 = vcvtnq_s32_f32(vfpacc4567); #if XNN_ARCH_ARM64 int16x8_t vacc01234567 = vqmovn_high_s32(vqmovn_s32(vacc0123), vacc4567); #else int16x8_t vacc01234567 = vcombine_s16(vqmovn_s32(vacc0123), vqmovn_s32(vacc4567)); #endif vacc01234567 = vqaddq_s16(vacc01234567, voutput_zero_point); uint8x8_t vout01234567 = vqmovun_s16(vacc01234567); vout01234567 = vmax_u8(vout01234567, vget_low_u8(voutput_min)); vout01234567 = vmin_u8(vout01234567, vget_low_u8(voutput_max)); if XNN_LIKELY(channels >= 8) { vst1_u8(output, vout01234567); output += 8; channels -= 8; } else { if (channels & 4) { vst1_lane_u32((void*) output, vreinterpret_u32_u8(vout01234567), 0); output += 4; vout01234567 = vext_u8(vout01234567, vout01234567, 4); } if (channels & 2) { vst1_lane_u16((void*) output, vreinterpret_u16_u8(vout01234567), 0); output += 2; vout01234567 = vext_u8(vout01234567, vout01234567, 2); } if (channels & 1) { vst1_lane_u8(output, vout01234567, 0); output += 1; } channels = 0; } } while (channels != 0); } }
5e7af395eb5e5d61ace310fc0609b3a00a71c489
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
/mail/safecat/patches/patch-tryulong32.c
1d9d40288dfbc932153dfcf365afde03b15f8fdf
[]
no_license
NetBSD/pkgsrc
a0732c023519650ef821ab89c23ab6ab59e25bdb
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
refs/heads/trunk
2023-09-01T07:40:12.138283
2023-09-01T05:25:19
2023-09-01T05:25:19
88,439,572
321
138
null
2023-07-12T22:34:14
2017-04-16T20:04:15
null
UTF-8
C
false
false
457
c
patch-tryulong32.c
$NetBSD: patch-tryulong32.c,v 1.1 2017/07/27 02:20:30 schmonz Exp $ Support arm. --- tryulong32.c.orig 2000-02-29 04:10:12.000000000 +0000 +++ tryulong32.c @@ -1,5 +1,8 @@ void main() { +#ifdef __arm__ + _exit(0); +#else unsigned long u; u = 1; u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; @@ -8,4 +11,5 @@ void main() u += u; u += u; u += u; u += u; u += u; u += u; u += u; u += u; if (!u) _exit(0); _exit(1); +#endif }
c56179e45cf3b435ab5cfa21ab3abd2ee72de09b
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/ffmpeg/libavcodec/alpha/blockdsp_alpha.c
c6f09646077ff6973ca6b709ae6f951703a67da1
[ "LGPL-2.1-only", "LGPL-3.0-only", "LGPL-2.0-or-later", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.1-or-later", "GPL-3.0-or-later", "LGPL-3.0-or-later", "IJG", "LicenseRef-scancode-other-permissive", "MIT", "GPL-2.0-or-later", "Apache-2.0", "GPL-3.0-only", "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C
false
false
1,398
c
blockdsp_alpha.c
/* * Alpha optimised block operations * Copyright (c) 2002 Falk Hueffner <falk@debian.org> * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdint.h> #include "libavutil/attributes.h" #include "libavcodec/blockdsp.h" #include "asm.h" static void clear_blocks_axp(int16_t *blocks) { uint64_t *p = (uint64_t *) blocks; int n = sizeof(int16_t) * 6 * 64; do { p[0] = 0; p[1] = 0; p[2] = 0; p[3] = 0; p[4] = 0; p[5] = 0; p[6] = 0; p[7] = 0; p += 8; n -= 8 * 8; } while (n); } av_cold void ff_blockdsp_init_alpha(BlockDSPContext *c) { c->clear_blocks = clear_blocks_axp; }
ebb6cd27438346b6d641d69b1480b1d6f0de8c5b
99bdb3251fecee538e0630f15f6574054dfc1468
/bsp/Infineon/libraries/IFX_PSOC6_HAL/mtb-hal-cat1/include_pvt/cyhal_system_impl.h
6c199373a7dc12f95cfe973560a0ea727e73e8aa
[ "Zlib", "LicenseRef-scancode-proprietary-license", "MIT", "BSD-3-Clause", "X11", "BSD-4-Clause-UC", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "GPL-1.0-or-later", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
1,956
h
cyhal_system_impl.h
/***************************************************************************//** * \file cyhal_system_impl.h * * \brief * Provides a PSoCâ„¢ Specific interface for interacting with the Infineon power * management and system clock configuration. This interface abstracts out the * chip specific details. If any chip specific functionality is necessary, or * performance is critical the low level functions can be used directly. * ******************************************************************************** * \copyright * Copyright 2018-2022 Cypress Semiconductor Corporation (an Infineon company) or * an affiliate of Cypress Semiconductor Corporation * * SPDX-License-Identifier: Apache-2.0 * * 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 "cyhal_system.h" #if defined(CY_IP_MXS40SRSS) || defined(CY_IP_S8SRSSLT) || defined(CY_IP_MXS28SRSS) || defined(CY_IP_MXS40SSRSS) || defined(CY_IP_MXS22SRSS) #define cyhal_system_critical_section_enter() Cy_SysLib_EnterCriticalSection() #define cyhal_system_critical_section_exit(x) Cy_SysLib_ExitCriticalSection(x) #define cyhal_system_delay_us(microseconds) Cy_SysLib_DelayUs(microseconds) #define cyhal_system_clear_reset_reason() Cy_SysLib_ClearResetReason() #endif /* defined(CY_IP_MXS40SRSS) || defined(CY_IP_S8SRSSLT) || defined(CY_IP_MXS28SRSS) || defined(CY_IP_MXS40SSRSS) */
a3a1a57edbd0287c73103229b78c86ff1e11e455
779cd3de885ad7c23e2f625684a55e1d1b27730a
/include/insert_box_into_box.h
49bced2d1b9cb673ca68dd3df981d39d2e7582fd
[]
no_license
alecjacobson/computer-graphics-bounding-volume-hierarchy
fa0daf9d38651f4ccf5f680ef9b2283e0e481ee0
b5e801ea101fcba5a068cd564a905c11e6bc7635
refs/heads/master
2022-02-14T05:03:23.086216
2022-02-01T22:54:37
2022-02-01T22:54:37
147,458,320
103
44
null
2022-02-02T15:56:05
2018-09-05T04:11:20
C++
UTF-8
C
false
false
384
h
insert_box_into_box.h
#ifndef INSERT_BOX_INTO_BOX_H #define INSERT_BOX_INTO_BOX_H #include "BoundingBox.h" #include <Eigen/Core> // Grow a box `B` by inserting a box `A`. // // Inputs: // A bounding box to be inserted // B bounding box to be grown // Outputs: // B bounding box grown to include original contents and A void insert_box_into_box( const BoundingBox & A, BoundingBox & B); #endif
e11a50ff53dd768861d6e7f2ecffe9797cec6ace
b4c2b8dc89417e966a67a433267ebb9c156dbff4
/src/8_Sound.h
b66b9fcb1bc74b6302d3201aa63380ce522d4cf1
[]
no_license
TheDIYGuy999/Rc_Engine_Sound_ESP32
92134030dbc047627310d54ccf1fd34fb3cad791
eeeb47964861b66f8e1db34bffe35657846d8b20
refs/heads/master
2023-08-31T00:17:03.698027
2023-05-04T19:46:51
2023-05-04T19:46:51
225,658,413
230
105
null
2023-08-26T14:38:39
2019-12-03T15:51:13
C
UTF-8
C
false
false
1,006
h
8_Sound.h
#include <Arduino.h> /* General SOUND SETTINGS ************************************************************************************************ * * Most sound settings are done in the vehicle configuration files in the /vehicles/ directory. * */ // #define NO_SIREN // siren sound is not played, if defined // #define NO_INDICATOR_SOUND // If you don't want the indicator "tick - tack" sound // Volume adjustment // const uint8_t numberOfVolumeSteps = 3; // The mumber of volume steps below // const uint8_t masterVolumePercentage[] = {100, 66, 44}; // loud, medium, silent (more than 100% may cause distortions) const uint8_t numberOfVolumeSteps = 4; // The mumber of volume steps below const uint8_t masterVolumePercentage[] = {100, 66, 44, 0}; // loud, medium, silent, no sound (more than 100% may cause distortions) // Crawler mode const uint8_t masterVolumeCrawlerThreshold = 44; // If master volume is <= this threshold, crawler mode (without virtual inertia) is active
5cd8214bdd48248640effcb1bb5264d81571fa66
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/mips/atheros/dev/ehci_arbus.c
3f4e6d56e30584f9ed6ece67a076fdf1a64143ad
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
4,951
c
ehci_arbus.c
/* $NetBSD: ehci_arbus.c,v 1.10 2021/08/07 16:18:59 thorpej Exp $ */ /*- * Copyright (c) 2011 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Matt Thomas of 3am Software Foundry. * * 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. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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 <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: ehci_arbus.c,v 1.10 2021/08/07 16:18:59 thorpej Exp $"); #include "locators.h" #include <sys/param.h> #include <sys/bus.h> #include <sys/device.h> #include <sys/systm.h> #include <mips/locore.h> #include <mips/atheros/include/ar9344reg.h> #include <mips/atheros/include/arbusvar.h> #include <dev/usb/usb.h> #include <dev/usb/usbdi.h> #include <dev/usb/usbdivar.h> #include <dev/usb/usb_mem.h> #include <dev/usb/ehcireg.h> #include <dev/usb/ehcivar.h> /* * This is relative to the start of the unreserved registers in USB controller * block and not the full USB block which would be 0x1a8. */ #define ARBUS_USBMODE 0xa8 /* USB mode */ #define USBMODE_CM __BITS(0,1) /* Controller Mode */ #define USBMODE_CM_IDLE __SHIFTIN(0,USBMODE_CM) /* Idle (both) */ #define USBMODE_CM_DEVICE __SHIFTIN(2,USBMODE_CM) /* Device Controller */ #define USBMODE_CM_HOST __SHIFTIN(3,USBMODE_CM) /* Host Controller */ static int ehci_arbus_match(device_t, cfdata_t, void *); static void ehci_arbus_attach(device_t, device_t, void *); CFATTACH_DECL_NEW(ehci_arbus, sizeof (ehci_softc_t), ehci_arbus_match, ehci_arbus_attach, NULL, NULL); static void ehci_arbus_init(struct ehci_softc *); int ehci_arbus_match(device_t parent, cfdata_t cf, void *aux) { struct arbus_attach_args *aa = aux; if (strcmp(aa->aa_name, cf->cf_name) != 0) return 0; if (badaddr((void *)MIPS_PHYS_TO_KSEG1(aa->aa_addr), 4)) return 0; return 1; /* XXX */ } void ehci_arbus_attach(device_t parent, device_t self, void *aux) { ehci_softc_t *sc = device_private(self); struct arbus_attach_args * const aa = aux; void *ih = NULL; int error; sc->iot = aa->aa_bst_le; sc->sc_size = aa->aa_size; //sc->sc_bus.ub_hcpriv = sc; sc->sc_bus.ub_dmatag = aa->aa_dmat; sc->sc_bus.ub_revision = USBREV_1_0; sc->sc_flags |= EHCIF_ETTF; sc->sc_vendor_init = ehci_arbus_init; error = bus_space_map(aa->aa_bst, aa->aa_addr, aa->aa_size, 0, &sc->ioh); if (error) { aprint_error(": failed to map registers: %d\n", error); return; } /* The recommended value is 0x20 for both ports and the host */ REGVAL(AR9344_USB_CONFIG_BASE) = 0x20c00; /* magic */ DELAY(1000); /* get offset to operational regs */ uint32_t r = bus_space_read_4(aa->aa_bst, sc->ioh, 0); if (r != 0x40) { aprint_error(": error: CAPLENGTH (%#x) != 0x40\n", sc->sc_offs); return; } sc->sc_offs = EREAD1(sc, EHCI_CAPLENGTH); aprint_normal("\n"); /* Disable EHCI interrupts */ EOWRITE4(sc, EHCI_USBINTR, 0); /* establish interrupt */ ih = arbus_intr_establish(aa->aa_cirq, aa->aa_mirq, ehci_intr, sc); if (ih == NULL) panic("%s: couldn't establish interrupt", device_xname(self)); /* * There are no companion controllers */ sc->sc_ncomp = 0; error = ehci_init(sc); if (error) { aprint_error("%s: init failed, error=%d\n", device_xname(self), error); if (ih != NULL) arbus_intr_disestablish(ih); return; } /* Attach USB device */ sc->sc_child = config_found(self, &sc->sc_bus, usbctlprint, CFARGS_NONE); } static void ehci_arbus_init(struct ehci_softc *sc) { /* Set host mode */ uint32_t old = bus_space_read_4(sc->iot, sc->ioh, ARBUS_USBMODE); uint32_t reg = old; reg &= ~USBMODE_CM; reg |= USBMODE_CM_HOST; if (reg != old) bus_space_write_4(sc->iot, sc->ioh, ARBUS_USBMODE, reg); }
d9d0b0553aff6c3d89fb0fcf0742519d7214d08d
baf824f8819f90928e11480d0eae89efb60341a1
/ports/nxp_rt1050_60/omv/framebuffer.c
a67085660d42cb5c6aa83abeb8ff35e91a5bee8b
[ "MIT", "GPL-1.0-or-later" ]
permissive
RockySong/micropython-rocky
549770723ba92cb311c468880ead0ffdd4fa8fe5
2d728f414bf8d041ca609e00448850759aade3cd
refs/heads/omv_initial_integrate
2021-05-12T12:20:18.404341
2021-01-15T01:15:48
2021-01-15T01:15:48
117,408,452
198
90
MIT
2020-08-25T03:31:32
2018-01-14T06:40:36
C
UTF-8
C
false
false
5,702
c
framebuffer.c
/* * This file is part of the OpenMV project. * Copyright (c) 2013/2014 Ibrahim Abdelkader <i.abdalkader@gmail.com> * This work is licensed under the MIT license, see the file LICENSE for details. * * Framebuffer stuff. * */ #include "imlib.h" #include "omv_boardconfig.h" #include "framebuffer.h" #ifdef __CC_ARM __WEAK bool jpeg_compress(image_t *src, image_t *dst, int quality, bool realloc) {return 1;} extern unsigned int Image$$OMV_MAIN_FB$$Base; #define JPEG_BUF __attribute__((section(".jpeg_buf"))) JPEG_BUF uint32_t s_jpegBuf[OMV_JPEG_BUF_SIZE / 4]; framebuffer_t *fb_framebuffer = (framebuffer_t*) &Image$$OMV_MAIN_FB$$Base; jpegbuffer_t *jpeg_fb_framebuffer = (jpegbuffer_t*) &s_jpegBuf; #else extern char _fb_base; framebuffer_t *fb_framebuffer = (framebuffer_t *) &_fb_base; extern char _jpeg_buf; jpegbuffer_t *jpeg_fb_framebuffer = (jpegbuffer_t *) &_jpeg_buf; #endif int encode_for_ide_new_size(image_t *img) { return (((img->bpp * 8) + 5) / 6) + 2; } void encode_for_ide(uint8_t *ptr, image_t *img) { *ptr++ = 0xFE; for(int i = 0, j = (img->bpp / 3) * 3; i < j; i += 3) { int x = 0; x |= img->data[i + 0] << 0; x |= img->data[i + 1] << 8; x |= img->data[i + 2] << 16; *ptr++ = 0x80 | ((x >> 0) & 0x3F); *ptr++ = 0x80 | ((x >> 6) & 0x3F); *ptr++ = 0x80 | ((x >> 12) & 0x3F); *ptr++ = 0x80 | ((x >> 18) & 0x3F); } if((img->bpp % 3) == 2) { // 2 bytes -> 16-bits -> 24-bits sent int x = 0; x |= img->data[img->bpp - 2] << 0; x |= img->data[img->bpp - 1] << 8; *ptr++ = 0x80 | ((x >> 0) & 0x3F); *ptr++ = 0x80 | ((x >> 6) & 0x3F); *ptr++ = 0x80 | ((x >> 12) & 0x3F); } if((img->bpp % 3) == 1) { // 1 byte -> 8-bits -> 16-bits sent int x = 0; x |= img->data[img->bpp - 1] << 0; *ptr++ = 0x80 | ((x >> 0) & 0x3F); *ptr++ = 0x80 | ((x >> 6) & 0x3F); } *ptr++ = 0xFE; } uint32_t fb_buffer_size() { switch (MAIN_FB()->bpp) { case IMAGE_BPP_BINARY: { return ((MAIN_FB()->w + UINT32_T_MASK) >> UINT32_T_SHIFT) * MAIN_FB()->h; } case IMAGE_BPP_GRAYSCALE: { return (MAIN_FB()->w * MAIN_FB()->h) * sizeof(uint8_t); } case IMAGE_BPP_RGB565: { return (MAIN_FB()->w * MAIN_FB()->h) * sizeof(uint16_t); } case IMAGE_BPP_BAYER: { return MAIN_FB()->w * MAIN_FB()->h; } default: { // JPEG return MAIN_FB()->bpp; } } } void fb_update_jpeg_buffer() { static int overflow_count = 0; if ((MAIN_FB()->bpp > 3) && JPEG_FB()->enabled && JPEG_FB()->size == 0) { bool does_not_fit = false; // Lock FB if (mutex_try_lock(&JPEG_FB()->lock, MUTEX_TID_OMV)) { if((OMV_JPEG_BUF_SIZE-64) < MAIN_FB()->bpp) { // image won't fit. so don't copy. JPEG_FB()->w = 0; JPEG_FB()->h = 0; JPEG_FB()->size = 0; does_not_fit = true; } else { memcpy(JPEG_FB()->pixels, MAIN_FB()->pixels, MAIN_FB()->bpp); JPEG_FB()->w = MAIN_FB()->w; JPEG_FB()->h = MAIN_FB()->h; JPEG_FB()->size = MAIN_FB()->bpp; } // Unlock the framebuffer mutex mutex_unlock(&JPEG_FB()->lock, MUTEX_TID_OMV); } if (does_not_fit) { image_t out = { .w=MAIN_FB()->w, .h=MAIN_FB()->h, .bpp=MAIN_FB()->bpp, .data=MAIN_FB()->pixels }; int new_size = encode_for_ide_new_size(&out); fb_alloc_mark(); uint8_t *temp = fb_alloc(new_size, FB_ALLOC_NO_HINT); encode_for_ide(temp, &out); // (MP_PYTHON_PRINTER)->print_strn((MP_PYTHON_PRINTER)->data, (const char *) temp, new_size); fb_alloc_free_till_mark(); } } else if ((MAIN_FB()->bpp >= 0) && JPEG_FB()->enabled && JPEG_FB()->size == 0) { // Lock FB if (mutex_try_lock(&JPEG_FB()->lock, MUTEX_TID_OMV)) { // Set JPEG src and dst images. image_t src = {.w=MAIN_FB()->w, .h=MAIN_FB()->h, .bpp=MAIN_FB()->bpp, .pixels=MAIN_FB()->pixels}; image_t dst = {.w=MAIN_FB()->w, .h=MAIN_FB()->h, .bpp=(OMV_JPEG_BUF_SIZE-64), .pixels=JPEG_FB()->pixels}; // Note: lower quality saves USB bandwidth and results in a faster IDE FPS. bool overflow = jpeg_compress(&src, &dst, JPEG_FB()->quality, false); if (overflow == true) { // JPEG buffer overflowed, reduce JPEG quality for the next frame // and skip the current frame. The IDE doesn't receive this frame. if (JPEG_FB()->quality > 1) { // Keep this quality for the next n frames overflow_count = 60; JPEG_FB()->quality = IM_MAX(1, (JPEG_FB()->quality/2)); } JPEG_FB()->w = 0; JPEG_FB()->h = 0; JPEG_FB()->size = 0; } else { if (overflow_count) { overflow_count--; } // No buffer overflow, increase quality up to max quality based on frame size if (overflow_count == 0 && JPEG_FB()->quality < ((fb_buffer_size() > JPEG_QUALITY_THRESH) ? JPEG_QUALITY_LOW:JPEG_QUALITY_HIGH)) { JPEG_FB()->quality++; } // Set FB from JPEG image JPEG_FB()->w = dst.w; JPEG_FB()->h = dst.h; JPEG_FB()->size = dst.bpp; } // Unlock the framebuffer mutex mutex_unlock(&JPEG_FB()->lock, MUTEX_TID_OMV); } } }
dc1105e21b31c585e2d8d5998689e6f5e877db5b
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/include/linux/resume-trace.h
f31db23687828da2e209696c8612cb3f7a195801
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
700
h
resume-trace.h
#ifndef RESUME_TRACE_H #define RESUME_TRACE_H #ifdef CONFIG_PM_TRACE #include <asm/resume-trace.h> #include <linux/types.h> extern int pm_trace_enabled; static inline int pm_trace_is_enabled(void) { return pm_trace_enabled; } struct device; extern void set_trace_device(struct device *); extern void generate_resume_trace(const void *tracedata, unsigned int user); extern int show_trace_dev_match(char *buf, size_t size); #define TRACE_DEVICE(dev) do { \ if (pm_trace_enabled) \ set_trace_device(dev); \ } while(0) #else static inline int pm_trace_is_enabled(void) { return 0; } #define TRACE_DEVICE(dev) do { } while (0) #define TRACE_RESUME(dev) do { } while (0) #endif #endif
5375788e237182433e89987ba4d6fdf91c3b799a
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/include/linux/spinlock_api_smp.h
51df117abe46279223ed1f2a7cb911998aca5ecc
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
5,546
h
spinlock_api_smp.h
#ifndef __LINUX_SPINLOCK_API_SMP_H #define __LINUX_SPINLOCK_API_SMP_H #ifndef __LINUX_SPINLOCK_H # error "please don't include this file directly" #endif /* * include/linux/spinlock_api_smp.h * * spinlock API declarations on SMP (and debug) * (implemented in kernel/spinlock.c) * * portions Copyright 2005, Red Hat, Inc., Ingo Molnar * Released under the General Public License (GPL). */ int in_lock_functions(unsigned long addr); #define assert_raw_spin_locked(x) BUG_ON(!raw_spin_is_locked(x)) void __lockfunc _raw_spin_lock(raw_spinlock_t *lock) __acquires(lock); void __lockfunc _raw_spin_lock_nested(raw_spinlock_t *lock, int subclass) __acquires(lock); void __lockfunc _raw_spin_lock_nest_lock(raw_spinlock_t *lock, struct lockdep_map *map) __acquires(lock); void __lockfunc _raw_spin_lock_bh(raw_spinlock_t *lock) __acquires(lock); void __lockfunc _raw_spin_lock_irq(raw_spinlock_t *lock) __acquires(lock); unsigned long __lockfunc _raw_spin_lock_irqsave(raw_spinlock_t *lock) __acquires(lock); unsigned long __lockfunc _raw_spin_lock_irqsave_nested(raw_spinlock_t *lock, int subclass) __acquires(lock); int __lockfunc _raw_spin_trylock(raw_spinlock_t *lock); int __lockfunc _raw_spin_trylock_bh(raw_spinlock_t *lock); void __lockfunc _raw_spin_unlock(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_bh(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_irq(raw_spinlock_t *lock) __releases(lock); void __lockfunc _raw_spin_unlock_irqrestore(raw_spinlock_t *lock, unsigned long flags) __releases(lock); #ifdef CONFIG_INLINE_SPIN_LOCK #define _raw_spin_lock(lock) __raw_spin_lock(lock) #endif #ifdef CONFIG_INLINE_SPIN_LOCK_BH #define _raw_spin_lock_bh(lock) __raw_spin_lock_bh(lock) #endif #ifdef CONFIG_INLINE_SPIN_LOCK_IRQ #define _raw_spin_lock_irq(lock) __raw_spin_lock_irq(lock) #endif #ifdef CONFIG_INLINE_SPIN_LOCK_IRQSAVE #define _raw_spin_lock_irqsave(lock) __raw_spin_lock_irqsave(lock) #endif #ifdef CONFIG_INLINE_SPIN_TRYLOCK #define _raw_spin_trylock(lock) __raw_spin_trylock(lock) #endif #ifdef CONFIG_INLINE_SPIN_TRYLOCK_BH #define _raw_spin_trylock_bh(lock) __raw_spin_trylock_bh(lock) #endif #ifndef CONFIG_UNINLINE_SPIN_UNLOCK #define _raw_spin_unlock(lock) __raw_spin_unlock(lock) #endif #ifdef CONFIG_INLINE_SPIN_UNLOCK_BH #define _raw_spin_unlock_bh(lock) __raw_spin_unlock_bh(lock) #endif #ifdef CONFIG_INLINE_SPIN_UNLOCK_IRQ #define _raw_spin_unlock_irq(lock) __raw_spin_unlock_irq(lock) #endif #ifdef CONFIG_INLINE_SPIN_UNLOCK_IRQRESTORE #define _raw_spin_unlock_irqrestore(lock, flags) __raw_spin_unlock_irqrestore(lock, flags) #endif static inline int __raw_spin_trylock(raw_spinlock_t *lock) { preempt_disable(); if (do_raw_spin_trylock(lock)) { spin_acquire(&lock->dep_map, 0, 1, _RET_IP_); return 1; } preempt_enable(); return 0; } /* * If lockdep is enabled then we use the non-preemption spin-ops * even on CONFIG_PREEMPT, because lockdep assumes that interrupts are * not re-enabled during lock-acquire (which the preempt-spin-ops do): */ #if !defined(CONFIG_GENERIC_LOCKBREAK) || defined(CONFIG_DEBUG_LOCK_ALLOC) static inline unsigned long __raw_spin_lock_irqsave(raw_spinlock_t *lock) { unsigned long flags; local_irq_save(flags); preempt_disable(); spin_acquire(&lock->dep_map, 0, 0, _RET_IP_); /* * On lockdep we dont want the hand-coded irq-enable of * do_raw_spin_lock_flags() code, because lockdep assumes * that interrupts are not re-enabled during lock-acquire: */ #ifdef CONFIG_LOCKDEP LOCK_CONTENDED(lock, do_raw_spin_trylock, do_raw_spin_lock); #else do_raw_spin_lock_flags(lock, &flags); #endif return flags; } static inline void __raw_spin_lock_irq(raw_spinlock_t *lock) { local_irq_disable(); preempt_disable(); spin_acquire(&lock->dep_map, 0, 0, _RET_IP_); LOCK_CONTENDED(lock, do_raw_spin_trylock, do_raw_spin_lock); } static inline void __raw_spin_lock_bh(raw_spinlock_t *lock) { local_bh_disable(); preempt_disable(); spin_acquire(&lock->dep_map, 0, 0, _RET_IP_); LOCK_CONTENDED(lock, do_raw_spin_trylock, do_raw_spin_lock); } static inline void __raw_spin_lock(raw_spinlock_t *lock) { preempt_disable(); spin_acquire(&lock->dep_map, 0, 0, _RET_IP_); LOCK_CONTENDED(lock, do_raw_spin_trylock, do_raw_spin_lock); } #endif /* CONFIG_PREEMPT */ static inline void __raw_spin_unlock(raw_spinlock_t *lock) { spin_release(&lock->dep_map, 1, _RET_IP_); do_raw_spin_unlock(lock); preempt_enable(); } static inline void __raw_spin_unlock_irqrestore(raw_spinlock_t *lock, unsigned long flags) { spin_release(&lock->dep_map, 1, _RET_IP_); do_raw_spin_unlock(lock); local_irq_restore(flags); preempt_enable(); } static inline void __raw_spin_unlock_irq(raw_spinlock_t *lock) { spin_release(&lock->dep_map, 1, _RET_IP_); do_raw_spin_unlock(lock); local_irq_enable(); preempt_enable(); } static inline void __raw_spin_unlock_bh(raw_spinlock_t *lock) { spin_release(&lock->dep_map, 1, _RET_IP_); do_raw_spin_unlock(lock); preempt_enable_no_resched(); local_bh_enable_ip((unsigned long)__builtin_return_address(0)); } static inline int __raw_spin_trylock_bh(raw_spinlock_t *lock) { local_bh_disable(); preempt_disable(); if (do_raw_spin_trylock(lock)) { spin_acquire(&lock->dep_map, 0, 1, _RET_IP_); return 1; } preempt_enable_no_resched(); local_bh_enable_ip((unsigned long)__builtin_return_address(0)); return 0; } #include <linux/rwlock_api_smp.h> #endif /* __LINUX_SPINLOCK_API_SMP_H */
e3b1490e7904dcaa7cc40de37670950f2487c638
0ba9681b235b377b3f57d52532ab7212d4d4cd8a
/examples/zuc/zuc.c
3cfb79b6fcc02272a3fba6044137fffcd05cfd0a
[ "BSD-3-Clause" ]
permissive
GaloisInc/saw-script
d9a3eb7b05c1bcbcc319987223cd53b903b55b5d
79ddd800bec59528958ed6d7593304e2b17b7dfb
refs/heads/master
2023-09-01T09:47:31.415255
2023-08-30T11:26:08
2023-08-30T11:26:08
34,082,065
458
82
BSD-3-Clause
2023-09-14T16:23:09
2015-04-16T21:39:32
Haskell
UTF-8
C
false
false
9,010
c
zuc.c
/* ——————————————————————- */ typedef unsigned char u8; typedef unsigned int u32; /* ——————————————————————- */ /* the state registers of LFSR */ u32 LFSR_S0; u32 LFSR_S1; u32 LFSR_S2; u32 LFSR_S3; u32 LFSR_S4; u32 LFSR_S5; u32 LFSR_S6; u32 LFSR_S7; u32 LFSR_S8; u32 LFSR_S9; u32 LFSR_S10; u32 LFSR_S11; u32 LFSR_S12; u32 LFSR_S13; u32 LFSR_S14; u32 LFSR_S15; /* the registers of F */ u32 F_R1; u32 F_R2; /* the outputs of BitReorganization */ u32 BRC_X0; u32 BRC_X1; u32 BRC_X2; u32 BRC_X3; /* the s-boxes */ u8 S0[256] = { 0x3e,0x72,0x5b,0x47,0xca,0xe0,0x00,0x33,0x04,0xd1,0x54,0x98,0x09,0xb9,0x6d,0xcb, 0x7b,0x1b,0xf9,0x32,0xaf,0x9d,0x6a,0xa5,0xb8,0x2d,0xfc,0x1d,0x08,0x53,0x03,0x90, 0x4d,0x4e,0x84,0x99,0xe4,0xce,0xd9,0x91,0xdd,0xb6,0x85,0x48,0x8b,0x29,0x6e,0xac, 0xcd,0xc1,0xf8,0x1e,0x73,0x43,0x69,0xc6,0xb5,0xbd,0xfd,0x39,0x63,0x20,0xd4,0x38, 0x76,0x7d,0xb2,0xa7,0xcf,0xed,0x57,0xc5,0xf3,0x2c,0xbb,0x14,0x21,0x06,0x55,0x9b, 0xe3,0xef,0x5e,0x31,0x4f,0x7f,0x5a,0xa4,0x0d,0x82,0x51,0x49,0x5f,0xba,0x58,0x1c, 0x4a,0x16,0xd5,0x17,0xa8,0x92,0x24,0x1f,0x8c,0xff,0xd8,0xae,0x2e,0x01,0xd3,0xad, 0x3b,0x4b,0xda,0x46,0xeb,0xc9,0xde,0x9a,0x8f,0x87,0xd7,0x3a,0x80,0x6f,0x2f,0xc8, 0xb1,0xb4,0x37,0xf7,0x0a,0x22,0x13,0x28,0x7c,0xcc,0x3c,0x89,0xc7,0xc3,0x96,0x56, 0x07,0xbf,0x7e,0xf0,0x0b,0x2b,0x97,0x52,0x35,0x41,0x79,0x61,0xa6,0x4c,0x10,0xfe, 0xbc,0x26,0x95,0x88,0x8a,0xb0,0xa3,0xfb,0xc0,0x18,0x94,0xf2,0xe1,0xe5,0xe9,0x5d, 0xd0,0xdc,0x11,0x66,0x64,0x5c,0xec,0x59,0x42,0x75,0x12,0xf5,0x74,0x9c,0xaa,0x23, 0x0e,0x86,0xab,0xbe,0x2a,0x02,0xe7,0x67,0xe6,0x44,0xa2,0x6c,0xc2,0x93,0x9f,0xf1, 0xf6,0xfa,0x36,0xd2,0x50,0x68,0x9e,0x62,0x71,0x15,0x3d,0xd6,0x40,0xc4,0xe2,0x0f, 0x8e,0x83,0x77,0x6b,0x25,0x05,0x3f,0x0c,0x30,0xea,0x70,0xb7,0xa1,0xe8,0xa9,0x65, 0x8d,0x27,0x1a,0xdb,0x81,0xb3,0xa0,0xf4,0x45,0x7a,0x19,0xdf,0xee,0x78,0x34,0x60 }; u8 S1[256] = { 0x55,0xc2,0x63,0x71,0x3b,0xc8,0x47,0x86,0x9f,0x3c,0xda,0x5b,0x29,0xaa,0xfd,0x77, 0x8c,0xc5,0x94,0x0c,0xa6,0x1a,0x13,0x00,0xe3,0xa8,0x16,0x72,0x40,0xf9,0xf8,0x42, 0x44,0x26,0x68,0x96,0x81,0xd9,0x45,0x3e,0x10,0x76,0xc6,0xa7,0x8b,0x39,0x43,0xe1, 0x3a,0xb5,0x56,0x2a,0xc0,0x6d,0xb3,0x05,0x22,0x66,0xbf,0xdc,0x0b,0xfa,0x62,0x48, 0xdd,0x20,0x11,0x06,0x36,0xc9,0xc1,0xcf,0xf6,0x27,0x52,0xbb,0x69,0xf5,0xd4,0x87, 0x7f,0x84,0x4c,0xd2,0x9c,0x57,0xa4,0xbc,0x4f,0x9a,0xdf,0xfe,0xd6,0x8d,0x7a,0xeb, 0x2b,0x53,0xd8,0x5c,0xa1,0x14,0x17,0xfb,0x23,0xd5,0x7d,0x30,0x67,0x73,0x08,0x09, 0xee,0xb7,0x70,0x3f,0x61,0xb2,0x19,0x8e,0x4e,0xe5,0x4b,0x93,0x8f,0x5d,0xdb,0xa9, 0xad,0xf1,0xae,0x2e,0xcb,0x0d,0xfc,0xf4,0x2d,0x46,0x6e,0x1d,0x97,0xe8,0xd1,0xe9, 0x4d,0x37,0xa5,0x75,0x5e,0x83,0x9e,0xab,0x82,0x9d,0xb9,0x1c,0xe0,0xcd,0x49,0x89, 0x01,0xb6,0xbd,0x58,0x24,0xa2,0x5f,0x38,0x78,0x99,0x15,0x90,0x50,0xb8,0x95,0xe4, 0xd0,0x91,0xc7,0xce,0xed,0x0f,0xb4,0x6f,0xa0,0xcc,0xf0,0x02,0x4a,0x79,0xc3,0xde, 0xa3,0xef,0xea,0x51,0xe6,0x6b,0x18,0xec,0x1b,0x2c,0x80,0xf7,0x74,0xe7,0xff,0x21, 0x5a,0x6a,0x54,0x1e,0x41,0x31,0x92,0x35,0xc4,0x33,0x07,0x0a,0xba,0x7e,0x0e,0x34, 0x88,0xb1,0x98,0x7c,0xf3,0x3d,0x60,0x6c,0x7b,0xca,0xd3,0x1f,0x32,0x65,0x04,0x28, 0x64,0xbe,0x85,0x9b,0x2f,0x59,0x8a,0xd7,0xb0,0x25,0xac,0xaf,0x12,0x03,0xe2,0xf2 }; /* the constants D */ u32 EK_d[16] = { 0x44D7, 0x26BC, 0x626B, 0x135E, 0x5789, 0x35E2, 0x7135, 0x09AF, 0x4D78, 0x2F13, 0x6BC4, 0x1AF1, 0x5E26, 0x3C4D, 0x789A, 0x47AC }; u32 F(); /* ——————————————————————- */ /* c = a + b mod 2^31 - 1 */ u32 AddM(u32 a, u32 b) { u32 c = a + b; if (c & 0x80000000) { c = (c & 0x7FFFFFFF) + 1; } return c; } /* LFSR with initialization mode */ u32 MulByPow2(u32 x, u32 k) { return ((x << k) | (x >> (31 - k))) & 0x7FFFFFFF; } void LFSRWithInitialisationMode(u32 u) { u32 f, v; f = LFSR_S0; v = MulByPow2(LFSR_S0, 8); f = AddM(f, v); v = MulByPow2(LFSR_S4, 20); f = AddM(f, v); v = MulByPow2(LFSR_S10, 21); f = AddM(f, v); v = MulByPow2(LFSR_S13, 17); f = AddM(f, v); v = MulByPow2(LFSR_S15, 15); f = AddM(f, v); /* update the state */ LFSR_S0 = LFSR_S1; LFSR_S1 = LFSR_S2; LFSR_S2 = LFSR_S3; LFSR_S3 = LFSR_S4; LFSR_S4 = LFSR_S5; LFSR_S5 = LFSR_S6; LFSR_S6 = LFSR_S7; LFSR_S7 = LFSR_S8; LFSR_S8 = LFSR_S9; LFSR_S9 = LFSR_S10; LFSR_S10 = LFSR_S11; LFSR_S11 = LFSR_S12; LFSR_S12 = LFSR_S13; LFSR_S13 = LFSR_S14; LFSR_S14 = LFSR_S15; #ifdef VERSION_1_4 LFSR_S15 = f ^ u; #else LFSR_S15 = AddM(f, u); #endif /* adjust LFSR_S15 if LFSR_S15 is zero */ if (LFSR_S15 == 0) { LFSR_S15 = 0x7FFFFFFF; } } /* LFSR with work mode */ void LFSRWithWorkMode() { u32 f, v; f = LFSR_S0; v = MulByPow2(LFSR_S0, 8); f = AddM(f, v); v = MulByPow2(LFSR_S4, 20); f = AddM(f, v); v = MulByPow2(LFSR_S10, 21); f = AddM(f, v); v = MulByPow2(LFSR_S13, 17); f = AddM(f, v); v = MulByPow2(LFSR_S15, 15); f = AddM(f, v); /* update the state */ LFSR_S0 = LFSR_S1; LFSR_S1 = LFSR_S2; LFSR_S2 = LFSR_S3; LFSR_S3 = LFSR_S4; LFSR_S4 = LFSR_S5; LFSR_S5 = LFSR_S6; LFSR_S6 = LFSR_S7; LFSR_S7 = LFSR_S8; LFSR_S8 = LFSR_S9; LFSR_S9 = LFSR_S10; LFSR_S10 = LFSR_S11; LFSR_S11 = LFSR_S12; LFSR_S12 = LFSR_S13; LFSR_S13 = LFSR_S14; LFSR_S14 = LFSR_S15; LFSR_S15 = f; } /* BitReorganization */ void BitReorganization() { BRC_X0 = ((LFSR_S15 & 0x7FFF8000) << 1) | (LFSR_S14 & 0xFFFF); BRC_X1 = ((LFSR_S11 & 0xFFFF) << 16) | (LFSR_S9 >> 15); BRC_X2 = ((LFSR_S7 & 0xFFFF) << 16) | (LFSR_S5 >> 15); BRC_X3 = ((LFSR_S2 & 0xFFFF) << 16) | (LFSR_S0 >> 15); } #define ROT(a, k) (((a) << k) | ((a) >> (32 - k))) /* L1 */ u32 L1(u32 X) { return (X ^ ROT(X, 2) ^ ROT(X, 10) ^ ROT(X, 18) ^ ROT(X, 24)); } /* L2 */ u32 L2(u32 X) { return (X ^ ROT(X, 8) ^ ROT(X, 14) ^ ROT(X, 22) ^ ROT(X, 30)); } #define MAKEU32(a, b, c, d) (((u32)(a) << 24) | ((u32)(b) << 16) | ((u32)(c) << 8) | ((u32)(d))) /* F */ u32 F() { u32 W, W1, W2, u, v; W = (BRC_X0 ^ F_R1) + F_R2; W1 = F_R1 + BRC_X1; W2 = F_R2 ^ BRC_X2; u = L1((W1 << 16) | (W2 >> 16)); v = L2((W2 << 16) | (W1 >> 16)); F_R1 = MAKEU32(S0[u >> 24], S1[(u >> 16) & 0xFF], S0[(u >> 8) & 0xFF], S1[u & 0xFF]); F_R2 = MAKEU32(S0[v >> 24], S1[(v >> 16) & 0xFF], S0[(v >> 8) & 0xFF], S1[v & 0xFF]); return W; } #define MAKEU31(a, b, c) (((u32)(a) << 23) | ((u32)(b) << 8) | (u32)(c)) /* initialize */ void Initialization(u8* k, u8* iv) { u32 w, nCount; /* expand key */ LFSR_S0 = MAKEU31(k[0], EK_d[0], iv[0]); LFSR_S1 = MAKEU31(k[1], EK_d[1], iv[1]); LFSR_S2 = MAKEU31(k[2], EK_d[2], iv[2]); LFSR_S3 = MAKEU31(k[3], EK_d[3], iv[3]); LFSR_S4 = MAKEU31(k[4], EK_d[4], iv[4]); LFSR_S5 = MAKEU31(k[5], EK_d[5], iv[5]); LFSR_S6 = MAKEU31(k[6], EK_d[6], iv[6]); LFSR_S7 = MAKEU31(k[7], EK_d[7], iv[7]); LFSR_S8 = MAKEU31(k[8], EK_d[8], iv[8]); LFSR_S9 = MAKEU31(k[9], EK_d[9], iv[9]); LFSR_S10 = MAKEU31(k[10], EK_d[10], iv[10]); LFSR_S11 = MAKEU31(k[11], EK_d[11], iv[11]); LFSR_S12 = MAKEU31(k[12], EK_d[12], iv[12]); LFSR_S13 = MAKEU31(k[13], EK_d[13], iv[13]); LFSR_S14 = MAKEU31(k[14], EK_d[14], iv[14]); LFSR_S15 = MAKEU31(k[15], EK_d[15], iv[15]); /* set F_R1 and F_R2 to zero */ F_R1 = 0; F_R2 = 0; nCount = 32; while (nCount > 0) { BitReorganization(); w = F(); #ifdef VERSION_1_4 w ^= BRC_X3; #endif LFSRWithInitialisationMode(w >> 1); nCount --; } } void InitializationOne(u8* k, u8* iv) { u32 w; /* expand key */ LFSR_S0 = MAKEU31(k[0], EK_d[0], iv[0]); LFSR_S1 = MAKEU31(k[1], EK_d[1], iv[1]); LFSR_S2 = MAKEU31(k[2], EK_d[2], iv[2]); LFSR_S3 = MAKEU31(k[3], EK_d[3], iv[3]); LFSR_S4 = MAKEU31(k[4], EK_d[4], iv[4]); LFSR_S5 = MAKEU31(k[5], EK_d[5], iv[5]); LFSR_S6 = MAKEU31(k[6], EK_d[6], iv[6]); LFSR_S7 = MAKEU31(k[7], EK_d[7], iv[7]); LFSR_S8 = MAKEU31(k[8], EK_d[8], iv[8]); LFSR_S9 = MAKEU31(k[9], EK_d[9], iv[9]); LFSR_S10 = MAKEU31(k[10], EK_d[10], iv[10]); LFSR_S11 = MAKEU31(k[11], EK_d[11], iv[11]); LFSR_S12 = MAKEU31(k[12], EK_d[12], iv[12]); LFSR_S13 = MAKEU31(k[13], EK_d[13], iv[13]); LFSR_S14 = MAKEU31(k[14], EK_d[14], iv[14]); LFSR_S15 = MAKEU31(k[15], EK_d[15], iv[15]); /* set F_R1 and F_R2 to zero */ F_R1 = 0; F_R2 = 0; BitReorganization(); w = F(); #ifdef VERSION_1_4 w ^= BRC_X3; #endif LFSRWithInitialisationMode(w >> 1); } void GenerateKeystream(u32* pKeystream, int KeystreamLen) { int i; { BitReorganization(); F(); /* discard the output of F */ LFSRWithWorkMode(); } for (i = 0; i < KeystreamLen; i ++) { BitReorganization(); pKeystream[i] = F() ^ BRC_X3; LFSRWithWorkMode(); } }
9f7958a175b0203c713ec756b64539328714ba26
a5a7c59b04a1a64fe34653c7970c3cf173f9c1df
/numerics/src/QP/ConvexQP_cst.h
b7bf353171e9aafe8d3e201724b42bea56784175
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
siconos/siconos
a7afdba41a2bc1192ad8dcd93ac7266fa281f4cf
82a8d1338bfc1be0d36b5e8a9f40c1ad5384a641
refs/heads/master
2023-08-21T22:22:55.625941
2023-07-17T13:07:32
2023-07-17T13:07:32
37,709,357
166
33
Apache-2.0
2023-07-17T12:31:16
2015-06-19T07:55:53
C
UTF-8
C
false
false
3,733
h
ConvexQP_cst.h
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2022 INRIA. * * 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 CONVEXQP_CST_H #define CONVEXQP_CST_H /*!\file ConvexQP_cst.h \brief Enum and constants relative to QP solvers. */ /** \enum CONVEXQP_SOLVER List of available ids for QP solvers. */ enum CONVEXQP_SOLVER { /** convex QP, projected gradient */ SICONOS_CONVEXQP_PG = 1200, /** convex QP, VI solver, fixed point projection */ SICONOS_CONVEXQP_VI_FPP= 1201, /** convex QP, VI solver, extra-gradient */ SICONOS_CONVEXQP_VI_EG= 1202, /** convex QP, alternating direction method of multipliers (ADMM) */ SICONOS_CONVEXQP_ADMM= 1203 }; extern const char* const SICONOS_CONVEXQP_PG_STR; extern const char* const SICONOS_CONVEXQP_VI_FPP_STR; extern const char* const SICONOS_CONVEXQP_VI_EG_STR; extern const char* const SICONOS_CONVEXQP_ADMM_STR; /** iparam indices specific to QP solvers. */ enum SICONOS_CONVEXQP_PGOC_IPARAM_ENUM { /** index in iparam to store the maximum number of iterations */ SICONOS_CONVEXQP_PGOC_LINESEARCH_MAX_ITER = 10 }; /** dparam indices specific to QP solvers. */ enum SICONOS_CONVEXQP_PGOC_DPARAM_ENUM { /** index in dparam to store the rho value for projection formulation */ SICONOS_CONVEXQP_PGOC_RHO = 3, /** index in dparam to store the minrho value for projection formulation */ SICONOS_CONVEXQP_PGOC_RHOMIN = 4, /** index in dparam to store the mu value for line search algo */ SICONOS_CONVEXQP_PGOC_LINESEARCH_MU = 5, /** index in dparam to store the tau value for line search algo */ SICONOS_CONVEXQP_PGOC_LINESEARCH_TAU = 6 }; enum SICONOS_CONVEXQP_ADMM_IPARAM_ENUM { /** index in iparam to store the strategy for computing rho */ SICONOS_CONVEXQP_ADMM_IPARAM_RHO_STRATEGY = 9, /** index in iparam to store the acceleration paramter */ SICONOS_CONVEXQP_ADMM_IPARAM_ACCELERATION= 10 }; enum SICONOS_CONVEXQP_ADMM_DPARAM_ENUM { /** index in dparam to store the rho value for projection formulation */ SICONOS_CONVEXQP_ADMM_RHO = 3, /** index in dparam to store the rho value for projection formulation */ SICONOS_CONVEXQP_ADMM_RESTART_ETA = 4, /** index in dparam to store the tau value for the balancing residual technique */ SICONOS_CONVEXQP_ADMM_BALANCING_RESIDUAL_TAU = 5, /** index in dparam to store the phi value for the balancing residual technique */ SICONOS_CONVEXQP_ADMM_BALANCING_RESIDUAL_PHI = 6 }; enum SICONOS_CONVEXQP_ADMM_ACCELERATION_ENUM { SICONOS_CONVEXQP_ADMM_NO_ACCELERATION= 0, SICONOS_CONVEXQP_ADMM_ACCELERATION= 1, SICONOS_CONVEXQP_ADMM_ACCELERATION_AND_RESTART= 2 }; enum SICONOS_CONVEXQP_RHO_STRATEGY_ENUM { /** A constant value given in dparam[CONVEXQP_RHO_RHO] is used */ SICONOS_CONVEXQP_RHO_STRATEGY_CONSTANT = 0, /** A computed value stored in dparam[SICONOS_CONVEXQP_NSN_RHO] is used */ SICONOS_CONVEXQP_ADMM_RHO_STRATEGY_NORM_INF =1, /** An adaptive strategy for rho is used */ SICONOS_CONVEXQP_ADMM_RHO_STRATEGY_RESIDUAL_BALANCING =2, /** An adaptive strategy for rho is used */ SICONOS_CONVEXQP_ADMM_RHO_STRATEGY_SCALED_RESIDUAL_BALANCING =3 }; #endif
de9033edd075529c6aafe953d400c90a057b6148
e73547787354afd9b717ea57fe8dd0695d161821
/src/battle/move/star_power/smooch.c
7384161634517c90a7ebec6908f2ccac326245e2
[]
no_license
pmret/papermario
8b514b19653cef8d6145e47499b3636b8c474a37
9774b26d93f1045dd2a67e502b6efc9599fb6c31
refs/heads/main
2023-08-31T07:09:48.951514
2023-08-21T18:07:08
2023-08-21T18:07:08
287,151,133
904
139
null
2023-09-14T02:44:23
2020-08-13T01:22:57
C
UTF-8
C
false
false
7,169
c
smooch.c
#include "common.h" #include "script_api/battle.h" #include "sprite/npc/BattleMisstar.h" #include "sprite/player.h" #define NAMESPACE battle_move_smooch #include "battle/common/move/StarPowerSupport.inc.c" #include "common/AddHP.inc.c" API_CALLABLE(N(SpawnRecoverFX)) { Bytecode* args = script->ptrReadPos; s32 x = evt_get_variable(script, *args++); s32 y = evt_get_variable(script, *args++); s32 z = evt_get_variable(script, *args++); s32 duration = evt_get_variable(script, *args++); fx_recover(0, x, y, z, duration); return ApiStatus_DONE2; } Vec2i N(RecoverEffectPositions)[] = { { 15, 15 }, { -33, 27 }, { -22, -26 }, { 10, -35 }, { 35, 0 }, }; EvtScript N(EVS_UsePower) = { EVT_EXEC_WAIT(N(EVS_StarPower_WishForSpirit)) EVT_SET_CONST(LVar0, ANIM_BattleMisstar_Still) EVT_EXEC_WAIT(N(EVS_StarPower_SpiritSummoned)) EVT_WAIT(16) EVT_THREAD EVT_WAIT(10) EVT_CALL(SetNpcRotation, NPC_BTL_SPIRIT, 0, 180, 0) EVT_WAIT(1) EVT_CALL(SetNpcRotation, NPC_BTL_SPIRIT, 0, 150, 0) EVT_WAIT(1) EVT_CALL(SetNpcRotation, NPC_BTL_SPIRIT, 0, 120, 0) EVT_WAIT(1) EVT_CALL(SetNpcRotation, NPC_BTL_SPIRIT, 0, 90, 0) EVT_WAIT(1) EVT_CALL(SetNpcRotation, NPC_BTL_SPIRIT, 0, 60, 0) EVT_WAIT(1) EVT_CALL(SetNpcRotation, NPC_BTL_SPIRIT, 0, 30, 0) EVT_WAIT(1) EVT_CALL(SetNpcRotation, NPC_BTL_SPIRIT, 0, 0, 0) EVT_END_THREAD EVT_CALL(GetActorPos, ACTOR_PLAYER, LVar0, LVar1, LVar2) EVT_ADD(LVar1, 25) EVT_ADD(LVar0, 30) EVT_CALL(NpcFlyTo, NPC_BTL_SPIRIT, LVar0, LVar1, LVar2, 20, 0, EASING_COS_IN_OUT) EVT_WAIT(15) EVT_CALL(SetNpcAnimation, NPC_BTL_SPIRIT, ANIM_BattleMisstar_Idle) EVT_CALL(GetActorPos, ACTOR_PLAYER, LVar0, LVar1, LVar2) EVT_ADD(LVar0, 15) EVT_ADD(LVar1, 15) EVT_ADD(LVar2, -5) EVT_CALL(NpcFlyTo, NPC_BTL_SPIRIT, LVar0, LVar1, LVar2, 10, 0, EASING_COS_IN_OUT) EVT_CALL(PlaySound, SOUND_SMOOCH) EVT_THREAD EVT_PLAY_EFFECT(EFFECT_RECOVER, 2, LVar0, LVar1, LVar2, 1, 0) EVT_WAIT(2) EVT_USE_BUF(EVT_PTR(N(RecoverEffectPositions))) EVT_LOOP(ARRAY_COUNT(N(RecoverEffectPositions))) EVT_BUF_READ2(LVar5, LVar6) EVT_SET(LVar3, LVar0) EVT_SET(LVar4, LVar1) EVT_ADD(LVar3, LVar5) EVT_ADD(LVar4, LVar6) EVT_PLAY_EFFECT(EFFECT_RECOVER, 2, LVar3, LVar4, LVar2, 1, 0) EVT_WAIT(2) EVT_END_LOOP EVT_END_THREAD EVT_THREAD EVT_CALL(GetActorPos, ACTOR_PLAYER, LVar0, LVar1, LVar2) EVT_ADD(LVar1, 15) EVT_ADD(LVar0, 5) EVT_CALL(N(SpawnStarSparkleFX), LVar0, LVar1, LVar2) EVT_CALL(GetActorPos, ACTOR_PLAYER, LVar0, LVar1, LVar2) EVT_ADD(LVar1, 20) EVT_ADD(LVar0, 25) EVT_CALL(NpcFlyTo, NPC_BTL_SPIRIT, LVar0, LVar1, LVar2, 10, 0, EASING_COS_IN_OUT) EVT_END_THREAD EVT_CALL(SetAnimation, ACTOR_PLAYER, 0, ANIM_Mario1_FallBack) EVT_WAIT(12) EVT_THREAD EVT_EXEC_WAIT(N(EVS_StarPower_SpiritDeparts)) EVT_END_THREAD EVT_THREAD EVT_LOOP(2) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.0), EVT_FLOAT(1.0), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.1), EVT_FLOAT(1.0), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.2), EVT_FLOAT(0.95), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.3), EVT_FLOAT(0.9), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.35), EVT_FLOAT(0.85), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.38), EVT_FLOAT(0.8), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.4), EVT_FLOAT(0.8), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.3), EVT_FLOAT(0.85), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.2), EVT_FLOAT(0.9), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.1), EVT_FLOAT(0.95), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_END_LOOP EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.0), EVT_FLOAT(1.0), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.1), EVT_FLOAT(1.0), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.2), EVT_FLOAT(0.95), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.3), EVT_FLOAT(0.9), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.35), EVT_FLOAT(0.85), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.38), EVT_FLOAT(0.8), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.4), EVT_FLOAT(0.8), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(0.9), EVT_FLOAT(1.3), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(0.9), EVT_FLOAT(1.2), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(0.95), EVT_FLOAT(1.1), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetActorScale, ACTOR_SELF, EVT_FLOAT(1.0), EVT_FLOAT(1.0), EVT_FLOAT(1.0)) EVT_WAIT(1) EVT_CALL(SetAnimation, ACTOR_PLAYER, 0, ANIM_Mario1_Idle) EVT_END_THREAD EVT_LOOP(10) EVT_WAIT(3) EVT_END_LOOP EVT_CALL(UseBattleCamPreset, BTL_CAM_DEFAULT) EVT_CALL(GetActorPos, ACTOR_PLAYER, LVar0, LVar1, LVar2) EVT_ADD(LVar0, 0) EVT_ADD(LVar1, 35) EVT_CALL(N(SpawnRecoverFX), LVar0, LVar1, LVar2, 20) EVT_CALL(GetActorPos, ACTOR_PLAYER, LVar0, LVar1, LVar2) EVT_ADD(LVar1, 25) EVT_CALL(ShowStartRecoveryShimmer, LVar0, LVar1, LVar2, 20) EVT_CALL(N(AddHP), 20) EVT_THREAD EVT_CALL(N(FadeBackgroundLighten)) EVT_END_THREAD EVT_CALL(PlayerYieldTurn) EVT_CALL(PlaySoundAtActor, ACTOR_PLAYER, SOUND_PLAYER_JUMP) EVT_CALL(SetActorJumpGravity, ACTOR_PLAYER, EVT_FLOAT(1.0)) EVT_CALL(SetActorSpeed, ACTOR_PLAYER, EVT_FLOAT(1.0)) EVT_CALL(GetActorPos, ACTOR_PLAYER, LVar0, LVar1, LVar2) EVT_CALL(SetJumpAnimations, ACTOR_PLAYER, 0, ANIM_Mario1_Jump, ANIM_Mario1_Fall, ANIM_Mario1_Land) EVT_CALL(SetGoalPos, ACTOR_PLAYER, LVar0, LVar1, LVar2) EVT_CALL(func_80273444, 20, 0, 0) EVT_CALL(SetAnimation, ACTOR_PLAYER, 0, ANIM_Mario1_Land) EVT_WAIT(4) EVT_CALL(SetAnimation, ACTOR_PLAYER, 0, ANIM_Mario1_Idle) EVT_CALL(SetGoalToHome, ACTOR_PLAYER) EVT_CALL(SetActorSpeed, ACTOR_PLAYER, EVT_FLOAT(8.0)) EVT_CALL(SetAnimation, ACTOR_PLAYER, 0, ANIM_Mario1_Run) EVT_CALL(PlayerRunToGoal, 0) EVT_CALL(SetAnimation, ACTOR_PLAYER, 0, ANIM_Mario1_Idle) EVT_RETURN EVT_END };
e4560edc5cb77e38664d9a3161f65c11fac7b4a6
03666e5f961946fc1a0ac67781ac1425562ef0d7
/src/operators/LineSampler/LineSamplerViewerEnginePluginInfo.C
681eb32a2f631035ad9297ddd34d0da961ab0d50
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
visit-dav/visit
e9f81b4d4b9b9930a0db9d5282cd1bcabf465e2e
601ae46e0bef2e18425b482a755d03490ade0493
refs/heads/develop
2023-09-06T08:19:38.397058
2023-09-05T21:29:32
2023-09-05T21:29:32
165,565,988
335
120
BSD-3-Clause
2023-09-14T00:53:37
2019-01-13T23:27:26
C
UTF-8
C
false
false
8,869
c
LineSamplerViewerEnginePluginInfo.C
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt // Project developers. See the top-level LICENSE file for dates and other // details. No copyright assignment is required to contribute to VisIt. // **************************************************************************** // File: LineSamplerViewerEnginePluginInfo.C // **************************************************************************** #include <LineSamplerPluginInfo.h> #include <LineSamplerAttributes.h> // // Storage for static data elements. // LineSamplerAttributes *LineSamplerViewerEnginePluginInfo::clientAtts = NULL; LineSamplerAttributes *LineSamplerViewerEnginePluginInfo::defaultAtts = NULL; // **************************************************************************** // Method: LineSamplerViewerEnginePluginInfo::InitializeGlobalObjects // // Purpose: // Initialize the operator atts. // // Programmer: generated by xml2info // Creation: omitted // // **************************************************************************** void LineSamplerViewerEnginePluginInfo::InitializeGlobalObjects() { if (LineSamplerViewerEnginePluginInfo::clientAtts == NULL) { LineSamplerViewerEnginePluginInfo::clientAtts = new LineSamplerAttributes; LineSamplerViewerEnginePluginInfo::defaultAtts = new LineSamplerAttributes; } } // **************************************************************************** // Method: LineSamplerViewerEnginePluginInfo::GetClientAtts // // Purpose: // Return a pointer to the viewer client attributes. // // Returns: A pointer to the viewer client attributes. // // Programmer: generated by xml2info // Creation: omitted // // **************************************************************************** AttributeSubject * LineSamplerViewerEnginePluginInfo::GetClientAtts() { return clientAtts; } // **************************************************************************** // Method: LineSamplerViewerEnginePluginInfo::GetDefaultAtts // // Purpose: // Return a pointer to the viewer default attributes. // // Returns: A pointer to the viewer default attributes. // // Programmer: generated by xml2info // Creation: omitted // // **************************************************************************** AttributeSubject * LineSamplerViewerEnginePluginInfo::GetDefaultAtts() { return defaultAtts; } // **************************************************************************** // Method: LineSamplerViewerEnginePluginInfo::SetClientAtts // // Purpose: // Set the viewer client attributes. // // Arguments: // atts A pointer to the new client attributes. // // Programmer: generated by xml2info // Creation: omitted // // **************************************************************************** void LineSamplerViewerEnginePluginInfo::SetClientAtts(AttributeSubject *atts) { *clientAtts = *(LineSamplerAttributes *)atts; clientAtts->Notify(); } // **************************************************************************** // Method: LineSamplerViewerEnginePluginInfo::GetClientAtts // // Purpose: // Get the viewer client attributes. // // Arguments: // atts A pointer to return the client default attributes in. // // Programmer: generated by xml2info // Creation: omitted // // **************************************************************************** void LineSamplerViewerEnginePluginInfo::GetClientAtts(AttributeSubject *atts) { std::cerr << __FILE__ << " " << __LINE__ << " " << "SHOULD NOT BE CALLED" << std::endl; // *(LineSamplerAttributes *)atts = *clientAtts; } // Just do this stuff in the viewer version. #if !defined(ELineSamplerOperator_ser_EXPORTS) && !defined(ELineSamplerOperator_par_EXPORTS) && !defined(VISIT_STATIC) #include <ViewerBase.h> #include <ViewerMessaging.h> #include <ViewerText.h> #endif // **************************************************************************** // Method: LineSamplerViewerEnginePluginInfo::GetClientAtts // // Purpose: // Get the viewer client attributes. // // Arguments: // atts A pointer to return the client default attributes in. // // Programmer: generated by xml2info // Creation: omitted // // **************************************************************************** void LineSamplerViewerEnginePluginInfo::GetClientAtts(AttributeSubject *atts, const bool activeOperator, const bool applyToAll) { LineSamplerAttributes aTmp = *clientAtts; if( applyToAll ) { // Allow the user to set the instance (up to 5 are allowed). Only // apply to all if the instances match otherwise skip it. if( (*(LineSamplerAttributes *)atts).GetInstanceId() != (*clientAtts).GetInstanceId() ) return; // If needed save off the old values so they are not changed. if( (*(LineSamplerAttributes *)atts).GetDonotApplyToAll() ) { LineSamplerAttributes::ViewDimension oldViewDim = (*(LineSamplerAttributes *)atts).GetViewDimension(); LineSamplerAttributes::ViewGeometry oldViewGeom = (*(LineSamplerAttributes *)atts).GetViewGeometry(); // Just do this stuff in the viewer version. #if !defined(ELineSamplerOperator_ser_EXPORTS) && !defined(ELineSamplerOperator_par_EXPORTS) && !defined(VISIT_STATIC) LineSamplerAttributes::ViewDimension newViewDim = (*clientAtts).GetViewDimension(); LineSamplerAttributes::ViewGeometry newViewGeom = (*clientAtts).GetViewGeometry(); if( activeOperator && (newViewDim != oldViewDim || newViewGeom != oldViewGeom) ) { ViewerBase vb; ViewerText msg("You are attemping to change the 'View dimension' " "or the 'View geometry' while the 'Apply to all windows' " "and/or the 'Apply operators to all plots' and the " "'Do not apply to all' are all checked. This setting " "is a conflict. The 'View dimension' and 'View geometry' " "will not be changed."); vb.GetViewerMessaging()->Warning(msg); } #endif *(LineSamplerAttributes *)atts = *clientAtts; (*(LineSamplerAttributes *)atts).SetViewDimension( oldViewDim ); (*(LineSamplerAttributes *)atts).SetViewGeometry( oldViewGeom ); } else // No restriction on the apply operation. { *(LineSamplerAttributes *)atts = *clientAtts; } } else // Not applying to all { *(LineSamplerAttributes *)atts = *clientAtts; } } // **************************************************************************** // Method: LineSamplerViewerEnginePluginInfo::InitializeOperatorAtts // // Purpose: // Initialize the operator attributes to the default attributes. // // Arguments: // atts The attribute subject to initialize. // plot The viewer plot that owns the operator. // fromDefault True to initialize the attributes from the defaults. False // to initialize from the current attributes. // // Programmer: generated by xml2info // Creation: omitted // // **************************************************************************** void LineSamplerViewerEnginePluginInfo::InitializeOperatorAtts(AttributeSubject *atts, const avtPlotMetaData &plot, const bool fromDefault) { if (fromDefault) *(LineSamplerAttributes*)atts = *defaultAtts; else *(LineSamplerAttributes*)atts = *clientAtts; UpdateOperatorAtts(atts, plot); } // **************************************************************************** // Method: LineSamplerViewerEnginePluginInfo::UpdateOperatorAtts // // Purpose: // Update the operator attributes when using operator expressions. // // Arguments: // atts The attribute subject to update. // plot The viewer plot that owns the operator. // // Programmer: generated by xml2info // Creation: omitted // // **************************************************************************** void LineSamplerViewerEnginePluginInfo::UpdateOperatorAtts(AttributeSubject *atts, const avtPlotMetaData &plot) { } // **************************************************************************** // Method: LineSamplerViewerEnginePluginInfo::GetMenuName // // Purpose: // Return a pointer to the name to use in the viewer menus. // // Returns: A pointer to the name to use in the viewer menus. // // Programmer: generated by xml2info // Creation: omitted // // **************************************************************************** const char * LineSamplerViewerEnginePluginInfo::GetMenuName() const { return "LineSampler"; }
9e3be38aa0d9031e4ebf1eeea9e468f3ccad80a1
d490cce62a5b14bfb11b3597365fa98cb2d1611f
/clang/test/CAS/fcache-compile-job-dependency-file.c
de32a1232ab274eafcfae352095568c3327e765c
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
apple/llvm-project
bbaf327ccd73f830f91a3519e16c21ac10f5d245
8e19e2fe15202bad879471d45976b53db132a10b
refs/heads/next
2023-08-31T13:34:15.321709
2023-08-31T12:02:09
2023-08-30T23:39:33
215,875,945
938
380
NOASSERTION
2023-09-14T21:52:14
2019-10-17T20:03:10
null
UTF-8
C
false
false
3,600
c
fcache-compile-job-dependency-file.c
// RUN: rm -rf %t && mkdir -p %t // RUN: split-file %s %t/src // RUN: llvm-cas --cas %t/cas --ingest --data %t/src > %t/casid // // RUN: %clang -cc1 -triple x86_64-apple-macos11 \ // RUN: -fcas-path %t/cas -fcas-fs @%t/casid -fcache-compile-job \ // RUN: -Rcompile-job-cache %t/src/main.c -emit-obj -o %t/output.o -isystem %t/src/sys \ // RUN: -dependency-file %t/deps1.d -MT depends 2>&1 \ // RUN: | FileCheck %s --allow-empty --check-prefix=CACHE-MISS // // RUN: FileCheck %s --input-file=%t/deps1.d --check-prefix=DEPS // DEPS: depends: // DEPS: main.c // DEPS: my_header.h // DEPS-NOT: sys.h // RUN: ls %t/output.o && rm %t/output.o // // RUN: %clang -cc1 -triple x86_64-apple-macos11 \ // RUN: -fcas-path %t/cas -fcas-fs @%t/casid -fcache-compile-job \ // RUN: -Rcompile-job-cache %t/src/main.c -emit-obj -o %t/output.o -isystem %t/src/sys \ // RUN: -dependency-file %t/deps2.d -MT depends 2>&1 \ // RUN: | FileCheck %s --check-prefix=CACHE-HIT // // RUN: ls %t/output.o // RUN: diff -u %t/deps1.d %t/deps2.d // // CACHE-HIT: remark: compile job cache hit // CACHE-MISS-NOT: remark: compile job cache hit // RUN: %clang -cc1 -triple x86_64-apple-macos11 \ // RUN: -fcas-path %t/cas -fcas-fs @%t/casid -fcache-compile-job \ // RUN: -Rcompile-job-cache %t/src/main.c -emit-obj -o %t/output.o -isystem %t/src/sys \ // RUN: -dependency-file %t/deps3.d -MT other1 -MT other2 -MP -fdepfile-entry=extra-depfile.json 2>&1 \ // RUN: | FileCheck %s --check-prefix=CACHE-HIT // RUN: FileCheck %s --input-file=%t/deps3.d --check-prefix=DEPS_OTHER // DEPS_OTHER: other1 other2: // DEPS_OTHER: extra-depfile.json // DEPS_OTHER: main.c // DEPS_OTHER: my_header.h // DEPS_OTHER-NOT: sys.h // DEPS_OTHER: my_header.h: // RUN: %clang -cc1 -triple x86_64-apple-macos11 \ // RUN: -fcas-path %t/cas -fcas-fs @%t/casid -fcache-compile-job \ // RUN: -Rcompile-job-cache %t/src/main.c -emit-obj -o %t/output.o -isystem %t/src/sys \ // RUN: -sys-header-deps -dependency-file %t/deps4.d -MT depends 2>&1 \ // RUN: | FileCheck %s --check-prefix=CACHE-MISS // Note: currently options that affect the list of deps (like sys-header-deps) // are part of the cache key, to avoid saving unnecessary paths. // RUN: FileCheck %s --input-file=%t/deps4.d --check-prefix=DEPS_SYS // DEPS_SYS: depends: // DEPS_SYS: main.c // DEPS_SYS: my_header.h // DEPS_SYS: sys.h // Using another cas path to avoid reusing artifacts. // RUN: llvm-cas --cas %t/cas2 --ingest --data %t/src // RUN: %clang -cc1 -triple x86_64-apple-macos11 \ // RUN: -fcas-path %t/cas2 -fcas-fs @%t/casid -fcache-compile-job \ // RUN: -Rcompile-job-cache %t/src/main.c -emit-obj -o %t/output.o -isystem %t/src/sys \ // RUN: -dependency-file %t/deps-depfile1.d -MT deps -fdepfile-entry=extra-depfile.json -fdepfile-entry=%t/main.c 2>&1 \ // RUN: | FileCheck %s --check-prefix=CACHE-MISS // RUN: FileCheck %s --input-file=%t/deps-depfile1.d --check-prefix=DEPS_DEPFILE1 // DEPS_DEPFILE1: deps: // DEPS_DEPFILE1: extra-depfile.json // DEPS_DEPFILE1: main.c // RUN: %clang -cc1 -triple x86_64-apple-macos11 \ // RUN: -fcas-path %t/cas2 -fcas-fs @%t/casid -fcache-compile-job \ // RUN: -Rcompile-job-cache %t/src/main.c -emit-obj -o %t/output.o -isystem %t/src/sys \ // RUN: -dependency-file %t/deps-depfile2.d -MT deps 2>&1 \ // RUN: | FileCheck %s --check-prefix=CACHE-HIT // RUN: FileCheck %s --input-file=%t/deps-depfile2.d --check-prefix=DEPS_DEPFILE2 // DEPS_DEPFILE2-NOT: extra-depfile.json // DEPS_DEPFILE2: main.c //--- main.c #include "my_header.h" #include <sys.h> //--- my_header.h //--- sys/sys.h
eadd9cce2f2b5873c64d3169c1da7e78fc1298e2
35806cf316f378a8ca98c0e244d149e052b1248d
/src/syscall/types_plan9.c
cd9e15fa8cf987b9770e54116d96e36d01f7b1b6
[ "BSD-3-Clause", "LicenseRef-scancode-google-patent-license-golang" ]
permissive
gomini/go-mips32
337000fe20d8c35e24245d3a9d205defddedad65
56b0efd6bad0c9554b5670fa6c3641282dd4d570
refs/heads/dev.github
2023-03-10T01:34:51.544213
2023-02-20T22:40:56
2023-02-20T22:40:56
43,116,287
155
52
BSD-3-Clause
2023-02-20T22:40:57
2015-09-25T07:30:35
Go
UTF-8
C
false
false
3,335
c
types_plan9.c
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore /* Input to godefs. See also mkerrors.sh and mkall.sh */ typedef unsigned short ushort; typedef unsigned char uchar; typedef unsigned long ulong; typedef unsigned int uint; typedef long long vlong; typedef unsigned long long uvlong; typedef int $_C_int; enum { OREAD = 0, // open for read OWRITE = 1, // write ORDWR = 2, // read and write OEXEC = 3, // execute, == read but check execute permission OTRUNC = 16, // or'ed in (except for exec), truncate file first OCEXEC = 32, // or'ed in, close on exec ORCLOSE = 64, // or'ed in, remove on close OEXCL = 0x1000, // or'ed in, exclusive use (create only) $O_RDONLY = OREAD, $O_WRONLY = OWRITE, $O_RDWR = ORDWR, $O_TRUNC = OTRUNC, $O_CLOEXEC = OCEXEC, $O_EXCL = OEXCL, $STATMAX = 65535U, $ERRMAX = 128, $MORDER = 0x0003, // mask for bits defining order of mounting $MREPL = 0x0000, // mount replaces object $MBEFORE = 0x0001, // mount goes before others in union directory $MAFTER = 0x0002, // mount goes after others in union directory $MCREATE = 0x0004, // permit creation in mounted directory $MCACHE = 0x0010, // cache some data $MMASK = 0x0017, // all bits on $RFNAMEG = (1<<0), $RFENVG = (1<<1), $RFFDG = (1<<2), $RFNOTEG = (1<<3), $RFPROC = (1<<4), $RFMEM = (1<<5), $RFNOWAIT = (1<<6), $RFCNAMEG = (1<<10), $RFCENVG = (1<<11), $RFCFDG = (1<<12), $RFREND = (1<<13), $RFNOMNT = (1<<14), // bits in Qid.type $QTDIR = 0x80, // type bit for directories $QTAPPEND = 0x40, // type bit for append only files $QTEXCL = 0x20, // type bit for exclusive use files $QTMOUNT = 0x10, // type bit for mounted channel $QTAUTH = 0x08, // type bit for authentication file $QTTMP = 0x04, // type bit for not-backed-up file $QTFILE = 0x00, // plain file // bits in Dir.mode $DMDIR = 0x80000000, // mode bit for directories $DMAPPEND = 0x40000000, // mode bit for append only files $DMEXCL = 0x20000000, // mode bit for exclusive use files $DMMOUNT = 0x10000000, // mode bit for mounted channel $DMAUTH = 0x08000000, // mode bit for authentication file $DMTMP = 0x04000000, // mode bit for non-backed-up files $DMREAD = 0x4, // mode bit for read permission $DMWRITE = 0x2, // mode bit for write permission $DMEXEC = 0x1, // mode bit for execute permission BIT8SZ = 1, BIT16SZ = 2, BIT32SZ = 4, BIT64SZ = 8, QIDSZ = BIT8SZ+BIT32SZ+BIT64SZ, // STATFIXLEN includes leading 16-bit count // The count, however, excludes itself; total size is BIT16SZ+count $STATFIXLEN = BIT16SZ+QIDSZ+5*BIT16SZ+4*BIT32SZ+1*BIT64SZ, // amount of fixed length data in a stat buffer }; struct Prof // Per process profiling { struct Plink *pp; // known to be 0(ptr) struct Plink *next; // known to be 4(ptr) struct Plink *last; struct Plink *first; ulong pid; ulong what; }; struct Tos { struct Prof prof; uvlong cyclefreq; // cycle clock frequency if there is one, 0 otherwise vlong kcycles; // cycles spent in kernel vlong pcycles; // cycles spent in process (kernel + user) ulong pid; // might as well put the pid here ulong clock; // top of stack is here }; typedef struct Prof $Prof; typedef struct Tos $Tos;
605f7cf4e94f1b7ad02869fe6752007b82d1c765
0744dcc5394cebf57ebcba343747af6871b67017
/apps/examples/board_specific_demo/ameba_cmsis_nn_demo/TestData/conv_1_x_n_1/output_ref_data.h
d62d4fe00ba2d2648e212caa4339ba663a7d2e40
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
Samsung/TizenRT
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
refs/heads/master
2023-08-31T08:59:33.327998
2023-08-08T06:09:20
2023-08-31T04:38:20
82,517,252
590
719
Apache-2.0
2023-09-14T06:54:49
2017-02-20T04:38:30
C
UTF-8
C
false
false
1,223
h
output_ref_data.h
/* * Copyright (C) 2010-2020 Arm Limited or its affiliates. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * 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 * * 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. */ // Generated by generate_test_data.py using TFL version 2.7.0 as reference. #pragma once #include <stdint.h> const q7_t conv_1_x_n_1_output_ref[48] = {-62, -35, -127, -96, 43, -63, -39, 26, -50, -82, 47, -31, -12, -43, -91, -79, -38, -100, -27, 32, -72, -49, 28, -127, -58, -31, -124, -73, 47, -83, -127, -4, -82, -64, 29, -81, -68, -9, -113, -22, -77, -77, -100, 23, -64, -59, 60, -5};
966aca8ccaee4ec8c4174cfe563190a1b6935984
7df190df28da7e4ff166e55dc8ce780f11236a9f
/src/router/open-plc-utils/tools/emalloc.c
eefb17abb77da3b57b64b91768d7c537afd65f56
[ "BSD-3-Clause-Clear" ]
permissive
mirror/dd-wrt
25416946e6132aa54b35809de61834a1825a9a36
8f2934a5a2adfbb59b471375aa3a38de5d036531
refs/heads/master
2023-08-31T14:54:47.496685
2023-08-30T17:40:54
2023-08-30T17:40:54
7,470,282
520
281
null
2023-05-29T20:56:24
2013-01-06T17:21:29
null
UTF-8
C
false
false
866
c
emalloc.c
/*====================================================================* * * void * emalloc (size_t length) * * error.h * * attempt to allocate memory using malloc(); return the memory address * on success; print an error message on stderr and then terminate the * program on failure; * * Motley Tools by Charles Maier <cmaier@cmassoc.net>; * Copyright (c) 2001-2006 by Charles Maier Associates; * Licensed under the Internet Software Consortium License; * *--------------------------------------------------------------------*/ #ifndef EMALLOC_SOURCE #define EMALLOC_SOURCE #include <stdio.h> #include <stdlib.h> #include <errno.h> #include "../tools/error.h" void * emalloc (size_t length) { void * memory = malloc (length); if (!memory) { error (1, errno, "need %lu bytes", (long)(length)); } return (memory); } #endif
1205442667f65146c27a27448d07782eb6acd24e
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/arm/mach-mvebu/platsmp.c
875ea748391ca87adfbc0756837da2bad6584be8
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
3,036
c
platsmp.c
/* * Symmetric Multi Processing (SMP) support for Armada XP * * Copyright (C) 2012 Marvell * * Lior Amsalem <alior@marvell.com> * Yehuda Yitschak <yehuday@marvell.com> * Gregory CLEMENT <gregory.clement@free-electrons.com> * Thomas Petazzoni <thomas.petazzoni@free-electrons.com> * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. * * The Armada XP SoC has 4 ARMv7 PJ4B CPUs running in full HW coherency * This file implements the routines for preparing the SMP infrastructure * and waking up the secondary CPUs */ #include <linux/init.h> #include <linux/smp.h> #include <linux/clk.h> #include <linux/of.h> #include <linux/mbus.h> #include <asm/cacheflush.h> #include <asm/smp_plat.h> #include "common.h" #include "armada-370-xp.h" #include "pmsu.h" #include "coherency.h" void __init set_secondary_cpus_clock(void) { int thiscpu; unsigned long rate; struct clk *cpu_clk = NULL; struct device_node *np = NULL; thiscpu = smp_processor_id(); for_each_node_by_type(np, "cpu") { int err; int cpu; err = of_property_read_u32(np, "reg", &cpu); if (WARN_ON(err)) return; if (cpu == thiscpu) { cpu_clk = of_clk_get(np, 0); break; } } if (WARN_ON(IS_ERR(cpu_clk))) return; clk_prepare_enable(cpu_clk); rate = clk_get_rate(cpu_clk); /* set all the other CPU clk to the same rate than the boot CPU */ for_each_node_by_type(np, "cpu") { int err; int cpu; err = of_property_read_u32(np, "reg", &cpu); if (WARN_ON(err)) return; if (cpu != thiscpu) { cpu_clk = of_clk_get(np, 0); clk_set_rate(cpu_clk, rate); } } } static void __cpuinit armada_xp_secondary_init(unsigned int cpu) { armada_xp_mpic_smp_cpu_init(); } static int __cpuinit armada_xp_boot_secondary(unsigned int cpu, struct task_struct *idle) { pr_info("Booting CPU %d\n", cpu); armada_xp_boot_cpu(cpu, armada_xp_secondary_startup); return 0; } static void __init armada_xp_smp_init_cpus(void) { unsigned int i, ncores; ncores = coherency_get_cpu_count(); /* Limit possible CPUs to defconfig */ if (ncores > nr_cpu_ids) { pr_warn("SMP: %d CPUs physically present. Only %d configured.", ncores, nr_cpu_ids); pr_warn("Clipping CPU count to %d\n", nr_cpu_ids); ncores = nr_cpu_ids; } for (i = 0; i < ncores; i++) set_cpu_possible(i, true); set_smp_cross_call(armada_mpic_send_doorbell); } void __init armada_xp_smp_prepare_cpus(unsigned int max_cpus) { set_secondary_cpus_clock(); flush_cache_all(); set_cpu_coherent(cpu_logical_map(smp_processor_id()), 0); mvebu_mbus_add_window("bootrom", 0xfff00000, SZ_1M); } struct smp_operations armada_xp_smp_ops __initdata = { .smp_init_cpus = armada_xp_smp_init_cpus, .smp_prepare_cpus = armada_xp_smp_prepare_cpus, .smp_secondary_init = armada_xp_secondary_init, .smp_boot_secondary = armada_xp_boot_secondary, #ifdef CONFIG_HOTPLUG_CPU .cpu_die = armada_xp_cpu_die, #endif };
440b7863bc99f1bbbf5136d0d665913431f6584a
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
/PWGPP/T0/drawPerformanceT0QATrends.C
9c2ba1c41a8d24bc385933616d13d39717d6498b
[]
permissive
alisw/AliPhysics
91bf1bd01ab2af656a25ff10b25e618a63667d3e
5df28b2b415e78e81273b0d9bf5c1b99feda3348
refs/heads/master
2023-08-31T20:41:44.927176
2023-08-31T14:51:12
2023-08-31T14:51:12
61,661,378
129
1,150
BSD-3-Clause
2023-09-14T18:48:45
2016-06-21T19:31:29
C++
UTF-8
C
false
false
12,195
c
drawPerformanceT0QATrends.C
TGraphErrors * MakeGraphSparse(TTree * tree, const Char_t * expr="mean-fdelta:run", const Char_t * cut="isTPC&&ptype==0&&theta>0"){ // Format of expr: Var:Error:Run // // Make a sparse draw of the variables // Format of expr : Var:Error:Run // const Int_t entries = tree->Draw(expr,cut,"goff"); if (entries<=0) return 0x0; Double_t *graphX, *graphY, *graphError; //check whether error argument exists in expr if(!tree->GetV3()){ graphX = tree->GetV2(); graphY = tree->GetV1(); } else{ graphX = tree->GetV3(); graphY = tree->GetV1(); graphError = tree->GetV2(); } // sort according to run number Int_t *index = new Int_t[entries]; TMath::Sort(entries,graphX,index,false); // define arrays for the new graph Double_t *tempArray = new Double_t[entries]; Double_t *xError = new Double_t[entries]; Double_t *yError = new Double_t[entries]; Int_t *vrun = new Int_t[entries]; Double_t count = 0.5; // evaluate arrays for the new graph accroding to the run-number Int_t icount=0; tempArray[index[0]] = count; xError[0] = 0; yError[0] = 0; if(tree->GetV3()) yError[index[0]] = graphError[index[0]]; vrun[0] = graphX[index[0]]; // loop the rest entries for(Int_t i=1;i<entries;i++){ xError[i] = 0; yError[i] = 0; if(tree->GetV3()) yError[i] = graphError[index[i]]; if(graphX[index[i]]==graphX[index[i-1]]) tempArray[index[i]] = count; else if((graphX[index[i]]!=graphX[index[i-1]])){ count++; icount++; tempArray[index[i]] = count; vrun[icount]=graphX[index[i]]; } } // count the number of xbins (run-wise) for the new graph const Int_t newNbins = int(count+0.5); Double_t *newBins = new Double_t[newNbins+1]; for(Int_t i=0; i<=count+1;i++){ newBins[i] = i; } // define and fill the new graph TGraphErrors *graphNew = new TGraphErrors(entries,tempArray,graphY,xError,yError); graphNew->GetXaxis()->Set(newNbins,newBins); // set the bins for the x-axis Char_t xName[50]; for(Int_t i=0;i<count;i++){ sprintf(xName,"%d",Int_t(vrun[i])); graphNew->GetXaxis()->SetBinLabel(i+1,xName); } graphNew->GetHistogram()->SetTitle(""); // memory clearing delete [] xError; delete [] yError; delete [] tempArray; delete [] index; delete [] newBins; delete [] vrun; return graphNew; } //------------------------------------------------------------------------------------------------ void drawPerformanceT0QATrends(const char* inFile = "trending.root", const char* runType="pp") { // // gROOT->Reset(); gROOT->SetStyle("Plain"); gStyle->SetPalette(1); gStyle->SetLabelSize(0.04,"x"); // open input file // TFile *file = TFile::Open(inFile); if(!file) return; file->cd(); TTree *tree = (TTree*)file->Get("trending"); if(!tree) return; int const entries = tree->GetEntries(); cout<<"number of entries "<<entries<<endl; TH1F *frame = new TH1F(); float norm_runs = 10.0; if(entries<8) norm_runs =10.0; else if(entries>=8&&entries<16) norm_runs =20.0; else norm_runs =50.0; int const canvas_width = int(((entries*1.0)/norm_runs)*2000.0); if(entries>50){ gStyle->SetTickLength(0.03*norm_runs/(entries*1.0),"Y"); gStyle->SetTitleYOffset((norm_runs/(entries*1.0))*0.8); gStyle->SetPadLeftMargin(0.1*norm_runs/(entries*1.0)); gStyle->SetPadRightMargin(0.1*norm_runs/(entries*1.0)); } //Define ranges of you trending plots double resolutionMin = 10, resolutionMax = 100; // OR A - OR C double oraplusorcMin = -100, oraplusorcMax = 100; // OR A + OR CA double oraMin = -100, oraMax = 100; // OR A double orcMin = -100, orcMax = 100; // OR C // double amplMin =0, amplMax =3 ; // amplitude in each PMT // double timeMin = 2900, timeMax =3300 ; // amplitude in each PMT //-----> add ranges of your new trending plot TCanvas *c1 = new TCanvas("can","can",canvas_width,500); c1->SetGridy(1); c1->SetGridx(1); c1->SetBottomMargin(0.17); /****** T0 ORA+ORC ******/ double orMinCalib = -20, orMaxCalib = 20; // OR limits for GOOD run with calibration double orMinNoCalib = -40, orMaxNoCalib = 40; // OR limits for GOOD run without calibration TGraphErrors *grSum = MakeGraphSparse(tree,"tzeroOrAPlusOrC:run",""); grSum->SetMarkerStyle(20); grSum->SetMarkerSize(1.0); grSum->SetMarkerColor(2); TGraphErrors *grORA = MakeGraphSparse(tree,"tzeroOrA:run",""); grORA->SetMarkerStyle(28); grORA->SetMarkerSize(1.0); grORA->SetMarkerColor(4); TGraphErrors *grORC = MakeGraphSparse(tree,"tzeroOrC:run",""); grORC->SetMarkerStyle(25); grORC->SetMarkerSize(1.0); grORC->SetMarkerColor(1); grSum->GetHistogram()->SetYTitle("mean [ps]"); grSum->GetHistogram()->SetTitle("T0 ORA, ORC and (ORA+ORC)/2"); grSum->GetHistogram()->SetMinimum(oraplusorcMin); grSum->GetHistogram()->SetMaximum(oraplusorcMax); int nRuns = grSum->GetN(); double *x = grSum->GetX(); double min = x[0]; double max = x[0]; for(int irun =1; irun<nRuns;irun++){ if(min > x[irun] && x[irun]>0) min = x[irun]; if(max < x[irun]) max = x[irun]; } min-=0.5; max+=0.5; TBox* outOfLimits = new TBox(min,oraplusorcMin,max,oraplusorcMax); outOfLimits->SetFillColor(kOrange); TBox* limitsNoCalib = new TBox(min,orMinNoCalib,max,orMaxNoCalib); limitsNoCalib->SetFillColor(kYellow); TBox* limitsCalib = new TBox(min,orMinCalib,max,orMaxCalib); limitsCalib->SetFillColor(kTeal); TLine* limitsOR[4]; limitsOR[0] = new TLine(min,orMinCalib,max,orMinCalib); limitsOR[0]->SetLineColor(kGreen);limitsOR[0]->SetLineWidth(3); limitsOR[1] = new TLine(min,orMaxCalib,max,orMaxCalib); limitsOR[1]->SetLineColor(kGreen);limitsOR[1]->SetLineWidth(3); limitsOR[2] = new TLine(min,orMinNoCalib,max,orMinNoCalib);limitsOR[2]->SetLineColor(kRed); limitsOR[2]->SetLineWidth(3); limitsOR[3] = new TLine(min,orMaxNoCalib,max,orMaxNoCalib);limitsOR[3]->SetLineColor(kRed); limitsOR[3]->SetLineWidth(3); grSum->Draw("AP"); outOfLimits->Draw("same"); limitsNoCalib->Draw("same"); limitsCalib->Draw("same"); // for(Int_t i=0;i<nRuns-1;i++) // { // ((TLine*)(TLine::DrawLine(min,oraplusorcMin,min,oraplusorcMax)));//x[i]+0.5,oraplusorcMin,x[i]+0.5,oraplusorcMax)));//->SetLineStyle(2); // } grSum->Draw("psame"); grORA->Draw("psame"); grORC->Draw("psame"); for(Int_t i=0;i<4;i++)limitsOR[i]->Draw("same"); TLegend *leg = new TLegend(0.1,0.85,0.3,0.95," ","brNDC"); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetTextSize(0.05);leg->SetNColumns(3);leg->SetColumnSeparation(1); leg->AddEntry(grORA,"ORA","p"); leg->AddEntry(grORC,"ORC","p"); leg->AddEntry(grSum,"(ORA+ORC)/2","p"); leg->Draw(); grSum->GetXaxis()->LabelsOption("v"); c1->SaveAs("meanT0OrAPlusOrC_vs_run.png"); /****** T0 Resolution ******/ TGraphErrors *gr = MakeGraphSparse(tree,"resolution:run",""); gr->SetMarkerStyle(20); gr->SetMarkerSize(1.0); gr->SetMarkerColor(2); gr->GetHistogram()->SetMinimum(resolutionMin); gr->GetHistogram()->SetMaximum(resolutionMax); gr->Draw("AP"); gr->GetXaxis()->LabelsOption("v"); gr->GetHistogram()->SetYTitle("sigma [ps]"); gr->GetHistogram()->SetTitle("T0 resolution (ORA -ORC)/2"); c1->SaveAs("sigmaResolutionT0_vs_run.png"); /****** Mean Amplitude in PMT ******/ const int kNPMTs = 24; char name[200]; for(int ipmt=1;ipmt<=kNPMTs; ipmt++){ sprintf(name,"amplPMT%d:run",ipmt); TString cutamp = Form("amplPMT%i>0",ipmt); TGraphErrors *gramp = MakeGraphSparse(tree, name, cutamp.Data()); if (!gramp) continue; // gr = MakeGraphSparse(tree,name,""); gramp->SetMarkerStyle(20); gramp->SetMarkerSize(1.0); gramp->SetMarkerColor(6); gramp->GetHistogram()->SetYTitle("mean"); gramp->GetHistogram()->SetTitle(Form("Amplitude PMT%d", ipmt)); int nRuns = gramp->GetN(); double *y = gramp->GetY(); double min = y[0]; double max = y[0]; for (int irun = 1; irun < nRuns; irun++) { if (min > y[irun] & y[irun] > 0) min = y[irun]; if (max < y[irun]) max = y[irun]; } // amplMin = min - 2; // amplMax = max + 2; // gr->GetHistogram()->SetMinimum(amplMin); // gr->GetHistogram()->SetMaximum(amplMax); gramp->Draw("AP"); gramp->GetXaxis()->LabelsOption("v"); c1->SaveAs(Form("meanAmplPMT%d_vs_run.png", ipmt)); } /****** Mean Time in PMT ******/ for (int ipmt = 1; ipmt <= kNPMTs; ipmt++) { sprintf(name, "timePMT%d:run", ipmt); TString cut = Form("timePMT%i>0", ipmt); TGraphErrors *grtime = MakeGraphSparse(tree, name, cut.Data()); if (!grtime) continue; // regular run int nRuns = grtime->GetN(); double *y = grtime->GetY(); double min = y[0]; double max = y[0]; for (int irun = 1; irun < nRuns; irun++) { if (min > y[irun] && y[irun] > 0) min = y[irun]; if (max < y[irun]) max = y[irun]; } grtime->SetMarkerStyle(20); grtime->SetMarkerSize(1.0); grtime->SetMarkerColor(2); grtime->GetHistogram()->SetYTitle("mean [channels]"); grtime->GetHistogram()->SetTitle(Form("Time PMT%d", ipmt)); // gr->GetHistogram()->SetMinimum(timeMin); // gr->GetHistogram()->SetMaximum(timeMax); grtime->GetXaxis()->LabelsOption("v"); grtime->Draw("AP"); TLegend *leg = new TLegend(0.1, 0.85, 0.3, 0.95, " ", "brNDC"); leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetTextSize(0.05); leg->SetNColumns(3); leg->AddEntry(grtime, "mean time", "p"); leg->Draw(); c1->SaveAs(Form("meanTimePMT%d_vs_run.png", ipmt)); } // TGraphErrors *grEfficiencySPD = // MakeGraphSparse(tree,"efficiencySPD:run",""); // grEfficiencySPD->SetMarkerStyle(25); // grEfficiencySPD->SetMarkerSize(1.0); // grEfficiencySPD->SetMarkerColor(1); // grEfficiencySPD->GetXaxis()->LabelsOption("v"); // grEfficiencySPD->SetTitle("T0 to SPD // ratio;run;Nevts_{T0}/Nevts_{SPD}"); grEfficiencySPD->Draw("AP"); // c1->SaveAs("efficiencyT0toSPD_vs_run.gif"); if (tree->GetBranch("efficiency0TVX_CINT7")) { TGraphErrors *grEfficiency0TVX_CINT7 = MakeGraphSparse(tree, "efficiency0TVX_CINT7:run", ""); if (grEfficiency0TVX_CINT7) { grEfficiency0TVX_CINT7->GetYaxis()->SetRangeUser(0., 1.); grEfficiency0TVX_CINT7->SetMarkerStyle(25); grEfficiency0TVX_CINT7->SetMarkerSize(1.0); grEfficiency0TVX_CINT7->SetMarkerColor(1); grEfficiency0TVX_CINT7->GetXaxis()->LabelsOption("v"); grEfficiency0TVX_CINT7->SetTitle("T0 to V0 ratio;run;0TVX/CINT7"); grEfficiency0TVX_CINT7->Draw("AP"); c1->SaveAs("efficiencyT0toV0_vs_run.png"); } } if ( tree->GetBranch("efficiency0TVX_CADAND")) { TGraphErrors *grEfficiency0TVX_CADAND = MakeGraphSparse(tree, "efficiency0TVX_CADAND:run", ""); if (grEfficiency0TVX_CADAND) { grEfficiency0TVX_CADAND->GetYaxis()->SetRangeUser(0., 1.); grEfficiency0TVX_CADAND->SetMarkerStyle(22); grEfficiency0TVX_CADAND->SetMarkerSize(1.0); grEfficiency0TVX_CADAND->SetMarkerColor(2); grEfficiency0TVX_CADAND->GetXaxis()->LabelsOption("v"); grEfficiency0TVX_CADAND->SetTitle("T0 to AD ratio;run;0TVX/CADAND"); grEfficiency0TVX_CADAND->Draw("AP"); c1->SaveAs("efficiencyT0toAD_vs_run.png"); } } // leg->Clear(); // TLegend *leg = new TLegend(0.1,0.8,0.3,0.95," ","efficiency"); // leg->SetFillStyle(0); leg->SetBorderSize(0); // leg->SetTextSize(0.05);leg->SetNColumns(1);//leg->SetColumnSeparation(1); // leg->AddEntry(grEfficiency0TVX_CINT7,"T0 to V0 ratio","p"); // leg->AddEntry(grEfficiency0TVX_CADAND,"T0 to AD ratio","p"); // leg->AddEntry(grSum,"(ORA+ORC)/2","p"); // leg->Draw(); // c1->SaveAs("efficiency_vs_run.gif"); //-----> draw your new trending plot here c1->Close(); }
d7be18ef38594714c598a8201d58b924fa7efcb9
aa3befea459382dc5c01c925653d54f435b3fb0f
/include/inttypes.h
056ad4ea6243d3f03d7466cb0220be6600f1e902
[ "MIT-open-group", "BSD-3-Clause", "HPND-sell-variant", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "MIT-0", "LicenseRef-scancode-bsd-atmel", "LicenseRef-scancode-gary-s-brown", "LicenseRef-scancode-proprietary-license", "SunPro", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "LicenseRef-scancode-other-permissive", "HPND", "ISC", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "GPL-1.0-or-later", "CC-BY-2.0", "CC-BY-4.0" ]
permissive
apache/nuttx
14519a7bff4a87935d94fb8fb2b19edb501c7cec
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
refs/heads/master
2023-08-25T06:55:45.822534
2023-08-23T16:03:31
2023-08-24T21:25:47
228,103,273
407
241
Apache-2.0
2023-09-14T18:26:05
2019-12-14T23:27:55
C
UTF-8
C
false
false
9,014
h
inttypes.h
/**************************************************************************** * include/inttypes.h * * 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 __INCLUDE_INTTYPES_H #define __INCLUDE_INTTYPES_H /**************************************************************************** * Included Files ****************************************************************************/ #include <stddef.h> /* for wchar_t */ /* Notes from www.opengroup.org: * * "The <inttypes.h> header shall include the <stdint.h> header." */ #include <stdint.h> #include <arch/inttypes.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* "The following macros shall be defined. Each expands to a character string * literal containing a conversion specifier, possibly modified by a length * modifier, suitable for use within the format argument of a formatted * input/output function when converting the corresponding integer type. * These macros have the general form of PRI (character string literals for * the fprintf() and fwprintf() family of functions) or SCN (character * string literals for the fscanf() and fwscanf() family of functions), * followed by the conversion specifier, followed by a name corresponding * to a similar type name in <stdint.h>. In these names, N represents the * width of the type as described in <stdint.h>. For example, PRIdFAST32 * can be used in a format string to print the value of an integer of type * int_fast32_t. * * "The fprintf() macros for signed integers are: * * PRIdN * PRIdLEASTN * PRIdFASTN * PRIdMAX * PRIdPTR * * PRIiN * PRIiLEASTN * PRIiFASTN * PRIiMAX * PRIiPTR * * "The fprintf() macros for unsigned integers are: * * PRIoN * PRIoLEASTN * PRIoFASTN * PRIoMAX * PRIoPTR * * PRIuN * PRIuLEASTN * PRIuFASTN * PRIuMAX * PRIuPTR * * PRIxN * PRIxLEASTN * PRIxFASTN * PRIxMAX * PRIxPTR * * PRIXN * PRIXLEASTN * PRIXFASTN * PRIXMAX * PRIXPTR * * "The fscanf() macros for signed integers are: * * SCNdN * SCNdLEASTN * SCNdFASTN * SCNdMAX * SCNdPTR * * SCNiN * SCNiLEASTN * SCNiFASTN * SCNiMAX * SCNiPTR * * "The fscanf() macros for unsigned integers are: * * SCNoN * SCNoLEASTN * SCNoFASTN * SCNoMAX * SCNoPTR * * SCNuN * SCNuLEASTN * SCNuFASTN * SCNuMAX * SCNuPTR * * SCNxN * SCNxLEASTN * SCNxFASTN * SCNxMAX * SCNxPTR * * "For each type that the implementation provides in <stdint.h>, the * corresponding fprintf() and fwprintf() macros shall be defined and the * corresponding fscanf() and fwscanf() macros shall be defined unless the * implementation does not have a suitable modifier for the type. */ /* On NuttX, least and fast types are aliases of the exact type. * (See stdint.h) */ #define PRIdLEAST8 PRId8 #define PRIdLEAST16 PRId16 #define PRIdLEAST32 PRId32 #if defined(PRId64) #define PRIdLEAST64 PRId64 #endif #define PRIdFAST8 PRId8 #define PRIdFAST16 PRId16 #define PRIdFAST32 PRId32 #if defined(PRId64) #define PRIdFAST64 PRId64 #endif #define PRIiLEAST8 PRIi8 #define PRIiLEAST16 PRIi16 #define PRIiLEAST32 PRIi32 #if defined(PRIi64) #define PRIiLEAST64 PRIi64 #endif #define PRIiFAST8 PRIi8 #define PRIiFAST16 PRIi16 #define PRIiFAST32 PRIi32 #if defined(PRIi64) #define PRIiFAST64 PRIi64 #endif #define PRIoLEAST8 PRIo8 #define PRIoLEAST16 PRIo16 #define PRIoLEAST32 PRIo32 #if defined(PRIo64) #define PRIoLEAST64 PRIo64 #endif #define PRIoFAST8 PRIo8 #define PRIoFAST16 PRIo16 #define PRIoFAST32 PRIo32 #if defined(PRIo64) #define PRIoFAST64 PRIo64 #endif #define PRIuLEAST8 PRIu8 #define PRIuLEAST16 PRIu16 #define PRIuLEAST32 PRIu32 #if defined(PRIu64) #define PRIuLEAST64 PRIu64 #endif #define PRIuFAST8 PRIu8 #define PRIuFAST16 PRIu16 #define PRIuFAST32 PRIu32 #if defined(PRIu64) #define PRIuFAST64 PRIu64 #endif #define PRIxLEAST8 PRIx8 #define PRIxLEAST16 PRIx16 #define PRIxLEAST32 PRIx32 #if defined(PRIx64) #define PRIxLEAST64 PRIx64 #endif #define PRIxFAST8 PRIx8 #define PRIxFAST16 PRIx16 #define PRIxFAST32 PRIx32 #if defined(PRIx64) #define PRIxFAST64 PRIx64 #endif #define PRIXLEAST8 PRIX8 #define PRIXLEAST16 PRIX16 #define PRIXLEAST32 PRIX32 #if defined(PRIX64) #define PRIXLEAST64 PRIX64 #endif #define PRIXFAST8 PRIX8 #define PRIXFAST16 PRIX16 #define PRIXFAST32 PRIX32 #if defined(PRIX64) #define PRIXFAST64 PRIX64 #endif #define SCNdLEAST8 SCNd8 #define SCNdLEAST16 SCNd16 #define SCNdLEAST32 SCNd32 #if defined(SCNd64) #define SCNdLEAST64 SCNd64 #endif #define SCNdFAST8 SCNd8 #define SCNdFAST16 SCNd16 #define SCNdFAST32 SCNd32 #if defined(SCNd64) #define SCNdFAST64 SCNd64 #endif #define SCNiLEAST8 SCNi8 #define SCNiLEAST16 SCNi16 #define SCNiLEAST32 SCNi32 #if defined(SCNi64) #define SCNiLEAST64 SCNi64 #endif #define SCNiFAST8 SCNi8 #define SCNiFAST16 SCNi16 #define SCNiFAST32 SCNi32 #if defined(SCNi64) #define SCNiFAST64 SCNi64 #endif #define SCNoLEAST8 SCNo8 #define SCNoLEAST16 SCNo16 #define SCNoLEAST32 SCNo32 #if defined(SCNo64) #define SCNoLEAST64 SCNo64 #endif #define SCNoFAST8 SCNo8 #define SCNoFAST16 SCNo16 #define SCNoFAST32 SCNo32 #if defined(SCNo64) #define SCNoFAST64 SCNo64 #endif #define SCNuLEAST8 SCNu8 #define SCNuLEAST16 SCNu16 #define SCNuLEAST32 SCNu32 #if defined(SCNu64) #define SCNuLEAST64 SCNu64 #endif #define SCNuFAST8 SCNu8 #define SCNuFAST16 SCNu16 #define SCNuFAST32 SCNu32 #if defined(SCNu64) #define SCNuFAST64 SCNu64 #endif #define SCNxLEAST8 SCNx8 #define SCNxLEAST16 SCNx16 #define SCNxLEAST32 SCNx32 #if defined(SCNx64) #define SCNxLEAST64 SCNx64 #endif #define SCNxFAST8 SCNx8 #define SCNxFAST16 SCNx16 #define SCNxFAST32 SCNx32 #if defined(SCNx64) #define SCNxFAST64 SCNx64 #endif /* intmax_t/uintmax_t */ #define PRIdMAX "jd" #define PRIiMAX "ji" #define PRIoMAX "jo" #define PRIuMAX "ju" #define PRIxMAX "jx" #define PRIXMAX "jX" #define SCNdMAX "jd" #define SCNiMAX "ji" #define SCNoMAX "jo" #define SCNuMAX "ju" #define SCNxMAX "jx" /* off_t */ #if defined(CONFIG_FS_LARGEFILE) #define PRIdOFF PRId64 #define PRIiOFF PRIi64 #define PRIoOFF PRIo64 #define PRIuOFF PRIu64 #define PRIxOFF PRIx64 #define PRIXOFF PRIX64 #define SCNdOFF SCNd64 #define SCNiOFF SCNi64 #define SCNoOFF SCNo64 #define SCNuOFF SCNu64 #define SCNxOFF SCNx64 #else #define PRIdOFF PRId32 #define PRIiOFF PRIi32 #define PRIoOFF PRIo32 #define PRIuOFF PRIu32 #define PRIxOFF PRIx32 #define PRIXOFF PRIX32 #define SCNdOFF SCNd32 #define SCNiOFF SCNi32 #define SCNoOFF SCNo32 #define SCNuOFF SCNu32 #define SCNxOFF SCNx32 #endif /**************************************************************************** * Type Definitions ****************************************************************************/ /* "The <inttypes.h> header shall include a definition of at least the * following type: * * imaxdiv_t * Structure type that is the type of the value returned by the imaxdiv() * function. */ typedef void *imaxdiv_t; /* Dummy type since imaxdiv is not yet supported */ /**************************************************************************** * Public Function Prototypes ****************************************************************************/ #ifdef __cplusplus #define EXTERN extern "C" extern "C" { #else #define EXTERN extern #endif /* "The following shall be declared as functions and may also be defined as * macros. Function prototypes shall be provided." */ intmax_t imaxabs(intmax_t j); imaxdiv_t imaxdiv(intmax_t number, intmax_t denom); intmax_t strtoimax(FAR const char *nptr, FAR char **endptr, int base); uintmax_t strtoumax(FAR const char *nptr, FAR char **endptr, int base); intmax_t wcstoimax(FAR const wchar_t *nptr, FAR wchar_t **endptr, int base); uintmax_t wcstoumax(FAR const wchar_t *nptr, FAR wchar_t **endptr, int base); #undef EXTERN #ifdef __cplusplus } #endif #endif /* __INCLUDE_INTTYPES_H */
31d408b462f4c5f9011c2ae5f6916938bd6a7879
55540f3e86f1d5d86ef6b5d295a63518e274efe3
/toolchain/riscv/Linux/lib/gcc/riscv64-unknown-elf/10.2.0/plugin/include/hsa-brig-format.h
e16f469473eacd45455450ce3d1adf2642f3a347
[ "Apache-2.0" ]
permissive
bouffalolab/bl_iot_sdk
bc5eaf036b70f8c65dd389439062b169f8d09daa
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
refs/heads/master
2023-08-31T03:38:03.369853
2023-08-16T08:50:33
2023-08-18T09:13:27
307,347,250
244
101
Apache-2.0
2023-08-28T06:29:02
2020-10-26T11:16:30
C
UTF-8
C
false
false
29,547
h
hsa-brig-format.h
/* HSA BRIG (binary representation of HSAIL) 1.0.1 representation description. Copyright (C) 2016-2020 Free Software Foundation, Inc. This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. The contents of the file was created by extracting data structures, enum, typedef and other definitions from HSA Programmer's Reference Manual Version 1.0.1 (http://www.hsafoundation.com/standards/). HTML version is provided on the following link: http://www.hsafoundation.com/html/Content/PRM/Topics/PRM_title_page.htm */ #ifndef HSA_BRIG_FORMAT_H #define HSA_BRIG_FORMAT_H struct BrigModuleHeader; typedef uint16_t BrigKind16_t; typedef uint32_t BrigVersion32_t; typedef BrigModuleHeader *BrigModule_t; typedef uint32_t BrigDataOffset32_t; typedef uint32_t BrigCodeOffset32_t; typedef uint32_t BrigOperandOffset32_t; typedef BrigDataOffset32_t BrigDataOffsetString32_t; typedef BrigDataOffset32_t BrigDataOffsetCodeList32_t; typedef BrigDataOffset32_t BrigDataOffsetOperandList32_t; typedef uint8_t BrigAlignment8_t; enum BrigAlignment { BRIG_ALIGNMENT_NONE = 0, BRIG_ALIGNMENT_1 = 1, BRIG_ALIGNMENT_2 = 2, BRIG_ALIGNMENT_4 = 3, BRIG_ALIGNMENT_8 = 4, BRIG_ALIGNMENT_16 = 5, BRIG_ALIGNMENT_32 = 6, BRIG_ALIGNMENT_64 = 7, BRIG_ALIGNMENT_128 = 8, BRIG_ALIGNMENT_256 = 9 }; typedef uint8_t BrigAllocation8_t; enum BrigAllocation { BRIG_ALLOCATION_NONE = 0, BRIG_ALLOCATION_PROGRAM = 1, BRIG_ALLOCATION_AGENT = 2, BRIG_ALLOCATION_AUTOMATIC = 3 }; typedef uint8_t BrigAluModifier8_t; enum BrigAluModifierMask { BRIG_ALU_FTZ = 1 }; typedef uint8_t BrigAtomicOperation8_t; enum BrigAtomicOperation { BRIG_ATOMIC_ADD = 0, BRIG_ATOMIC_AND = 1, BRIG_ATOMIC_CAS = 2, BRIG_ATOMIC_EXCH = 3, BRIG_ATOMIC_LD = 4, BRIG_ATOMIC_MAX = 5, BRIG_ATOMIC_MIN = 6, BRIG_ATOMIC_OR = 7, BRIG_ATOMIC_ST = 8, BRIG_ATOMIC_SUB = 9, BRIG_ATOMIC_WRAPDEC = 10, BRIG_ATOMIC_WRAPINC = 11, BRIG_ATOMIC_XOR = 12, BRIG_ATOMIC_WAIT_EQ = 13, BRIG_ATOMIC_WAIT_NE = 14, BRIG_ATOMIC_WAIT_LT = 15, BRIG_ATOMIC_WAIT_GTE = 16, BRIG_ATOMIC_WAITTIMEOUT_EQ = 17, BRIG_ATOMIC_WAITTIMEOUT_NE = 18, BRIG_ATOMIC_WAITTIMEOUT_LT = 19, BRIG_ATOMIC_WAITTIMEOUT_GTE = 20 }; struct BrigBase { uint16_t byteCount; BrigKind16_t kind; }; typedef uint8_t BrigCompareOperation8_t; enum BrigCompareOperation { BRIG_COMPARE_EQ = 0, BRIG_COMPARE_NE = 1, BRIG_COMPARE_LT = 2, BRIG_COMPARE_LE = 3, BRIG_COMPARE_GT = 4, BRIG_COMPARE_GE = 5, BRIG_COMPARE_EQU = 6, BRIG_COMPARE_NEU = 7, BRIG_COMPARE_LTU = 8, BRIG_COMPARE_LEU = 9, BRIG_COMPARE_GTU = 10, BRIG_COMPARE_GEU = 11, BRIG_COMPARE_NUM = 12, BRIG_COMPARE_NAN = 13, BRIG_COMPARE_SEQ = 14, BRIG_COMPARE_SNE = 15, BRIG_COMPARE_SLT = 16, BRIG_COMPARE_SLE = 17, BRIG_COMPARE_SGT = 18, BRIG_COMPARE_SGE = 19, BRIG_COMPARE_SGEU = 20, BRIG_COMPARE_SEQU = 21, BRIG_COMPARE_SNEU = 22, BRIG_COMPARE_SLTU = 23, BRIG_COMPARE_SLEU = 24, BRIG_COMPARE_SNUM = 25, BRIG_COMPARE_SNAN = 26, BRIG_COMPARE_SGTU = 27 }; typedef uint16_t BrigControlDirective16_t; enum BrigControlDirective { BRIG_CONTROL_NONE = 0, BRIG_CONTROL_ENABLEBREAKEXCEPTIONS = 1, BRIG_CONTROL_ENABLEDETECTEXCEPTIONS = 2, BRIG_CONTROL_MAXDYNAMICGROUPSIZE = 3, BRIG_CONTROL_MAXFLATGRIDSIZE = 4, BRIG_CONTROL_MAXFLATWORKGROUPSIZE = 5, BRIG_CONTROL_REQUIREDDIM = 6, BRIG_CONTROL_REQUIREDGRIDSIZE = 7, BRIG_CONTROL_REQUIREDWORKGROUPSIZE = 8, BRIG_CONTROL_REQUIRENOPARTIALWORKGROUPS = 9 }; typedef uint32_t BrigExceptions32_t; enum BrigExceptionsMask { BRIG_EXCEPTIONS_INVALID_OPERATION = 1 << 0, BRIG_EXCEPTIONS_DIVIDE_BY_ZERO = 1 << 1, BRIG_EXCEPTIONS_OVERFLOW = 1 << 2, BRIG_EXCEPTIONS_UNDERFLOW = 1 << 3, BRIG_EXCEPTIONS_INEXACT = 1 << 4, BRIG_EXCEPTIONS_FIRST_USER_DEFINED = 1 << 16 }; typedef uint8_t BrigExecutableModifier8_t; enum BrigExecutableModifierMask { BRIG_EXECUTABLE_DEFINITION = 1 }; typedef uint8_t BrigImageChannelOrder8_t; enum BrigImageChannelOrder { BRIG_CHANNEL_ORDER_A = 0, BRIG_CHANNEL_ORDER_R = 1, BRIG_CHANNEL_ORDER_RX = 2, BRIG_CHANNEL_ORDER_RG = 3, BRIG_CHANNEL_ORDER_RGX = 4, BRIG_CHANNEL_ORDER_RA = 5, BRIG_CHANNEL_ORDER_RGB = 6, BRIG_CHANNEL_ORDER_RGBX = 7, BRIG_CHANNEL_ORDER_RGBA = 8, BRIG_CHANNEL_ORDER_BGRA = 9, BRIG_CHANNEL_ORDER_ARGB = 10, BRIG_CHANNEL_ORDER_ABGR = 11, BRIG_CHANNEL_ORDER_SRGB = 12, BRIG_CHANNEL_ORDER_SRGBX = 13, BRIG_CHANNEL_ORDER_SRGBA = 14, BRIG_CHANNEL_ORDER_SBGRA = 15, BRIG_CHANNEL_ORDER_INTENSITY = 16, BRIG_CHANNEL_ORDER_LUMINANCE = 17, BRIG_CHANNEL_ORDER_DEPTH = 18, BRIG_CHANNEL_ORDER_DEPTH_STENCIL = 19, BRIG_CHANNEL_ORDER_FIRST_USER_DEFINED = 128 }; typedef uint8_t BrigImageChannelType8_t; enum BrigImageChannelType { BRIG_CHANNEL_TYPE_SNORM_INT8 = 0, BRIG_CHANNEL_TYPE_SNORM_INT16 = 1, BRIG_CHANNEL_TYPE_UNORM_INT8 = 2, BRIG_CHANNEL_TYPE_UNORM_INT16 = 3, BRIG_CHANNEL_TYPE_UNORM_INT24 = 4, BRIG_CHANNEL_TYPE_UNORM_SHORT_555 = 5, BRIG_CHANNEL_TYPE_UNORM_SHORT_565 = 6, BRIG_CHANNEL_TYPE_UNORM_INT_101010 = 7, BRIG_CHANNEL_TYPE_SIGNED_INT8 = 8, BRIG_CHANNEL_TYPE_SIGNED_INT16 = 9, BRIG_CHANNEL_TYPE_SIGNED_INT32 = 10, BRIG_CHANNEL_TYPE_UNSIGNED_INT8 = 11, BRIG_CHANNEL_TYPE_UNSIGNED_INT16 = 12, BRIG_CHANNEL_TYPE_UNSIGNED_INT32 = 13, BRIG_CHANNEL_TYPE_HALF_FLOAT = 14, BRIG_CHANNEL_TYPE_FLOAT = 15, BRIG_CHANNEL_TYPE_FIRST_USER_DEFINED = 128 }; typedef uint8_t BrigImageGeometry8_t; enum BrigImageGeometry { BRIG_GEOMETRY_1D = 0, BRIG_GEOMETRY_2D = 1, BRIG_GEOMETRY_3D = 2, BRIG_GEOMETRY_1DA = 3, BRIG_GEOMETRY_2DA = 4, BRIG_GEOMETRY_1DB = 5, BRIG_GEOMETRY_2DDEPTH = 6, BRIG_GEOMETRY_2DADEPTH = 7, BRIG_GEOMETRY_FIRST_USER_DEFINED = 128 }; typedef uint8_t BrigImageQuery8_t; enum BrigImageQuery { BRIG_IMAGE_QUERY_WIDTH = 0, BRIG_IMAGE_QUERY_HEIGHT = 1, BRIG_IMAGE_QUERY_DEPTH = 2, BRIG_IMAGE_QUERY_ARRAY = 3, BRIG_IMAGE_QUERY_CHANNELORDER = 4, BRIG_IMAGE_QUERY_CHANNELTYPE = 5 }; enum BrigKind { BRIG_KIND_NONE = 0x0000, BRIG_KIND_DIRECTIVE_BEGIN = 0x1000, BRIG_KIND_DIRECTIVE_ARG_BLOCK_END = 0x1000, BRIG_KIND_DIRECTIVE_ARG_BLOCK_START = 0x1001, BRIG_KIND_DIRECTIVE_COMMENT = 0x1002, BRIG_KIND_DIRECTIVE_CONTROL = 0x1003, BRIG_KIND_DIRECTIVE_EXTENSION = 0x1004, BRIG_KIND_DIRECTIVE_FBARRIER = 0x1005, BRIG_KIND_DIRECTIVE_FUNCTION = 0x1006, BRIG_KIND_DIRECTIVE_INDIRECT_FUNCTION = 0x1007, BRIG_KIND_DIRECTIVE_KERNEL = 0x1008, BRIG_KIND_DIRECTIVE_LABEL = 0x1009, BRIG_KIND_DIRECTIVE_LOC = 0x100a, BRIG_KIND_DIRECTIVE_MODULE = 0x100b, BRIG_KIND_DIRECTIVE_PRAGMA = 0x100c, BRIG_KIND_DIRECTIVE_SIGNATURE = 0x100d, BRIG_KIND_DIRECTIVE_VARIABLE = 0x100e, BRIG_KIND_DIRECTIVE_END = 0x100f, BRIG_KIND_INST_BEGIN = 0x2000, BRIG_KIND_INST_ADDR = 0x2000, BRIG_KIND_INST_ATOMIC = 0x2001, BRIG_KIND_INST_BASIC = 0x2002, BRIG_KIND_INST_BR = 0x2003, BRIG_KIND_INST_CMP = 0x2004, BRIG_KIND_INST_CVT = 0x2005, BRIG_KIND_INST_IMAGE = 0x2006, BRIG_KIND_INST_LANE = 0x2007, BRIG_KIND_INST_MEM = 0x2008, BRIG_KIND_INST_MEM_FENCE = 0x2009, BRIG_KIND_INST_MOD = 0x200a, BRIG_KIND_INST_QUERY_IMAGE = 0x200b, BRIG_KIND_INST_QUERY_SAMPLER = 0x200c, BRIG_KIND_INST_QUEUE = 0x200d, BRIG_KIND_INST_SEG = 0x200e, BRIG_KIND_INST_SEG_CVT = 0x200f, BRIG_KIND_INST_SIGNAL = 0x2010, BRIG_KIND_INST_SOURCE_TYPE = 0x2011, BRIG_KIND_INST_END = 0x2012, BRIG_KIND_OPERAND_BEGIN = 0x3000, BRIG_KIND_OPERAND_ADDRESS = 0x3000, BRIG_KIND_OPERAND_ALIGN = 0x3001, BRIG_KIND_OPERAND_CODE_LIST = 0x3002, BRIG_KIND_OPERAND_CODE_REF = 0x3003, BRIG_KIND_OPERAND_CONSTANT_BYTES = 0x3004, BRIG_KIND_OPERAND_RESERVED = 0x3005, BRIG_KIND_OPERAND_CONSTANT_IMAGE = 0x3006, BRIG_KIND_OPERAND_CONSTANT_OPERAND_LIST = 0x3007, BRIG_KIND_OPERAND_CONSTANT_SAMPLER = 0x3008, BRIG_KIND_OPERAND_OPERAND_LIST = 0x3009, BRIG_KIND_OPERAND_REGISTER = 0x300a, BRIG_KIND_OPERAND_STRING = 0x300b, BRIG_KIND_OPERAND_WAVESIZE = 0x300c, BRIG_KIND_OPERAND_END = 0x300d }; typedef uint8_t BrigLinkage8_t; enum BrigLinkage { BRIG_LINKAGE_NONE = 0, BRIG_LINKAGE_PROGRAM = 1, BRIG_LINKAGE_MODULE = 2, BRIG_LINKAGE_FUNCTION = 3, BRIG_LINKAGE_ARG = 4 }; typedef uint8_t BrigMachineModel8_t; enum BrigMachineModel { BRIG_MACHINE_SMALL = 0, BRIG_MACHINE_LARGE = 1 }; typedef uint8_t BrigMemoryModifier8_t; enum BrigMemoryModifierMask { BRIG_MEMORY_CONST = 1 }; typedef uint8_t BrigMemoryOrder8_t; enum BrigMemoryOrder { BRIG_MEMORY_ORDER_NONE = 0, BRIG_MEMORY_ORDER_RELAXED = 1, BRIG_MEMORY_ORDER_SC_ACQUIRE = 2, BRIG_MEMORY_ORDER_SC_RELEASE = 3, BRIG_MEMORY_ORDER_SC_ACQUIRE_RELEASE = 4 }; typedef uint8_t BrigMemoryScope8_t; enum BrigMemoryScope { BRIG_MEMORY_SCOPE_NONE = 0, BRIG_MEMORY_SCOPE_WORKITEM = 1, BRIG_MEMORY_SCOPE_WAVEFRONT = 2, BRIG_MEMORY_SCOPE_WORKGROUP = 3, BRIG_MEMORY_SCOPE_AGENT = 4, BRIG_MEMORY_SCOPE_SYSTEM = 5 }; struct BrigModuleHeader { char identification[8]; BrigVersion32_t brigMajor; BrigVersion32_t brigMinor; uint64_t byteCount; uint8_t hash[64]; uint32_t reserved; uint32_t sectionCount; uint64_t sectionIndex; }; typedef uint16_t BrigOpcode16_t; enum BrigOpcode { BRIG_OPCODE_NOP = 0, BRIG_OPCODE_ABS = 1, BRIG_OPCODE_ADD = 2, BRIG_OPCODE_BORROW = 3, BRIG_OPCODE_CARRY = 4, BRIG_OPCODE_CEIL = 5, BRIG_OPCODE_COPYSIGN = 6, BRIG_OPCODE_DIV = 7, BRIG_OPCODE_FLOOR = 8, BRIG_OPCODE_FMA = 9, BRIG_OPCODE_FRACT = 10, BRIG_OPCODE_MAD = 11, BRIG_OPCODE_MAX = 12, BRIG_OPCODE_MIN = 13, BRIG_OPCODE_MUL = 14, BRIG_OPCODE_MULHI = 15, BRIG_OPCODE_NEG = 16, BRIG_OPCODE_REM = 17, BRIG_OPCODE_RINT = 18, BRIG_OPCODE_SQRT = 19, BRIG_OPCODE_SUB = 20, BRIG_OPCODE_TRUNC = 21, BRIG_OPCODE_MAD24 = 22, BRIG_OPCODE_MAD24HI = 23, BRIG_OPCODE_MUL24 = 24, BRIG_OPCODE_MUL24HI = 25, BRIG_OPCODE_SHL = 26, BRIG_OPCODE_SHR = 27, BRIG_OPCODE_AND = 28, BRIG_OPCODE_NOT = 29, BRIG_OPCODE_OR = 30, BRIG_OPCODE_POPCOUNT = 31, BRIG_OPCODE_XOR = 32, BRIG_OPCODE_BITEXTRACT = 33, BRIG_OPCODE_BITINSERT = 34, BRIG_OPCODE_BITMASK = 35, BRIG_OPCODE_BITREV = 36, BRIG_OPCODE_BITSELECT = 37, BRIG_OPCODE_FIRSTBIT = 38, BRIG_OPCODE_LASTBIT = 39, BRIG_OPCODE_COMBINE = 40, BRIG_OPCODE_EXPAND = 41, BRIG_OPCODE_LDA = 42, BRIG_OPCODE_MOV = 43, BRIG_OPCODE_SHUFFLE = 44, BRIG_OPCODE_UNPACKHI = 45, BRIG_OPCODE_UNPACKLO = 46, BRIG_OPCODE_PACK = 47, BRIG_OPCODE_UNPACK = 48, BRIG_OPCODE_CMOV = 49, BRIG_OPCODE_CLASS = 50, BRIG_OPCODE_NCOS = 51, BRIG_OPCODE_NEXP2 = 52, BRIG_OPCODE_NFMA = 53, BRIG_OPCODE_NLOG2 = 54, BRIG_OPCODE_NRCP = 55, BRIG_OPCODE_NRSQRT = 56, BRIG_OPCODE_NSIN = 57, BRIG_OPCODE_NSQRT = 58, BRIG_OPCODE_BITALIGN = 59, BRIG_OPCODE_BYTEALIGN = 60, BRIG_OPCODE_PACKCVT = 61, BRIG_OPCODE_UNPACKCVT = 62, BRIG_OPCODE_LERP = 63, BRIG_OPCODE_SAD = 64, BRIG_OPCODE_SADHI = 65, BRIG_OPCODE_SEGMENTP = 66, BRIG_OPCODE_FTOS = 67, BRIG_OPCODE_STOF = 68, BRIG_OPCODE_CMP = 69, BRIG_OPCODE_CVT = 70, BRIG_OPCODE_LD = 71, BRIG_OPCODE_ST = 72, BRIG_OPCODE_ATOMIC = 73, BRIG_OPCODE_ATOMICNORET = 74, BRIG_OPCODE_SIGNAL = 75, BRIG_OPCODE_SIGNALNORET = 76, BRIG_OPCODE_MEMFENCE = 77, BRIG_OPCODE_RDIMAGE = 78, BRIG_OPCODE_LDIMAGE = 79, BRIG_OPCODE_STIMAGE = 80, BRIG_OPCODE_IMAGEFENCE = 81, BRIG_OPCODE_QUERYIMAGE = 82, BRIG_OPCODE_QUERYSAMPLER = 83, BRIG_OPCODE_CBR = 84, BRIG_OPCODE_BR = 85, BRIG_OPCODE_SBR = 86, BRIG_OPCODE_BARRIER = 87, BRIG_OPCODE_WAVEBARRIER = 88, BRIG_OPCODE_ARRIVEFBAR = 89, BRIG_OPCODE_INITFBAR = 90, BRIG_OPCODE_JOINFBAR = 91, BRIG_OPCODE_LEAVEFBAR = 92, BRIG_OPCODE_RELEASEFBAR = 93, BRIG_OPCODE_WAITFBAR = 94, BRIG_OPCODE_LDF = 95, BRIG_OPCODE_ACTIVELANECOUNT = 96, BRIG_OPCODE_ACTIVELANEID = 97, BRIG_OPCODE_ACTIVELANEMASK = 98, BRIG_OPCODE_ACTIVELANEPERMUTE = 99, BRIG_OPCODE_CALL = 100, BRIG_OPCODE_SCALL = 101, BRIG_OPCODE_ICALL = 102, BRIG_OPCODE_RET = 103, BRIG_OPCODE_ALLOCA = 104, BRIG_OPCODE_CURRENTWORKGROUPSIZE = 105, BRIG_OPCODE_CURRENTWORKITEMFLATID = 106, BRIG_OPCODE_DIM = 107, BRIG_OPCODE_GRIDGROUPS = 108, BRIG_OPCODE_GRIDSIZE = 109, BRIG_OPCODE_PACKETCOMPLETIONSIG = 110, BRIG_OPCODE_PACKETID = 111, BRIG_OPCODE_WORKGROUPID = 112, BRIG_OPCODE_WORKGROUPSIZE = 113, BRIG_OPCODE_WORKITEMABSID = 114, BRIG_OPCODE_WORKITEMFLATABSID = 115, BRIG_OPCODE_WORKITEMFLATID = 116, BRIG_OPCODE_WORKITEMID = 117, BRIG_OPCODE_CLEARDETECTEXCEPT = 118, BRIG_OPCODE_GETDETECTEXCEPT = 119, BRIG_OPCODE_SETDETECTEXCEPT = 120, BRIG_OPCODE_ADDQUEUEWRITEINDEX = 121, BRIG_OPCODE_CASQUEUEWRITEINDEX = 122, BRIG_OPCODE_LDQUEUEREADINDEX = 123, BRIG_OPCODE_LDQUEUEWRITEINDEX = 124, BRIG_OPCODE_STQUEUEREADINDEX = 125, BRIG_OPCODE_STQUEUEWRITEINDEX = 126, BRIG_OPCODE_CLOCK = 127, BRIG_OPCODE_CUID = 128, BRIG_OPCODE_DEBUGTRAP = 129, BRIG_OPCODE_GROUPBASEPTR = 130, BRIG_OPCODE_KERNARGBASEPTR = 131, BRIG_OPCODE_LANEID = 132, BRIG_OPCODE_MAXCUID = 133, BRIG_OPCODE_MAXWAVEID = 134, BRIG_OPCODE_NULLPTR = 135, BRIG_OPCODE_WAVEID = 136, BRIG_OPCODE_FIRST_USER_DEFINED = 32768 }; typedef uint8_t BrigPack8_t; enum BrigPack { BRIG_PACK_NONE = 0, BRIG_PACK_PP = 1, BRIG_PACK_PS = 2, BRIG_PACK_SP = 3, BRIG_PACK_SS = 4, BRIG_PACK_S = 5, BRIG_PACK_P = 6, BRIG_PACK_PPSAT = 7, BRIG_PACK_PSSAT = 8, BRIG_PACK_SPSAT = 9, BRIG_PACK_SSSAT = 10, BRIG_PACK_SSAT = 11, BRIG_PACK_PSAT = 12 }; typedef uint8_t BrigProfile8_t; enum BrigProfile { BRIG_PROFILE_BASE = 0, BRIG_PROFILE_FULL = 1 }; typedef uint16_t BrigRegisterKind16_t; enum BrigRegisterKind { BRIG_REGISTER_KIND_CONTROL = 0, BRIG_REGISTER_KIND_SINGLE = 1, BRIG_REGISTER_KIND_DOUBLE = 2, BRIG_REGISTER_KIND_QUAD = 3 }; typedef uint8_t BrigRound8_t; enum BrigRound { BRIG_ROUND_NONE = 0, BRIG_ROUND_FLOAT_DEFAULT = 1, BRIG_ROUND_FLOAT_NEAR_EVEN = 2, BRIG_ROUND_FLOAT_ZERO = 3, BRIG_ROUND_FLOAT_PLUS_INFINITY = 4, BRIG_ROUND_FLOAT_MINUS_INFINITY = 5, BRIG_ROUND_INTEGER_NEAR_EVEN = 6, BRIG_ROUND_INTEGER_ZERO = 7, BRIG_ROUND_INTEGER_PLUS_INFINITY = 8, BRIG_ROUND_INTEGER_MINUS_INFINITY = 9, BRIG_ROUND_INTEGER_NEAR_EVEN_SAT = 10, BRIG_ROUND_INTEGER_ZERO_SAT = 11, BRIG_ROUND_INTEGER_PLUS_INFINITY_SAT = 12, BRIG_ROUND_INTEGER_MINUS_INFINITY_SAT = 13, BRIG_ROUND_INTEGER_SIGNALING_NEAR_EVEN = 14, BRIG_ROUND_INTEGER_SIGNALING_ZERO = 15, BRIG_ROUND_INTEGER_SIGNALING_PLUS_INFINITY = 16, BRIG_ROUND_INTEGER_SIGNALING_MINUS_INFINITY = 17, BRIG_ROUND_INTEGER_SIGNALING_NEAR_EVEN_SAT = 18, BRIG_ROUND_INTEGER_SIGNALING_ZERO_SAT = 19, BRIG_ROUND_INTEGER_SIGNALING_PLUS_INFINITY_SAT = 20, BRIG_ROUND_INTEGER_SIGNALING_MINUS_INFINITY_SAT = 21 }; typedef uint8_t BrigSamplerAddressing8_t; enum BrigSamplerAddressing { BRIG_ADDRESSING_UNDEFINED = 0, BRIG_ADDRESSING_CLAMP_TO_EDGE = 1, BRIG_ADDRESSING_CLAMP_TO_BORDER = 2, BRIG_ADDRESSING_REPEAT = 3, BRIG_ADDRESSING_MIRRORED_REPEAT = 4, BRIG_ADDRESSING_FIRST_USER_DEFINED = 128 }; typedef uint8_t BrigSamplerCoordNormalization8_t; enum BrigSamplerCoordNormalization { BRIG_COORD_UNNORMALIZED = 0, BRIG_COORD_NORMALIZED = 1 }; typedef uint8_t BrigSamplerFilter8_t; enum BrigSamplerFilter { BRIG_FILTER_NEAREST = 0, BRIG_FILTER_LINEAR = 1, BRIG_FILTER_FIRST_USER_DEFINED = 128 }; typedef uint8_t BrigSamplerQuery8_t; enum BrigSamplerQuery { BRIG_SAMPLER_QUERY_ADDRESSING = 0, BRIG_SAMPLER_QUERY_COORD = 1, BRIG_SAMPLER_QUERY_FILTER = 2 }; typedef uint32_t BrigSectionIndex32_t; enum BrigSectionIndex { BRIG_SECTION_INDEX_DATA = 0, BRIG_SECTION_INDEX_CODE = 1, BRIG_SECTION_INDEX_OPERAND = 2, BRIG_SECTION_INDEX_BEGIN_IMPLEMENTATION_DEFINED = 3 }; struct BrigSectionHeader { uint64_t byteCount; uint32_t headerByteCount; uint32_t nameLength; uint8_t name[1]; }; typedef uint8_t BrigSegCvtModifier8_t; enum BrigSegCvtModifierMask { BRIG_SEG_CVT_NONULL = 1 }; typedef uint8_t BrigSegment8_t; enum BrigSegment { BRIG_SEGMENT_NONE = 0, BRIG_SEGMENT_FLAT = 1, BRIG_SEGMENT_GLOBAL = 2, BRIG_SEGMENT_READONLY = 3, BRIG_SEGMENT_KERNARG = 4, BRIG_SEGMENT_GROUP = 5, BRIG_SEGMENT_PRIVATE = 6, BRIG_SEGMENT_SPILL = 7, BRIG_SEGMENT_ARG = 8, BRIG_SEGMENT_FIRST_USER_DEFINED = 128 }; enum { BRIG_TYPE_BASE_SIZE = 5, BRIG_TYPE_PACK_SIZE = 2, BRIG_TYPE_ARRAY_SIZE = 1, BRIG_TYPE_BASE_SHIFT = 0, BRIG_TYPE_PACK_SHIFT = BRIG_TYPE_BASE_SHIFT + BRIG_TYPE_BASE_SIZE, BRIG_TYPE_ARRAY_SHIFT = BRIG_TYPE_PACK_SHIFT + BRIG_TYPE_PACK_SIZE, BRIG_TYPE_BASE_MASK = ((1 << BRIG_TYPE_BASE_SIZE) - 1) << BRIG_TYPE_BASE_SHIFT, BRIG_TYPE_PACK_MASK = ((1 << BRIG_TYPE_PACK_SIZE) - 1) << BRIG_TYPE_PACK_SHIFT, BRIG_TYPE_ARRAY_MASK = ((1 << BRIG_TYPE_ARRAY_SIZE) - 1) << BRIG_TYPE_ARRAY_SHIFT, BRIG_TYPE_PACK_NONE = 0 << BRIG_TYPE_PACK_SHIFT, BRIG_TYPE_PACK_32 = 1 << BRIG_TYPE_PACK_SHIFT, BRIG_TYPE_PACK_64 = 2 << BRIG_TYPE_PACK_SHIFT, BRIG_TYPE_PACK_128 = 3 << BRIG_TYPE_PACK_SHIFT, BRIG_TYPE_ARRAY = 1 << BRIG_TYPE_ARRAY_SHIFT }; typedef uint16_t BrigType16_t; enum BrigType { BRIG_TYPE_NONE = 0, BRIG_TYPE_U8 = 1, BRIG_TYPE_U16 = 2, BRIG_TYPE_U32 = 3, BRIG_TYPE_U64 = 4, BRIG_TYPE_S8 = 5, BRIG_TYPE_S16 = 6, BRIG_TYPE_S32 = 7, BRIG_TYPE_S64 = 8, BRIG_TYPE_F16 = 9, BRIG_TYPE_F32 = 10, BRIG_TYPE_F64 = 11, BRIG_TYPE_B1 = 12, BRIG_TYPE_B8 = 13, BRIG_TYPE_B16 = 14, BRIG_TYPE_B32 = 15, BRIG_TYPE_B64 = 16, BRIG_TYPE_B128 = 17, BRIG_TYPE_SAMP = 18, BRIG_TYPE_ROIMG = 19, BRIG_TYPE_WOIMG = 20, BRIG_TYPE_RWIMG = 21, BRIG_TYPE_SIG32 = 22, BRIG_TYPE_SIG64 = 23, BRIG_TYPE_U8X4 = BRIG_TYPE_U8 | BRIG_TYPE_PACK_32, BRIG_TYPE_U8X8 = BRIG_TYPE_U8 | BRIG_TYPE_PACK_64, BRIG_TYPE_U8X16 = BRIG_TYPE_U8 | BRIG_TYPE_PACK_128, BRIG_TYPE_U16X2 = BRIG_TYPE_U16 | BRIG_TYPE_PACK_32, BRIG_TYPE_U16X4 = BRIG_TYPE_U16 | BRIG_TYPE_PACK_64, BRIG_TYPE_U16X8 = BRIG_TYPE_U16 | BRIG_TYPE_PACK_128, BRIG_TYPE_U32X2 = BRIG_TYPE_U32 | BRIG_TYPE_PACK_64, BRIG_TYPE_U32X4 = BRIG_TYPE_U32 | BRIG_TYPE_PACK_128, BRIG_TYPE_U64X2 = BRIG_TYPE_U64 | BRIG_TYPE_PACK_128, BRIG_TYPE_S8X4 = BRIG_TYPE_S8 | BRIG_TYPE_PACK_32, BRIG_TYPE_S8X8 = BRIG_TYPE_S8 | BRIG_TYPE_PACK_64, BRIG_TYPE_S8X16 = BRIG_TYPE_S8 | BRIG_TYPE_PACK_128, BRIG_TYPE_S16X2 = BRIG_TYPE_S16 | BRIG_TYPE_PACK_32, BRIG_TYPE_S16X4 = BRIG_TYPE_S16 | BRIG_TYPE_PACK_64, BRIG_TYPE_S16X8 = BRIG_TYPE_S16 | BRIG_TYPE_PACK_128, BRIG_TYPE_S32X2 = BRIG_TYPE_S32 | BRIG_TYPE_PACK_64, BRIG_TYPE_S32X4 = BRIG_TYPE_S32 | BRIG_TYPE_PACK_128, BRIG_TYPE_S64X2 = BRIG_TYPE_S64 | BRIG_TYPE_PACK_128, BRIG_TYPE_F16X2 = BRIG_TYPE_F16 | BRIG_TYPE_PACK_32, BRIG_TYPE_F16X4 = BRIG_TYPE_F16 | BRIG_TYPE_PACK_64, BRIG_TYPE_F16X8 = BRIG_TYPE_F16 | BRIG_TYPE_PACK_128, BRIG_TYPE_F32X2 = BRIG_TYPE_F32 | BRIG_TYPE_PACK_64, BRIG_TYPE_F32X4 = BRIG_TYPE_F32 | BRIG_TYPE_PACK_128, BRIG_TYPE_F64X2 = BRIG_TYPE_F64 | BRIG_TYPE_PACK_128, BRIG_TYPE_U8_ARRAY = BRIG_TYPE_U8 | BRIG_TYPE_ARRAY, BRIG_TYPE_U16_ARRAY = BRIG_TYPE_U16 | BRIG_TYPE_ARRAY, BRIG_TYPE_U32_ARRAY = BRIG_TYPE_U32 | BRIG_TYPE_ARRAY, BRIG_TYPE_U64_ARRAY = BRIG_TYPE_U64 | BRIG_TYPE_ARRAY, BRIG_TYPE_S8_ARRAY = BRIG_TYPE_S8 | BRIG_TYPE_ARRAY, BRIG_TYPE_S16_ARRAY = BRIG_TYPE_S16 | BRIG_TYPE_ARRAY, BRIG_TYPE_S32_ARRAY = BRIG_TYPE_S32 | BRIG_TYPE_ARRAY, BRIG_TYPE_S64_ARRAY = BRIG_TYPE_S64 | BRIG_TYPE_ARRAY, BRIG_TYPE_F16_ARRAY = BRIG_TYPE_F16 | BRIG_TYPE_ARRAY, BRIG_TYPE_F32_ARRAY = BRIG_TYPE_F32 | BRIG_TYPE_ARRAY, BRIG_TYPE_F64_ARRAY = BRIG_TYPE_F64 | BRIG_TYPE_ARRAY, BRIG_TYPE_B8_ARRAY = BRIG_TYPE_B8 | BRIG_TYPE_ARRAY, BRIG_TYPE_B16_ARRAY = BRIG_TYPE_B16 | BRIG_TYPE_ARRAY, BRIG_TYPE_B32_ARRAY = BRIG_TYPE_B32 | BRIG_TYPE_ARRAY, BRIG_TYPE_B64_ARRAY = BRIG_TYPE_B64 | BRIG_TYPE_ARRAY, BRIG_TYPE_B128_ARRAY = BRIG_TYPE_B128 | BRIG_TYPE_ARRAY, BRIG_TYPE_SAMP_ARRAY = BRIG_TYPE_SAMP | BRIG_TYPE_ARRAY, BRIG_TYPE_ROIMG_ARRAY = BRIG_TYPE_ROIMG | BRIG_TYPE_ARRAY, BRIG_TYPE_WOIMG_ARRAY = BRIG_TYPE_WOIMG | BRIG_TYPE_ARRAY, BRIG_TYPE_RWIMG_ARRAY = BRIG_TYPE_RWIMG | BRIG_TYPE_ARRAY, BRIG_TYPE_SIG32_ARRAY = BRIG_TYPE_SIG32 | BRIG_TYPE_ARRAY, BRIG_TYPE_SIG64_ARRAY = BRIG_TYPE_SIG64 | BRIG_TYPE_ARRAY, BRIG_TYPE_U8X4_ARRAY = BRIG_TYPE_U8X4 | BRIG_TYPE_ARRAY, BRIG_TYPE_U8X8_ARRAY = BRIG_TYPE_U8X8 | BRIG_TYPE_ARRAY, BRIG_TYPE_U8X16_ARRAY = BRIG_TYPE_U8X16 | BRIG_TYPE_ARRAY, BRIG_TYPE_U16X2_ARRAY = BRIG_TYPE_U16X2 | BRIG_TYPE_ARRAY, BRIG_TYPE_U16X4_ARRAY = BRIG_TYPE_U16X4 | BRIG_TYPE_ARRAY, BRIG_TYPE_U16X8_ARRAY = BRIG_TYPE_U16X8 | BRIG_TYPE_ARRAY, BRIG_TYPE_U32X2_ARRAY = BRIG_TYPE_U32X2 | BRIG_TYPE_ARRAY, BRIG_TYPE_U32X4_ARRAY = BRIG_TYPE_U32X4 | BRIG_TYPE_ARRAY, BRIG_TYPE_U64X2_ARRAY = BRIG_TYPE_U64X2 | BRIG_TYPE_ARRAY, BRIG_TYPE_S8X4_ARRAY = BRIG_TYPE_S8X4 | BRIG_TYPE_ARRAY, BRIG_TYPE_S8X8_ARRAY = BRIG_TYPE_S8X8 | BRIG_TYPE_ARRAY, BRIG_TYPE_S8X16_ARRAY = BRIG_TYPE_S8X16 | BRIG_TYPE_ARRAY, BRIG_TYPE_S16X2_ARRAY = BRIG_TYPE_S16X2 | BRIG_TYPE_ARRAY, BRIG_TYPE_S16X4_ARRAY = BRIG_TYPE_S16X4 | BRIG_TYPE_ARRAY, BRIG_TYPE_S16X8_ARRAY = BRIG_TYPE_S16X8 | BRIG_TYPE_ARRAY, BRIG_TYPE_S32X2_ARRAY = BRIG_TYPE_S32X2 | BRIG_TYPE_ARRAY, BRIG_TYPE_S32X4_ARRAY = BRIG_TYPE_S32X4 | BRIG_TYPE_ARRAY, BRIG_TYPE_S64X2_ARRAY = BRIG_TYPE_S64X2 | BRIG_TYPE_ARRAY, BRIG_TYPE_F16X2_ARRAY = BRIG_TYPE_F16X2 | BRIG_TYPE_ARRAY, BRIG_TYPE_F16X4_ARRAY = BRIG_TYPE_F16X4 | BRIG_TYPE_ARRAY, BRIG_TYPE_F16X8_ARRAY = BRIG_TYPE_F16X8 | BRIG_TYPE_ARRAY, BRIG_TYPE_F32X2_ARRAY = BRIG_TYPE_F32X2 | BRIG_TYPE_ARRAY, BRIG_TYPE_F32X4_ARRAY = BRIG_TYPE_F32X4 | BRIG_TYPE_ARRAY, BRIG_TYPE_F64X2_ARRAY = BRIG_TYPE_F64X2 | BRIG_TYPE_ARRAY }; struct BrigUInt64 { uint32_t lo; uint32_t hi; }; typedef uint8_t BrigVariableModifier8_t; enum BrigVariableModifierMask { BRIG_VARIABLE_DEFINITION = 1, BRIG_VARIABLE_CONST = 2 }; enum BrigVersion { BRIG_VERSION_HSAIL_MAJOR = 1, BRIG_VERSION_HSAIL_MINOR = 0, BRIG_VERSION_BRIG_MAJOR = 1, BRIG_VERSION_BRIG_MINOR = 0 }; typedef uint8_t BrigWidth8_t; enum BrigWidth { BRIG_WIDTH_NONE = 0, BRIG_WIDTH_1 = 1, BRIG_WIDTH_2 = 2, BRIG_WIDTH_4 = 3, BRIG_WIDTH_8 = 4, BRIG_WIDTH_16 = 5, BRIG_WIDTH_32 = 6, BRIG_WIDTH_64 = 7, BRIG_WIDTH_128 = 8, BRIG_WIDTH_256 = 9, BRIG_WIDTH_512 = 10, BRIG_WIDTH_1024 = 11, BRIG_WIDTH_2048 = 12, BRIG_WIDTH_4096 = 13, BRIG_WIDTH_8192 = 14, BRIG_WIDTH_16384 = 15, BRIG_WIDTH_32768 = 16, BRIG_WIDTH_65536 = 17, BRIG_WIDTH_131072 = 18, BRIG_WIDTH_262144 = 19, BRIG_WIDTH_524288 = 20, BRIG_WIDTH_1048576 = 21, BRIG_WIDTH_2097152 = 22, BRIG_WIDTH_4194304 = 23, BRIG_WIDTH_8388608 = 24, BRIG_WIDTH_16777216 = 25, BRIG_WIDTH_33554432 = 26, BRIG_WIDTH_67108864 = 27, BRIG_WIDTH_134217728 = 28, BRIG_WIDTH_268435456 = 29, BRIG_WIDTH_536870912 = 30, BRIG_WIDTH_1073741824 = 31, BRIG_WIDTH_2147483648 = 32, BRIG_WIDTH_WAVESIZE = 33, BRIG_WIDTH_ALL = 34 }; struct BrigData { uint32_t byteCount; uint8_t bytes[1]; }; struct BrigDirectiveArgBlock { BrigBase base; }; struct BrigDirectiveComment { BrigBase base; BrigDataOffsetString32_t name; }; struct BrigDirectiveControl { BrigBase base; BrigControlDirective16_t control; uint16_t reserved; BrigDataOffsetOperandList32_t operands; }; struct BrigDirectiveExecutable { BrigBase base; BrigDataOffsetString32_t name; uint16_t outArgCount; uint16_t inArgCount; BrigCodeOffset32_t firstInArg; BrigCodeOffset32_t firstCodeBlockEntry; BrigCodeOffset32_t nextModuleEntry; BrigExecutableModifier8_t modifier; BrigLinkage8_t linkage; uint16_t reserved; }; struct BrigDirectiveExtension { BrigBase base; BrigDataOffsetString32_t name; }; struct BrigDirectiveFbarrier { BrigBase base; BrigDataOffsetString32_t name; BrigVariableModifier8_t modifier; BrigLinkage8_t linkage; uint16_t reserved; }; struct BrigDirectiveLabel { BrigBase base; BrigDataOffsetString32_t name; }; struct BrigDirectiveLoc { BrigBase base; BrigDataOffsetString32_t filename; uint32_t line; uint32_t column; }; struct BrigDirectiveModule { BrigBase base; BrigDataOffsetString32_t name; BrigVersion32_t hsailMajor; BrigVersion32_t hsailMinor; BrigProfile8_t profile; BrigMachineModel8_t machineModel; BrigRound8_t defaultFloatRound; uint8_t reserved; }; struct BrigDirectiveNone { BrigBase base; }; struct BrigDirectivePragma { BrigBase base; BrigDataOffsetOperandList32_t operands; }; struct BrigDirectiveVariable { BrigBase base; BrigDataOffsetString32_t name; BrigOperandOffset32_t init; BrigType16_t type; BrigSegment8_t segment; BrigAlignment8_t align; BrigUInt64 dim; BrigVariableModifier8_t modifier; BrigLinkage8_t linkage; BrigAllocation8_t allocation; uint8_t reserved; }; struct BrigInstBase { BrigBase base; BrigOpcode16_t opcode; BrigType16_t type; BrigDataOffsetOperandList32_t operands; }; struct BrigInstAddr { BrigInstBase base; BrigSegment8_t segment; uint8_t reserved[3]; }; struct BrigInstAtomic { BrigInstBase base; BrigSegment8_t segment; BrigMemoryOrder8_t memoryOrder; BrigMemoryScope8_t memoryScope; BrigAtomicOperation8_t atomicOperation; uint8_t equivClass; uint8_t reserved[3]; }; struct BrigInstBasic { BrigInstBase base; }; struct BrigInstBr { BrigInstBase base; BrigWidth8_t width; uint8_t reserved[3]; }; struct BrigInstCmp { BrigInstBase base; BrigType16_t sourceType; BrigAluModifier8_t modifier; BrigCompareOperation8_t compare; BrigPack8_t pack; uint8_t reserved[3]; }; struct BrigInstCvt { BrigInstBase base; BrigType16_t sourceType; BrigAluModifier8_t modifier; BrigRound8_t round; }; struct BrigInstImage { BrigInstBase base; BrigType16_t imageType; BrigType16_t coordType; BrigImageGeometry8_t geometry; uint8_t equivClass; uint16_t reserved; }; struct BrigInstLane { BrigInstBase base; BrigType16_t sourceType; BrigWidth8_t width; uint8_t reserved; }; struct BrigInstMem { BrigInstBase base; BrigSegment8_t segment; BrigAlignment8_t align; uint8_t equivClass; BrigWidth8_t width; BrigMemoryModifier8_t modifier; uint8_t reserved[3]; }; struct BrigInstMemFence { BrigInstBase base; BrigMemoryOrder8_t memoryOrder; BrigMemoryScope8_t globalSegmentMemoryScope; BrigMemoryScope8_t groupSegmentMemoryScope; BrigMemoryScope8_t imageSegmentMemoryScope; }; struct BrigInstMod { BrigInstBase base; BrigAluModifier8_t modifier; BrigRound8_t round; BrigPack8_t pack; uint8_t reserved; }; struct BrigInstQueryImage { BrigInstBase base; BrigType16_t imageType; BrigImageGeometry8_t geometry; BrigImageQuery8_t query; }; struct BrigInstQuerySampler { BrigInstBase base; BrigSamplerQuery8_t query; uint8_t reserved[3]; }; struct BrigInstQueue { BrigInstBase base; BrigSegment8_t segment; BrigMemoryOrder8_t memoryOrder; uint16_t reserved; }; struct BrigInstSeg { BrigInstBase base; BrigSegment8_t segment; uint8_t reserved[3]; }; struct BrigInstSegCvt { BrigInstBase base; BrigType16_t sourceType; BrigSegment8_t segment; BrigSegCvtModifier8_t modifier; }; struct BrigInstSignal { BrigInstBase base; BrigType16_t signalType; BrigMemoryOrder8_t memoryOrder; BrigAtomicOperation8_t signalOperation; }; struct BrigInstSourceType { BrigInstBase base; BrigType16_t sourceType; uint16_t reserved; }; struct BrigOperandAddress { BrigBase base; BrigCodeOffset32_t symbol; BrigOperandOffset32_t reg; BrigUInt64 offset; }; struct BrigOperandAlign { BrigBase base; BrigAlignment8_t align; uint8_t reserved[3]; }; struct BrigOperandCodeList { BrigBase base; BrigDataOffsetCodeList32_t elements; }; struct BrigOperandCodeRef { BrigBase base; BrigCodeOffset32_t ref; }; struct BrigOperandConstantBytes { BrigBase base; BrigType16_t type; uint16_t reserved; BrigDataOffsetString32_t bytes; }; struct BrigOperandConstantImage { BrigBase base; BrigType16_t type; BrigImageGeometry8_t geometry; BrigImageChannelOrder8_t channelOrder; BrigImageChannelType8_t channelType; uint8_t reserved[3]; BrigUInt64 width; BrigUInt64 height; BrigUInt64 depth; BrigUInt64 array; }; struct BrigOperandConstantOperandList { BrigBase base; BrigType16_t type; uint16_t reserved; BrigDataOffsetOperandList32_t elements; }; struct BrigOperandConstantSampler { BrigBase base; BrigType16_t type; BrigSamplerCoordNormalization8_t coord; BrigSamplerFilter8_t filter; BrigSamplerAddressing8_t addressing; uint8_t reserved[3]; }; struct BrigOperandOperandList { BrigBase base; BrigDataOffsetOperandList32_t elements; }; struct BrigOperandRegister { BrigBase base; BrigRegisterKind16_t regKind; uint16_t regNum; }; struct BrigOperandString { BrigBase base; BrigDataOffsetString32_t string; }; struct BrigOperandWavesize { BrigBase base; }; #endif /* HSA_BRIG_FORMAT_H */
883b67ea0512853e79490c69ee9f68cdc0f0eeb6
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/ffmpeg/libavfilter/vf_colorbalance.c
0e626681b60d49976b87e826e4c3bde797c9f8b4
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LGPL-2.1-only", "LGPL-3.0-only", "GPL-2.0-only", "LGPL-2.1-or-later", "GPL-3.0-or-later", "LGPL-3.0-or-later", "IJG", "LicenseRef-scancode-other-permissive", "GPL-2.0-or-later", "GPL-3.0-only" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C
false
false
15,953
c
vf_colorbalance.c
/* * Copyright (c) 2013 Paul B Mahol * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/opt.h" #include "libavutil/pixdesc.h" #include "avfilter.h" #include "drawutils.h" #include "formats.h" #include "internal.h" #include "video.h" #define R 0 #define G 1 #define B 2 #define A 3 typedef struct ThreadData { AVFrame *in, *out; } ThreadData; typedef struct Range { float shadows; float midtones; float highlights; } Range; typedef struct ColorBalanceContext { const AVClass *class; Range cyan_red; Range magenta_green; Range yellow_blue; int preserve_lightness; uint8_t rgba_map[4]; int depth; int max; int step; int (*color_balance)(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs); } ColorBalanceContext; #define OFFSET(x) offsetof(ColorBalanceContext, x) #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_RUNTIME_PARAM static const AVOption colorbalance_options[] = { { "rs", "set red shadows", OFFSET(cyan_red.shadows), AV_OPT_TYPE_FLOAT, {.dbl=0}, -1, 1, FLAGS }, { "gs", "set green shadows", OFFSET(magenta_green.shadows), AV_OPT_TYPE_FLOAT, {.dbl=0}, -1, 1, FLAGS }, { "bs", "set blue shadows", OFFSET(yellow_blue.shadows), AV_OPT_TYPE_FLOAT, {.dbl=0}, -1, 1, FLAGS }, { "rm", "set red midtones", OFFSET(cyan_red.midtones), AV_OPT_TYPE_FLOAT, {.dbl=0}, -1, 1, FLAGS }, { "gm", "set green midtones", OFFSET(magenta_green.midtones), AV_OPT_TYPE_FLOAT, {.dbl=0}, -1, 1, FLAGS }, { "bm", "set blue midtones", OFFSET(yellow_blue.midtones), AV_OPT_TYPE_FLOAT, {.dbl=0}, -1, 1, FLAGS }, { "rh", "set red highlights", OFFSET(cyan_red.highlights), AV_OPT_TYPE_FLOAT, {.dbl=0}, -1, 1, FLAGS }, { "gh", "set green highlights", OFFSET(magenta_green.highlights), AV_OPT_TYPE_FLOAT, {.dbl=0}, -1, 1, FLAGS }, { "bh", "set blue highlights", OFFSET(yellow_blue.highlights), AV_OPT_TYPE_FLOAT, {.dbl=0}, -1, 1, FLAGS }, { "pl", "preserve lightness", OFFSET(preserve_lightness), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS }, { NULL } }; AVFILTER_DEFINE_CLASS(colorbalance); static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24, AV_PIX_FMT_RGBA, AV_PIX_FMT_BGRA, AV_PIX_FMT_ABGR, AV_PIX_FMT_ARGB, AV_PIX_FMT_0BGR, AV_PIX_FMT_0RGB, AV_PIX_FMT_RGB0, AV_PIX_FMT_BGR0, AV_PIX_FMT_RGB48, AV_PIX_FMT_BGR48, AV_PIX_FMT_RGBA64, AV_PIX_FMT_BGRA64, AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRAP, AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRAP10, AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRAP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16, AV_PIX_FMT_GBRAP16, AV_PIX_FMT_NONE }; static float get_component(float v, float l, float s, float m, float h) { const float a = 4.f, b = 0.333f, scale = 0.7f; s *= av_clipf((b - l) * a + 0.5f, 0.f, 1.f) * scale; m *= av_clipf((l - b) * a + 0.5f, 0.f, 1.f) * av_clipf((1.f - l - b) * a + 0.5f, 0.f, 1.f) * scale; h *= av_clipf((l + b - 1) * a + 0.5f, 0.f, 1.f) * scale; v += s; v += m; v += h; return av_clipf(v, 0.f, 1.f); } static float hfun(float n, float h, float s, float l) { float a = s * FFMIN(l, 1.f - l); float k = fmodf(n + h / 30.f, 12.f); return av_clipf(l - a * FFMAX(FFMIN3(k - 3.f, 9.f - k, 1), -1.f), 0.f, 1.f); } static void preservel(float *r, float *g, float *b, float l) { float max = FFMAX3(*r, *g, *b); float min = FFMIN3(*r, *g, *b); float h, s; l *= 0.5f; if (*r == *g && *g == *b) { h = 0.f; } else if (max == *r) { h = 60.f * (0.f + (*g - *b) / (max - min)); } else if (max == *g) { h = 60.f * (2.f + (*b - *r) / (max - min)); } else if (max == *b) { h = 60.f * (4.f + (*r - *g) / (max - min)); } else { h = 0.f; } if (h < 0.f) h += 360.f; if (max == 1.f || min == 0.f) { s = 0.f; } else { s = (max - min) / (1.f - (FFABS(2.f * l - 1.f))); } *r = hfun(0.f, h, s, l); *g = hfun(8.f, h, s, l); *b = hfun(4.f, h, s, l); } static int color_balance8_p(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) { ColorBalanceContext *s = ctx->priv; ThreadData *td = arg; AVFrame *in = td->in; AVFrame *out = td->out; const int slice_start = (out->height * jobnr) / nb_jobs; const int slice_end = (out->height * (jobnr+1)) / nb_jobs; const uint8_t *srcg = in->data[0] + slice_start * in->linesize[0]; const uint8_t *srcb = in->data[1] + slice_start * in->linesize[1]; const uint8_t *srcr = in->data[2] + slice_start * in->linesize[2]; const uint8_t *srca = in->data[3] + slice_start * in->linesize[3]; uint8_t *dstg = out->data[0] + slice_start * out->linesize[0]; uint8_t *dstb = out->data[1] + slice_start * out->linesize[1]; uint8_t *dstr = out->data[2] + slice_start * out->linesize[2]; uint8_t *dsta = out->data[3] + slice_start * out->linesize[3]; const float max = s->max; int i, j; for (i = slice_start; i < slice_end; i++) { for (j = 0; j < out->width; j++) { float r = srcr[j] / max; float g = srcg[j] / max; float b = srcb[j] / max; const float l = FFMAX3(r, g, b) + FFMIN3(r, g, b); r = get_component(r, l, s->cyan_red.shadows, s->cyan_red.midtones, s->cyan_red.highlights); g = get_component(g, l, s->magenta_green.shadows, s->magenta_green.midtones, s->magenta_green.highlights); b = get_component(b, l, s->yellow_blue.shadows, s->yellow_blue.midtones, s->yellow_blue.highlights); if (s->preserve_lightness) preservel(&r, &g, &b, l); dstr[j] = av_clip_uint8(lrintf(r * max)); dstg[j] = av_clip_uint8(lrintf(g * max)); dstb[j] = av_clip_uint8(lrintf(b * max)); if (in != out && out->linesize[3]) dsta[j] = srca[j]; } srcg += in->linesize[0]; srcb += in->linesize[1]; srcr += in->linesize[2]; srca += in->linesize[3]; dstg += out->linesize[0]; dstb += out->linesize[1]; dstr += out->linesize[2]; dsta += out->linesize[3]; } return 0; } static int color_balance16_p(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) { ColorBalanceContext *s = ctx->priv; ThreadData *td = arg; AVFrame *in = td->in; AVFrame *out = td->out; const int slice_start = (out->height * jobnr) / nb_jobs; const int slice_end = (out->height * (jobnr+1)) / nb_jobs; const uint16_t *srcg = (const uint16_t *)in->data[0] + slice_start * in->linesize[0] / 2; const uint16_t *srcb = (const uint16_t *)in->data[1] + slice_start * in->linesize[1] / 2; const uint16_t *srcr = (const uint16_t *)in->data[2] + slice_start * in->linesize[2] / 2; const uint16_t *srca = (const uint16_t *)in->data[3] + slice_start * in->linesize[3] / 2; uint16_t *dstg = (uint16_t *)out->data[0] + slice_start * out->linesize[0] / 2; uint16_t *dstb = (uint16_t *)out->data[1] + slice_start * out->linesize[1] / 2; uint16_t *dstr = (uint16_t *)out->data[2] + slice_start * out->linesize[2] / 2; uint16_t *dsta = (uint16_t *)out->data[3] + slice_start * out->linesize[3] / 2; const int depth = s->depth; const float max = s->max; int i, j; for (i = slice_start; i < slice_end; i++) { for (j = 0; j < out->width; j++) { float r = srcr[j] / max; float g = srcg[j] / max; float b = srcb[j] / max; const float l = (FFMAX3(r, g, b) + FFMIN3(r, g, b)); r = get_component(r, l, s->cyan_red.shadows, s->cyan_red.midtones, s->cyan_red.highlights); g = get_component(g, l, s->magenta_green.shadows, s->magenta_green.midtones, s->magenta_green.highlights); b = get_component(b, l, s->yellow_blue.shadows, s->yellow_blue.midtones, s->yellow_blue.highlights); if (s->preserve_lightness) preservel(&r, &g, &b, l); dstr[j] = av_clip_uintp2_c(lrintf(r * max), depth); dstg[j] = av_clip_uintp2_c(lrintf(g * max), depth); dstb[j] = av_clip_uintp2_c(lrintf(b * max), depth); if (in != out && out->linesize[3]) dsta[j] = srca[j]; } srcg += in->linesize[0] / 2; srcb += in->linesize[1] / 2; srcr += in->linesize[2] / 2; srca += in->linesize[3] / 2; dstg += out->linesize[0] / 2; dstb += out->linesize[1] / 2; dstr += out->linesize[2] / 2; dsta += out->linesize[3] / 2; } return 0; } static int color_balance8(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) { ColorBalanceContext *s = ctx->priv; ThreadData *td = arg; AVFrame *in = td->in; AVFrame *out = td->out; AVFilterLink *outlink = ctx->outputs[0]; const int slice_start = (out->height * jobnr) / nb_jobs; const int slice_end = (out->height * (jobnr+1)) / nb_jobs; const uint8_t *srcrow = in->data[0] + slice_start * in->linesize[0]; const uint8_t roffset = s->rgba_map[R]; const uint8_t goffset = s->rgba_map[G]; const uint8_t boffset = s->rgba_map[B]; const uint8_t aoffset = s->rgba_map[A]; const float max = s->max; const int step = s->step; uint8_t *dstrow; int i, j; dstrow = out->data[0] + slice_start * out->linesize[0]; for (i = slice_start; i < slice_end; i++) { const uint8_t *src = srcrow; uint8_t *dst = dstrow; for (j = 0; j < outlink->w * step; j += step) { float r = src[j + roffset] / max; float g = src[j + goffset] / max; float b = src[j + boffset] / max; const float l = (FFMAX3(r, g, b) + FFMIN3(r, g, b)); r = get_component(r, l, s->cyan_red.shadows, s->cyan_red.midtones, s->cyan_red.highlights); g = get_component(g, l, s->magenta_green.shadows, s->magenta_green.midtones, s->magenta_green.highlights); b = get_component(b, l, s->yellow_blue.shadows, s->yellow_blue.midtones, s->yellow_blue.highlights); if (s->preserve_lightness) preservel(&r, &g, &b, l); dst[j + roffset] = av_clip_uint8(lrintf(r * max)); dst[j + goffset] = av_clip_uint8(lrintf(g * max)); dst[j + boffset] = av_clip_uint8(lrintf(b * max)); if (in != out && step == 4) dst[j + aoffset] = src[j + aoffset]; } srcrow += in->linesize[0]; dstrow += out->linesize[0]; } return 0; } static int color_balance16(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) { ColorBalanceContext *s = ctx->priv; ThreadData *td = arg; AVFrame *in = td->in; AVFrame *out = td->out; AVFilterLink *outlink = ctx->outputs[0]; const int slice_start = (out->height * jobnr) / nb_jobs; const int slice_end = (out->height * (jobnr+1)) / nb_jobs; const uint16_t *srcrow = (const uint16_t *)in->data[0] + slice_start * in->linesize[0] / 2; const uint8_t roffset = s->rgba_map[R]; const uint8_t goffset = s->rgba_map[G]; const uint8_t boffset = s->rgba_map[B]; const uint8_t aoffset = s->rgba_map[A]; const int step = s->step / 2; const int depth = s->depth; const float max = s->max; uint16_t *dstrow; int i, j; dstrow = (uint16_t *)out->data[0] + slice_start * out->linesize[0] / 2; for (i = slice_start; i < slice_end; i++) { const uint16_t *src = srcrow; uint16_t *dst = dstrow; for (j = 0; j < outlink->w * step; j += step) { float r = src[j + roffset] / max; float g = src[j + goffset] / max; float b = src[j + boffset] / max; const float l = (FFMAX3(r, g, b) + FFMIN3(r, g, b)); r = get_component(r, l, s->cyan_red.shadows, s->cyan_red.midtones, s->cyan_red.highlights); g = get_component(g, l, s->magenta_green.shadows, s->magenta_green.midtones, s->magenta_green.highlights); b = get_component(b, l, s->yellow_blue.shadows, s->yellow_blue.midtones, s->yellow_blue.highlights); if (s->preserve_lightness) preservel(&r, &g, &b, l); dst[j + roffset] = av_clip_uintp2_c(lrintf(r * max), depth); dst[j + goffset] = av_clip_uintp2_c(lrintf(g * max), depth); dst[j + boffset] = av_clip_uintp2_c(lrintf(b * max), depth); if (in != out && step == 4) dst[j + aoffset] = src[j + aoffset]; } srcrow += in->linesize[0] / 2; dstrow += out->linesize[0] / 2; } return 0; } static int config_output(AVFilterLink *outlink) { AVFilterContext *ctx = outlink->src; ColorBalanceContext *s = ctx->priv; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(outlink->format); const int depth = desc->comp[0].depth; const int max = (1 << depth) - 1; const int planar = av_pix_fmt_count_planes(outlink->format) > 1; s->depth = depth; s->max = max; if (max == 255 && planar) { s->color_balance = color_balance8_p; } else if (planar) { s->color_balance = color_balance16_p; } else if (max == 255) { s->color_balance = color_balance8; } else { s->color_balance = color_balance16; } ff_fill_rgba_map(s->rgba_map, outlink->format); s->step = av_get_padded_bits_per_pixel(desc) >> 3; return 0; } static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; ColorBalanceContext *s = ctx->priv; AVFilterLink *outlink = ctx->outputs[0]; ThreadData td; AVFrame *out; if (av_frame_is_writable(in)) { out = in; } else { out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } td.in = in; td.out = out; ff_filter_execute(ctx, s->color_balance, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx))); if (in != out) av_frame_free(&in); return ff_filter_frame(outlink, out); } static const AVFilterPad colorbalance_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .filter_frame = filter_frame, }, }; static const AVFilterPad colorbalance_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .config_props = config_output, }, }; const AVFilter ff_vf_colorbalance = { .name = "colorbalance", .description = NULL_IF_CONFIG_SMALL("Adjust the color balance."), .priv_size = sizeof(ColorBalanceContext), .priv_class = &colorbalance_class, FILTER_INPUTS(colorbalance_inputs), FILTER_OUTPUTS(colorbalance_outputs), FILTER_PIXFMTS_ARRAY(pix_fmts), .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS, .process_command = ff_filter_process_command, };
e85b2bae947a5810ab4098a877836cbabde2b851
55540f3e86f1d5d86ef6b5d295a63518e274efe3
/components/platform/soc/bl808/bl808_std/BSP_Common/lvgl/lv_port_fs.c
d2a849f0a69dfe49297cb05eca57e186c351ec1d
[ "Apache-2.0" ]
permissive
bouffalolab/bl_iot_sdk
bc5eaf036b70f8c65dd389439062b169f8d09daa
b90664de0bd4c1897a9f1f5d9e360a9631d38b34
refs/heads/master
2023-08-31T03:38:03.369853
2023-08-16T08:50:33
2023-08-18T09:13:27
307,347,250
244
101
Apache-2.0
2023-08-28T06:29:02
2020-10-26T11:16:30
C
UTF-8
C
false
false
21,492
c
lv_port_fs.c
/* * Copyright (c) 2016-2023 Bouffalolab. * * This file is part of * *** Bouffalolab Software Dev Kit *** * (see www.bouffalolab.com). * * 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 Bouffalo Lab 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. */ /** * @file lv_port_fs_templ.c * */ /*Copy this file as "lv_port_fs.c" and set this value to "1" to enable content*/ #if 1 /********************* * INCLUDES *********************/ #include "lv_port_fs.h" #include "stdio.h" #include "string.h" #include "bflb_platform.h" #if LV_USING_FATFS #include "ff.h" #endif #if LV_USING_ROMFS #include "bl_romfs.h" #endif /********************* * DEFINES *********************/ /********************** * TYPEDEFS **********************/ /* Create a type to store the required data about your file. * If you are using a File System library * it already should have a File type. * For example FatFS has `file_t `. In this case use `typedef file_t file_t`*/ typedef uint32_t file_t; /* 没有实际作用, 使用时是通过指针强转的 */ /*Similarly to `file_t` create a type for directory reading too */ typedef uint32_t dir_t; /* 没有实际作用, 使用时是通过指针强转的 */ #if (LV_USING_FATFS) FATFS FS_OBJ_SD; /********************** * STATIC PROTOTYPES **********************/ static void fs_init(void); static lv_fs_res_t fs_open(lv_fs_drv_t *drv, void *file_p, const char *path, lv_fs_mode_t mode); static lv_fs_res_t fs_close(lv_fs_drv_t *drv, void *file_p); static lv_fs_res_t fs_read(lv_fs_drv_t *drv, void *file_p, void *buf, uint32_t btr, uint32_t *br); static lv_fs_res_t fs_write(lv_fs_drv_t *drv, void *file_p, const void *buf, uint32_t btw, uint32_t *bw); static lv_fs_res_t fs_seek(lv_fs_drv_t *drv, void *file_p, uint32_t pos); static lv_fs_res_t fs_size(lv_fs_drv_t *drv, void *file_p, uint32_t *size_p); static lv_fs_res_t fs_tell(lv_fs_drv_t *drv, void *file_p, uint32_t *pos_p); static lv_fs_res_t fs_remove(lv_fs_drv_t *drv, const char *path); static lv_fs_res_t fs_trunc(lv_fs_drv_t *drv, void *file_p); static lv_fs_res_t fs_rename(lv_fs_drv_t *drv, const char *oldname, const char *newname); static lv_fs_res_t fs_free(lv_fs_drv_t *drv, uint32_t *total_p, uint32_t *free_p); static lv_fs_res_t fs_dir_open(lv_fs_drv_t *drv, void *rddir_p, const char *path); static lv_fs_res_t fs_dir_read(lv_fs_drv_t *drv, void *rddir_p, char *fn); static lv_fs_res_t fs_dir_close(lv_fs_drv_t *drv, void *rddir_p); extern void fatfs_sd_driver_register(void); #endif #if (LV_USING_ROMFS) static lv_fs_res_t lvport_romfs_open(lv_fs_drv_t *drv, void *file_p, const char *path, lv_fs_mode_t mode); static lv_fs_res_t lvport_romfs_close(lv_fs_drv_t *drv, void *file_p); static lv_fs_res_t lvport_romfs_size(lv_fs_drv_t *drv, void *file_p, uint32_t *size_p); static lv_fs_res_t lvport_romfs_read(lv_fs_drv_t *drv, void *file_p, void *buf, uint32_t btr, uint32_t *br); static lv_fs_res_t lvport_romfs_seek(lv_fs_drv_t *drv, void *file_p, uint32_t pos); static lv_fs_res_t lvport_romfs_tell(lv_fs_drv_t *drv, void *file_p, uint32_t *pos_p); static lv_fs_res_t lvport_romfs_dir_close(struct _lv_fs_drv_t *drv, void *rddir_p); static lv_fs_res_t lvport_romfs_dir_open(struct _lv_fs_drv_t *drv, void *rddir_p, const char *path); static lv_fs_res_t lvport_romfs_dir_read(struct _lv_fs_drv_t *drv, void *rddir_p, char *fn); #endif /********************** * STATIC VARIABLES **********************/ typedef uint8_t lv_fs_res_t; /********************** * GLOBAL PROTOTYPES **********************/ /********************** * MACROS **********************/ /********************** * GLOBAL FUNCTIONS **********************/ void lv_port_fs_init(void) { /* fatfs init */ #if (LV_USING_FATFS) /*---------------------------------------------------- * Initialize your storage device and File System * -------------------------------------------------*/ fs_init(); /*--------------------------------------------------- * Register the file system interface in LVGL *--------------------------------------------------*/ /* Add a simple drive to open images */ lv_fs_drv_t fs_drv_s; lv_fs_drv_init(&fs_drv_s); /*Set up fields...*/ fs_drv_s.file_size = sizeof(FIL); fs_drv_s.letter = 'S'; fs_drv_s.open_cb = fs_open; fs_drv_s.close_cb = fs_close; fs_drv_s.read_cb = fs_read; fs_drv_s.write_cb = fs_write; fs_drv_s.seek_cb = fs_seek; fs_drv_s.tell_cb = fs_tell; fs_drv_s.free_space_cb = fs_free; fs_drv_s.size_cb = fs_size; fs_drv_s.remove_cb = fs_remove; fs_drv_s.rename_cb = fs_rename; fs_drv_s.trunc_cb = fs_trunc; fs_drv_s.rddir_size = sizeof(DIR); fs_drv_s.dir_close_cb = fs_dir_close; fs_drv_s.dir_open_cb = fs_dir_open; fs_drv_s.dir_read_cb = fs_dir_read; lv_fs_drv_register(&fs_drv_s); #endif /* romfs init */ #if (LV_USING_ROMFS) romfs_mount(); /* Add a simple drive to open images */ lv_fs_drv_t fs_drv_r; lv_fs_drv_init(&fs_drv_r); /*Set up fields...*/ fs_drv_r.file_size = sizeof(romfs_file_t); fs_drv_r.letter = 'R'; fs_drv_r.open_cb = lvport_romfs_open; fs_drv_r.close_cb = lvport_romfs_close; fs_drv_r.read_cb = lvport_romfs_read; fs_drv_r.write_cb = NULL; fs_drv_r.seek_cb = lvport_romfs_seek; fs_drv_r.tell_cb = lvport_romfs_tell; fs_drv_r.free_space_cb = NULL; fs_drv_r.size_cb = lvport_romfs_size; fs_drv_r.remove_cb = NULL; fs_drv_r.rename_cb = NULL; fs_drv_r.trunc_cb = NULL; fs_drv_r.rddir_size = sizeof(romfs_dir_t); fs_drv_r.dir_close_cb = lvport_romfs_dir_close; fs_drv_r.dir_open_cb = lvport_romfs_dir_open; fs_drv_r.dir_read_cb = lvport_romfs_dir_read; lv_fs_drv_register(&fs_drv_r); #endif } #if (LV_USING_FATFS) /********************** * STATIC FUNCTIONS **********************/ lv_fs_res_t res_fatfs_to_lv(FRESULT res) { if (res == FR_OK) { return LV_FS_RES_OK; } switch (res) { case (FR_DISK_ERR): res = LV_FS_RES_HW_ERR; break; case (FR_NO_FILE): res = LV_FS_RES_NOT_EX; break; case (FR_NO_PATH): res = LV_FS_RES_NOT_EX; break; case (FR_NOT_ENOUGH_CORE): res = LV_FS_RES_OUT_OF_MEM; break; case (FR_LOCKED): res = LV_FS_RES_LOCKED; case (FR_TOO_MANY_OPEN_FILES): res = LV_FS_RES_LOCKED; break; case (FR_NO_FILESYSTEM): res = LV_FS_RES_FS_ERR; break; case (FR_WRITE_PROTECTED): res = LV_FS_RES_DENIED; break; case (FR_TIMEOUT): res = LV_FS_RES_TOUT; break; default: res = LV_FS_RES_UNKNOWN; } return res; } /* Initialize your Storage device and File system. */ static void fs_init(void) { /*E.g. for FatFS initialize the SD card and FatFS itself*/ /*You code here*/ fatfs_sd_driver_register(); f_mount(&FS_OBJ_SD, "sd:", 1); } /** * Open a file * @param drv pointer to a driver where this function belongs * @param file_p pointer to a file_t variable * @param path path to the file beginning with the driver letter (e.g. S:/folder/file.txt) * @param mode read: FS_MODE_RD, write: FS_MODE_WR, both: FS_MODE_RD | FS_MODE_WR * @return LV_FS_RES_OK or any error from lv_fs_res_t enum */ static lv_fs_res_t fs_open(lv_fs_drv_t *drv, void *file_p, const char *path, lv_fs_mode_t mode) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; BYTE fatfs_mode; char *path_buf = NULL; switch (drv->letter) { case 'S': path_buf = (char *)malloc(sizeof(char) * (strlen(path) + 5)); sprintf(path_buf, "SD:/%s", path); break; default: return LV_FS_RES_NOT_EX; break; } switch (mode) { case (LV_FS_MODE_RD): fatfs_mode = FA_READ; break; case (LV_FS_MODE_WR): fatfs_mode = FA_WRITE; break; case (LV_FS_MODE_WR | LV_FS_MODE_RD): fatfs_mode = FA_WRITE | FA_READ; break; default: fatfs_mode = LV_FS_MODE_RD; break; } res = f_open((FIL *)file_p, path_buf, fatfs_mode); res = res_fatfs_to_lv(res); lv_mem_free(path_buf); return res; } /** * Close an opened file * @param drv pointer to a driver where this function belongs * @param file_p pointer to a file_t variable. (opened with lv_ufs_open) * @return LV_FS_RES_OK: no error, the file is read * any error from lv_fs_res_t enum */ static lv_fs_res_t fs_close(lv_fs_drv_t *drv, void *file_p) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ res = f_close((FIL *)file_p); res = res_fatfs_to_lv(res); return res; } /** * Read data from an opened file * @param drv pointer to a driver where this function belongs * @param file_p pointer to a file_t variable. * @param buf pointer to a memory block where to store the read data * @param btr number of Bytes To Read * @param br the real number of read bytes (Byte Read) * @return LV_FS_RES_OK: no error, the file is read * any error from lv_fs_res_t enum */ static lv_fs_res_t fs_read(lv_fs_drv_t *drv, void *file_p, void *buf, uint32_t btr, uint32_t *br) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ res = f_read((FIL *)file_p, buf, btr, (UINT *)br); res = res_fatfs_to_lv(res); return res; } /** * Write into a file * @param drv pointer to a driver where this function belongs * @param file_p pointer to a file_t variable * @param buf pointer to a buffer with the bytes to write * @param btr Bytes To Write * @param br the number of real written bytes (Bytes Written). NULL if unused. * @return LV_FS_RES_OK or any error from lv_fs_res_t enum */ static lv_fs_res_t fs_write(lv_fs_drv_t *drv, void *file_p, const void *buf, uint32_t btw, uint32_t *bw) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ res = f_write((FIL *)file_p, buf, btw, (UINT *)bw); res = res_fatfs_to_lv(res); return res; } /** * Set the read write pointer. Also expand the file size if necessary. * @param drv pointer to a driver where this function belongs * @param file_p pointer to a file_t variable. (opened with lv_ufs_open ) * @param pos the new position of read write pointer * @return LV_FS_RES_OK: no error, the file is read * any error from lv_fs_res_t enum */ static lv_fs_res_t fs_seek(lv_fs_drv_t *drv, void *file_p, uint32_t pos) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ res = f_lseek((FIL *)file_p, pos); res = res_fatfs_to_lv(res); return res; } /** * Give the size of a file bytes * @param drv pointer to a driver where this function belongs * @param file_p pointer to a file_t variable * @param size pointer to a variable to store the size * @return LV_FS_RES_OK or any error from lv_fs_res_t enum */ static lv_fs_res_t fs_size(lv_fs_drv_t *drv, void *file_p, uint32_t *size_p) { //lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ *size_p = f_size((FIL *)file_p); return LV_FS_RES_OK; } /** * Give the position of the read write pointer * @param drv pointer to a driver where this function belongs * @param file_p pointer to a file_t variable. * @param pos_p pointer to to store the result * @return LV_FS_RES_OK: no error, the file is read * any error from lv_fs_res_t enum */ static lv_fs_res_t fs_tell(lv_fs_drv_t *drv, void *file_p, uint32_t *pos_p) { //lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ *pos_p = f_tell((FIL *)file_p); return LV_FS_RES_OK; } /** * Delete a file * @param drv pointer to a driver where this function belongs * @param path path of the file to delete * @return LV_FS_RES_OK or any error from lv_fs_res_t enum */ static lv_fs_res_t fs_remove(lv_fs_drv_t *drv, const char *path) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ char *path_buf = NULL; switch (drv->letter) { case 'S': path_buf = (char *)malloc(sizeof(char) * (strlen(path) + 5)); sprintf(path_buf, "SD:/%s", path); break; default: return LV_FS_RES_NOT_EX; break; } res = f_unlink(path_buf); res = res_fatfs_to_lv(res); lv_mem_free(path_buf); return res; } /** * Truncate the file size to the current position of the read write pointer * @param drv pointer to a driver where this function belongs * @param file_p pointer to an 'ufs_file_t' variable. (opened with lv_fs_open ) * @return LV_FS_RES_OK: no error, the file is read * any error from lv_fs_res_t enum */ static lv_fs_res_t fs_trunc(lv_fs_drv_t *drv, void *file_p) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ res = f_truncate((FIL *)file_p); res = res_fatfs_to_lv(res); return res; } /** * Rename a file * @param drv pointer to a driver where this function belongs * @param oldname path to the file * @param newname path with the new name * @return LV_FS_RES_OK or any error from 'fs_res_t' */ static lv_fs_res_t fs_rename(lv_fs_drv_t *drv, const char *oldname, const char *newname) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ char *path_old_buf = NULL; char *path_new_buf = NULL; switch (drv->letter) { case 'S': path_old_buf = (char *)malloc(sizeof(char) * (strlen(oldname) + 5)); path_new_buf = (char *)malloc(sizeof(char) * (strlen(newname) + 5)); sprintf(path_old_buf, "SD:/%s", oldname); sprintf(path_new_buf, "SD:/%s", newname); break; default: return LV_FS_RES_NOT_EX; break; } res = f_rename(path_old_buf, path_new_buf); res = res_fatfs_to_lv(res); lv_mem_free(path_old_buf); lv_mem_free(path_new_buf); return res; } /** * Get the free and total size of a driver in kB * @param drv pointer to a driver where this function belongs * @param letter the driver letter * @param total_p pointer to store the total size [kB] * @param free_p pointer to store the free size [kB] * @return LV_FS_RES_OK or any error from lv_fs_res_t enum */ static lv_fs_res_t fs_free(lv_fs_drv_t *drv, uint32_t *total_p, uint32_t *free_p) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; char *path = NULL; FATFS *fs_obj; /* Add your code here*/ switch (drv->letter) { case 'S': path = "SD:"; fs_obj = &FS_OBJ_SD; break; default: return LV_FS_RES_NOT_EX; break; } res = f_getfree(path, free_p, &fs_obj); *free_p = (fs_obj->csize) * (*free_p) / 1024; *total_p = (fs_obj->csize) * (fs_obj->n_fatent - 2) / 1024; res = res_fatfs_to_lv(res); return res; } /** * Initialize a 'lv_fs_dir_t' variable for directory reading * @param drv pointer to a driver where this function belongs * @param rddir_p pointer to a 'lv_fs_dir_t' variable * @param path path to a directory * @return LV_FS_RES_OK or any error from lv_fs_res_t enum */ static lv_fs_res_t fs_dir_open(lv_fs_drv_t *drv, void *rddir_p, const char *path) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ char *path_buf = NULL; switch (drv->letter) { case 'S': path_buf = (char *)malloc(sizeof(char) * (strlen(path) + 5)); sprintf(path_buf, "SD:/%s", path); break; default: return LV_FS_RES_NOT_EX; break; } res = f_opendir(rddir_p, path_buf); res = res_fatfs_to_lv(res); lv_mem_free(path_buf); return res; } /** * Read the next filename form a directory. * The name of the directories will begin with '/' * @param drv pointer to a driver where this function belongs * @param rddir_p pointer to an initialized 'lv_fs_dir_t' variable * @param fn pointer to a buffer to store the filename * @return LV_FS_RES_OK or any error from lv_fs_res_t enum */ static lv_fs_res_t fs_dir_read(lv_fs_drv_t *drv, void *rddir_p, char *fn) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; FILINFO entry; /* Add your code here*/ res = f_readdir(rddir_p, &entry); res = res_fatfs_to_lv(res); if (res == LV_FS_RES_OK) { sprintf(fn, "%s%s", (entry.fattrib & AM_DIR) ? "/" : "", entry.fname); } return res; } /** * Close the directory reading * @param drv pointer to a driver where this function belongs * @param rddir_p pointer to an initialized 'lv_fs_dir_t' variable * @return LV_FS_RES_OK or any error from lv_fs_res_t enum */ static lv_fs_res_t fs_dir_close(lv_fs_drv_t *drv, void *rddir_p) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ f_closedir((DIR *)rddir_p); res = res_fatfs_to_lv(res); return res; } #endif #if (LV_USING_ROMFS) static lv_fs_res_t lvport_romfs_open(lv_fs_drv_t *drv, void *file_p, const char *path, lv_fs_mode_t mode) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; char *path_buf = NULL; switch (drv->letter) { case 'R': path_buf = (char *)malloc(sizeof(char) * (strlen(path) + 8)); sprintf(path_buf, "/romfs/%s", path); break; default: return LV_FS_RES_NOT_EX; break; } res = romfs_open((romfs_file_t *)file_p, path_buf, mode); lv_mem_free(path_buf); return res; } static lv_fs_res_t lvport_romfs_close(lv_fs_drv_t *drv, void *file_p) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ res = romfs_close((romfs_file_t *)file_p); return res; } static lv_fs_res_t lvport_romfs_read(lv_fs_drv_t *drv, void *file_p, void *buf, uint32_t btr, uint32_t *br) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ uint32_t num = romfs_read((romfs_file_t *)file_p, buf, btr); if (num > 0) { *br = num; res = 0; }else{ res = num; } return res; } static lv_fs_res_t lvport_romfs_seek(lv_fs_drv_t *drv, void *file_p, uint32_t pos) { lv_fs_res_t res = LV_FS_RES_NOT_IMP; /* Add your code here*/ res = romfs_lseek((romfs_file_t *)file_p, pos, ROMFS_SEEK_SET); if (res > 0) { res = 0; } return res; } static lv_fs_res_t lvport_romfs_tell(lv_fs_drv_t *drv, void *file_p, uint32_t *pos_p) { if(file_p == NULL){ return -1; } *pos_p = ((romfs_file_t *)file_p)->offset; return 0; } static lv_fs_res_t lvport_romfs_dir_close(struct _lv_fs_drv_t *drv, void *rddir_p) { return romfs_closedir((romfs_dir_t *)rddir_p); } static lv_fs_res_t lvport_romfs_dir_open(struct _lv_fs_drv_t *drv, void *rddir_p,const char *path) { char *path_buf = NULL; if(rddir_p == NULL){ return LV_FS_RES_UNKNOWN; } path_buf = (char *)malloc(sizeof(char) * (strlen(path) + 8)); sprintf(path_buf, "/romfs/%s", path); return romfs_opendir((romfs_dir_t *)rddir_p,(const char *)path_buf); } static lv_fs_res_t lvport_romfs_dir_read(struct _lv_fs_drv_t *drv, void *rddir_p, char *fn) { if(rddir_p == NULL){ return LV_FS_RES_UNKNOWN; } romfs_dirent_t *romfs_dirent = romfs_readdir((romfs_dir_t *)rddir_p); if(romfs_dirent == NULL){ return LV_FS_RES_UNKNOWN; } if(fn != NULL){ memcpy((void*)fn,(const void*)romfs_dirent,sizeof(romfs_dirent_t)); } return LV_FS_RES_OK; } static lv_fs_res_t lvport_romfs_size(lv_fs_drv_t *drv, void *file_p, uint32_t *size_p) { /* Add your code here*/ int res = romfs_size((romfs_file_t *)file_p); if(res<0){ return LV_FS_RES_UNKNOWN; } *size_p = res; return LV_FS_RES_OK; } #endif #else /* Enable this file at the top */ /* This dummy typedef exists purely to silence -Wpedantic. */ typedef int keep_pedantic_happy; #endif
1d744568f0365e65a8bf8b5b2d64d2f597edcd60
3a30cfb29aac91e5c75d4dbcefddfd1f34d5f18c
/c-tests/gcc/980602-1.c
6d88a6d4ca3da5c4dc910ad19537277a2699a421
[ "MIT", "MPL-1.0", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LGPL-2.0-only", "GPL-3.0-only", "GPL-2.0-only" ]
permissive
vnmakarov/mir
a1725bc9c828e8580df6b7ae94e04175db8abe93
928e28fb3acaa50d051a906e76a55cc48a556574
refs/heads/master
2023-09-02T11:10:37.434581
2023-08-25T19:25:40
2023-08-25T19:25:40
178,932,492
2,005
156
MIT
2023-08-01T20:29:59
2019-04-01T19:24:56
C
UTF-8
C
false
false
122
c
980602-1.c
extern void exit (int); main() { int i; for (i = 1; i < 100; i++) ; if (i == 100) exit (0); abort (); }
a72ff1a0994653ec94b722211e9a37a840406df3
99bdb3251fecee538e0630f15f6574054dfc1468
/examples/utest/testcases/posix/unistd_h/functions/rmdir_tc.c
f289ddf8f48532472768a538a3394e45890f2618
[ "Apache-2.0" ]
permissive
RT-Thread/rt-thread
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
3602f891211904a27dcbd51e5ba72fefce7326b2
refs/heads/master
2023-09-01T04:10:20.295801
2023-08-31T16:20:55
2023-08-31T16:20:55
7,408,108
9,599
5,805
Apache-2.0
2023-09-14T13:37:26
2013-01-02T14:49:21
C
UTF-8
C
false
false
524
c
rmdir_tc.c
#include <unistd.h> #include <sys/stat.h> #define RM_DIR "./rmdir" static int rmdir_entry(void) { int res = 0; res = mkdir(RM_DIR, 0x777); if(res != 0) { return -1; } res = rmdir(RM_DIR); if(res != 0) { return -1; } return res; } #include <utest.h> static void test_rmdir(void) { uassert_int_equal(rmdir_entry(), 0); } static void testcase(void) { UTEST_UNIT_RUN(test_rmdir); } UTEST_TC_EXPORT(testcase, "posix.unistd_h.rmdir_tc.c", RT_NULL, RT_NULL, 10);
2bd117dcfcf69fc58ab7f61f9eb3e963dc2e822f
b6acd6eed2b8946c1c1e19fa30081cbab0a2954f
/starry_fmu/Framework/include/param.h
b759edc9970d900cc7605aeb831cc6007c1497fa
[ "BSD-3-Clause" ]
permissive
JcZou/StarryPilot
7ce1ed454f133ccd30d71916811e2bf23196d2eb
97af0338a54e1eeece877c72222aeaf4b7e80ad7
refs/heads/master
2023-03-12T19:10:17.225314
2021-11-27T19:44:26
2021-11-27T19:44:26
137,048,745
304
172
BSD-3-Clause
2020-08-26T07:34:49
2018-06-12T09:27:59
C
UTF-8
C
false
false
6,930
h
param.h
/* * File : param.h * * * Change Logs: * Date Author Notes * 2016-07-01 zoujiachi the first version */ #ifndef __PARAM_H__ #define __PARAM_H__ #include <stm32f4xx.h> #include "quaternion.h" #define PARAM_MAX_NAME_LEN typedef struct { /* firmware version */ uint16_t version; /* sensor compensate param */ float accOffset[3]; float accTransMat[3][3]; float magOffset[3]; float magTransMat[3][3]; float gyr_offset[3]; float gyr_gain[3]; /* attitude control pid param */ float att_angle_p[3]; float att_angle_i[3]; float att_angle_d[3]; float att_rate_p[3]; float att_rate_i[3]; float att_rate_d[3]; /* attitude integrate limit */ float att_i_limit[3]; /* attitude rate integrate limit */ float att_rate_i_limit[3]; /* attitude control output limit */ float att_control_limit[3]; /* altitude control pid param */ float alt_p; float alt_i; float alt_d; float alt_vel_p; float alt_vel_i; float alt_vel_d; float alt_acc_p; float alt_acc_i; float alt_acc_d; }PARAM_Def; typedef union { int32_t i; uint32_t u; float f; }param_value_t; typedef enum{ PARAM_TYPE_INT32 = 0, PARAM_TYPE_UINT32, PARAM_TYPE_FLOAT, PARAM_TYPE_UNKNOWN = 0xffff } param_type_t; typedef struct{ const char* name; const param_type_t type; param_value_t val; }param_info_t; #define PARAM_DECLARE(_name) param_info_t _name #define PARAM_DEFINE_INT32(_name, _default) \ { \ .name = #_name, \ .type = PARAM_TYPE_INT32, \ .val.i = _default \ } #define PARAM_DEFINE_UINT32(_name, _default) \ { \ .name = #_name, \ .type = PARAM_TYPE_UINT32, \ .val.u = _default \ } #define PARAM_DEFINE_FLOAT(_name, _default) \ { \ .name = #_name, \ .type = PARAM_TYPE_FLOAT, \ .val.f = _default \ } #define PARAM_GROUP(_group) _param_##_group #define PARAM_DECLARE_GROUP(_group) _param_##_group##_t #define PARAM_DEFINE_GROUP(_group) \ { \ .name = #_group, \ .param_num = sizeof(_param_##_group##_t)/sizeof(param_info_t), \ .content = (param_info_t*)&_param_##_group##_t \ } /* step 1: Parameter Declare */ typedef struct { PARAM_DECLARE(GYR_X_OFFSET); PARAM_DECLARE(GYR_Y_OFFSET); PARAM_DECLARE(GYR_Z_OFFSET); PARAM_DECLARE(GYR_X_GAIN); PARAM_DECLARE(GYR_Y_GAIN); PARAM_DECLARE(GYR_Z_GAIN); PARAM_DECLARE(GYR_CALIB); PARAM_DECLARE(ACC_X_OFFSET); PARAM_DECLARE(ACC_Y_OFFSET); PARAM_DECLARE(ACC_Z_OFFSET); PARAM_DECLARE(ACC_TRANS_MAT00); PARAM_DECLARE(ACC_TRANS_MAT01); PARAM_DECLARE(ACC_TRANS_MAT02); PARAM_DECLARE(ACC_TRANS_MAT10); PARAM_DECLARE(ACC_TRANS_MAT11); PARAM_DECLARE(ACC_TRANS_MAT12); PARAM_DECLARE(ACC_TRANS_MAT20); PARAM_DECLARE(ACC_TRANS_MAT21); PARAM_DECLARE(ACC_TRANS_MAT22); PARAM_DECLARE(ACC_CALIB); PARAM_DECLARE(MAG_X_OFFSET); PARAM_DECLARE(MAG_Y_OFFSET); PARAM_DECLARE(MAG_Z_OFFSET); PARAM_DECLARE(MAG_TRANS_MAT00); PARAM_DECLARE(MAG_TRANS_MAT01); PARAM_DECLARE(MAG_TRANS_MAT02); PARAM_DECLARE(MAG_TRANS_MAT10); PARAM_DECLARE(MAG_TRANS_MAT11); PARAM_DECLARE(MAG_TRANS_MAT12); PARAM_DECLARE(MAG_TRANS_MAT20); PARAM_DECLARE(MAG_TRANS_MAT21); PARAM_DECLARE(MAG_TRANS_MAT22); PARAM_DECLARE(MAG_CALIB); }PARAM_GROUP(CALIBRATION); typedef struct { PARAM_DECLARE(ATT_ROLL_P); PARAM_DECLARE(ATT_ROLL_RATE_P); PARAM_DECLARE(ATT_ROLL_RATE_I); PARAM_DECLARE(ATT_ROLL_RATE_D); PARAM_DECLARE(ATT_PITCH_P); PARAM_DECLARE(ATT_PITCH_RATE_P); PARAM_DECLARE(ATT_PITCH_RATE_I); PARAM_DECLARE(ATT_PITCH_RATE_D); PARAM_DECLARE(ATT_YAW_P); PARAM_DECLARE(ATT_YAW_RATE_P); PARAM_DECLARE(ATT_YAW_RATE_I); PARAM_DECLARE(ATT_YAW_RATE_D); PARAM_DECLARE(ATT_ROLLOUT_LIM); PARAM_DECLARE(ATT_PITCHOUT_LIM); PARAM_DECLARE(ATT_YAWOUT_LIM); PARAM_DECLARE(ATT_ROLLR_I_LIM); PARAM_DECLARE(ATT_PITCHR_I_LIM); PARAM_DECLARE(ATT_YAWR_I_LIM); }PARAM_GROUP(ATT_CONTROLLER); typedef struct { PARAM_DECLARE(ALT_P); PARAM_DECLARE(ALT_RATE_P); PARAM_DECLARE(ALT_ACC_P); PARAM_DECLARE(ALT_ACC_I); PARAM_DECLARE(ALT_ACC_D); PARAM_DECLARE(ALT_ERR_MIN); PARAM_DECLARE(ALT_ERR_MAX); PARAM_DECLARE(VEL_ERR_MIN); PARAM_DECLARE(VEL_ERR_MAX); PARAM_DECLARE(ACC_ERR_MIN); PARAM_DECLARE(ACC_ERR_MAX); PARAM_DECLARE(ALT_OUTPUT_MIN); PARAM_DECLARE(ALT_OUTPUT_MAX); PARAM_DECLARE(VEL_OUTPUT_MIN); PARAM_DECLARE(VEL_OUTPUT_MAX); PARAM_DECLARE(ACC_OUTPUT_MIN); PARAM_DECLARE(ACC_OUTPUT_MAX); PARAM_DECLARE(ACC_I_MIN); PARAM_DECLARE(ACC_I_MAX); PARAM_DECLARE(FEEDFORWARD_EN); PARAM_DECLARE(ACC_ERR_LPF_EN); PARAM_DECLARE(ACC_ERR_LPF_FREQ); }PARAM_GROUP(ALT_CONTROLLER); typedef struct { PARAM_DECLARE(ADRC_ENABLE); PARAM_DECLARE(ADRC_MODE); PARAM_DECLARE(TD_CONTROL_R2); PARAM_DECLARE(TD_CONTROL_H2F); PARAM_DECLARE(TD_R0); PARAM_DECLARE(NLSEF_R1); PARAM_DECLARE(NLSEF_H1F); PARAM_DECLARE(NLSEF_C); PARAM_DECLARE(NLSEF_KI); PARAM_DECLARE(LESO_W); // PARAM_DECLARE(ADRC_BETA1); // PARAM_DECLARE(ADRC_BETA2); // PARAM_DECLARE(ADRC_ALPHA); // PARAM_DECLARE(ADRC_DELTA); PARAM_DECLARE(T_UP); PARAM_DECLARE(T_DOWN); PARAM_DECLARE(GAMMA); PARAM_DECLARE(B0); }PARAM_GROUP(ADRC_ATT); typedef struct { PARAM_DECLARE(HIL_ATT_EST_PRD); PARAM_DECLARE(HIL_POS_EST_PRD); PARAM_DECLARE(HIL_CONTROL_PRD); }PARAM_GROUP(HIL_SIM); /* Parameter Declare End */ #define PARAM_GET(_group, _name) ((_param_##_group *)(param_list._param_##_group.content))->_name #define PARAM_GET_INT32(_group, _name) ((_param_##_group *)(param_list._param_##_group.content))->_name.val.i #define PARAM_GET_UINT32(_group, _name) ((_param_##_group *)(param_list._param_##_group.content))->_name.val.u #define PARAM_GET_FLOAT(_group, _name) ((_param_##_group *)(param_list._param_##_group.content))->_name.val.f #define PARAM_SET_INT32(_group, _name, _val) ((_param_##_group *)(param_list._param_##_group.content))->_name.val.i = _val #define PARAM_SET_UINT32(_group, _name, _val) ((_param_##_group *)(param_list._param_##_group.content))->_name.val.u = _val #define PARAM_SET_FLOAT(_group, _name, _val) ((_param_##_group *)(param_list._param_##_group.content))->_name.val.f = _val typedef struct{ const char* name; const uint32_t param_num; param_info_t* content; }param_group_info; /* step 2: param list declare */ typedef struct{ param_group_info PARAM_GROUP(CALIBRATION); param_group_info PARAM_GROUP(ATT_CONTROLLER); param_group_info PARAM_GROUP(ALT_CONTROLLER); param_group_info PARAM_GROUP(ADRC_ATT); param_group_info PARAM_GROUP(HIL_SIM); }param_list_t; extern param_list_t param_list; uint8_t param_init(void); const PARAM_Def * get_param(void); void param_release(void); param_info_t* param_get(char* group_name, char* param_name); param_info_t* param_get_by_name(char* param_name); void param_traverse(void (*param_ops)(param_info_t* param)); uint32_t param_get_info_count(void); uint32_t param_get_info_index(char* param_name); int param_set_by_info(param_info_t* param, float val); int param_get_by_info(param_info_t* param, float *val); #endif
fe423ce3d2737bb1227c6f6c573b899753d2688e
c6759b857e55991fea3ef0b465dbcee53fa38714
/rtos/pmsis/bsp/ram/spiram/spiram.c
b32df0772ca67a1e5bf035bed0a8a3062baed98f
[ "Apache-2.0" ]
permissive
GreenWaves-Technologies/gap_sdk
1b343bba97b7a5ce62a24162bd72eef5cc67e269
3fea306d52ee33f923f2423c5a75d9eb1c07e904
refs/heads/master
2023-09-01T14:38:34.270427
2023-08-10T09:04:44
2023-08-10T09:04:44
133,324,605
145
96
Apache-2.0
2023-08-27T19:03:52
2018-05-14T07:50:29
C
UTF-8
C
false
false
13,148
c
spiram.c
/* * Copyright (C) 2019 GreenWaves Technologies * * 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. */ /* * Authors: Germain Haugou, GreenWaves Technologies (germain.haugou@greenwaves-technologies.com) */ #include "pmsis.h" #include "bsp/bsp.h" #include "bsp/ram/spiram.h" #include "pmsis/drivers/spi.h" #include "../extern_alloc.h" #if !defined(POS_TRACE) #define POS_WARNING(x...) #endif #if !defined(__TRACE_ALL__) && !defined(__TRACE_RAM__) || !defined(POS_TRACE) #define RAM_TRACE(x...) #else #define RAM_TRACE(level, x...) POS_TRACE(level, "[RAM] " x) #endif #define SPIRAM_CS_PULSE_WIDTH_NS 8000 /** * pi_task : * data[0] = l2_buf * data[1] = size * data[2] = l3_addr * data[3] = flags */ typedef struct { uint32_t page_size; /* Fifo of waiting tasks. */ pi_task_t *fifo_head; pi_task_t *fifo_tail; uint32_t *buffer; struct pi_device spi_device; extern_alloc_t alloc; pi_task_t pending_task; } spiram_t; static inline uint32_t __spiram_fifo_task_enqueue(spiram_t *spiram, pi_task_t *task); static inline pi_task_t *__spiram_fifo_task_pop(spiram_t *spiram); static void __spiram_copy_async_exec(pi_device_t *device, struct pi_task *task); static void __spiram_task_handler(void *arg); static int __spiram_task_enqueue(spiram_t *spiram, uint32_t addr, void *buffer, uint32_t size, int ext2loc, pi_task_t *task); static int __spiram_send_cmd(spiram_t *spiram, uint32_t cmd, uint32_t flags) { *spiram->buffer = cmd; pi_spi_send(&spiram->spi_device, (uint8_t *)spiram->buffer, 8, flags); return 0; } static inline uint32_t __spiram_fifo_task_enqueue(spiram_t *spiram, pi_task_t *task) { uint32_t status = 0; task->next = NULL; if (spiram->fifo_head == NULL) { spiram->fifo_head = task; } else { spiram->fifo_tail->next = task; status = 1; } spiram->fifo_tail = task; return status; } static inline pi_task_t *__spiram_fifo_task_pop(spiram_t *spiram) { pi_task_t *task_to_return = NULL; if (spiram->fifo_head != NULL) { task_to_return = spiram->fifo_head; spiram->fifo_head = spiram->fifo_head->next; } return task_to_return; } static void __spiram_copy_async_exec(pi_device_t *device, struct pi_task *task) { spiram_t *spiram = (spiram_t *) device->data; #if defined(PMSIS_DRIVERS) || defined(__PULPOS2__) uint32_t buffer = task->data[0]; uint32_t iter_size = task->data[1]; uint32_t addr = task->data[2]; uint32_t flags = task->data[3]; uint32_t mask_addr = (spiram->page_size - 1); mask_addr = addr & mask_addr; if ((mask_addr + iter_size) > spiram->page_size) { iter_size = (spiram->page_size - mask_addr); } /* Reenqueue */ task->data[0] += iter_size; task->data[1] -= iter_size; task->data[2] += iter_size; #else uint32_t buffer = task->implem.data[0]; uint32_t iter_size = task->implem.data[1]; uint32_t addr = task->implem.data[2]; uint32_t flags = task->implem.data[3]; uint32_t mask_addr = (spiram->page_size - 1); mask_addr = addr & mask_addr; if ((mask_addr + iter_size) > spiram->page_size) { iter_size = (spiram->page_size - mask_addr); } /* Reenqueue */ task->implem.data[0] += iter_size; task->implem.data[1] -= iter_size; task->implem.data[2] += iter_size; #endif /* PMSIS_DRIVERS || __PULPOS2__ */ pi_task_callback(&(spiram->pending_task), __spiram_task_handler, device); pi_spi_copy_async(&(spiram->spi_device), addr, (void *) buffer, iter_size, flags, &(spiram->pending_task)); } static void __spiram_task_handler(void *arg) { uint32_t irq = disable_irq(); uint32_t pending_size = 0; struct pi_device *device = (struct pi_device *) arg; spiram_t *spiram = (spiram_t *) device->data; pi_task_t *task = NULL, *next_task = NULL; task = spiram->fifo_head; #if defined(PMSIS_DRIVERS) || defined(__PULPOS2__) pending_size = task->data[1]; #else pending_size = task->implem.data[1]; #endif /* PMSIS_DRIVERS || __PULPOS2__ */ if (pending_size) { /* Reenqueue pending data. */ __spiram_copy_async_exec(device, task); } else { task = __spiram_fifo_task_pop(spiram); /* Execute user task. */ pi_task_push(task); next_task = spiram->fifo_head; if (next_task != NULL) { /* Exec next task. */ __spiram_copy_async_exec(device, next_task); } } restore_irq(irq); } static int __spiram_task_enqueue(spiram_t *spiram, uint32_t addr, void *buffer, uint32_t size, int ext2loc, pi_task_t *task) { uint32_t irq = disable_irq(); uint32_t status = 0; uint32_t flags = ext2loc ? PI_SPI_COPY_EXT2LOC : PI_SPI_COPY_LOC2EXT; #if defined(PMSIS_DRIVERS) || defined(__PULPOS2__) task->data[0] = (uint32_t) buffer; task->data[1] = size; task->data[2] = addr; task->data[3] = (flags | PI_SPI_CS_AUTO | PI_SPI_LINES_QUAD); #else task->implem.data[0] = (uint32_t) buffer; task->implem.data[1] = size; task->implem.data[2] = addr; task->implem.data[3] = (flags | PI_SPI_CS_AUTO | PI_SPI_LINES_QUAD); #endif /* PMSIS_DRIVERS || __PULPOS2__ */ status = __spiram_fifo_task_enqueue(spiram, task); restore_irq(irq); return status; } static int spiram_open(struct pi_device *device) { RAM_TRACE(POS_LOG_INFO, "Opening SPIRAM device (device: %p)\n", device); struct pi_spiram_conf *conf = (struct pi_spiram_conf *)device->config; spiram_t *spiram = (spiram_t *)pi_fc_l1_malloc(sizeof(spiram_t)); if (spiram == NULL) { POS_WARNING("[SPIRAM] Error during driver opening: failed to allocate memory for internal structure\n"); goto error0; } spiram->buffer = pi_l2_malloc(sizeof(uint32_t)); if (spiram == NULL) { POS_WARNING("[SPIRAM] Error during driver opening: failed to allocate memory for internal structure\n"); goto error1; } spiram->fifo_head = NULL; spiram->fifo_tail = NULL; spiram->page_size = 1024; device->data = (void *)spiram; if (extern_alloc_init(&spiram->alloc, 0, conf->ram_size)) { POS_WARNING("[SPIRAM] Error during driver opening: failed to allocate memory for internal structure\n"); goto error2; } if (bsp_spiram_open(conf)) { POS_WARNING("[SPIRAM] Error during driver opening: failed to init bsp for spiram\n"); goto error3; } struct pi_spi_conf spi_conf; pi_spi_conf_init(&spi_conf); spi_conf.itf = conf->spi_itf; spi_conf.cs = conf->spi_cs; spi_conf.max_rcv_chunk_size = SPIRAM_CS_PULSE_WIDTH_NS; spi_conf.max_snd_chunk_size = SPIRAM_CS_PULSE_WIDTH_NS; spi_conf.max_baudrate = conf->baudrate*2; pi_open_from_conf(&spiram->spi_device, &spi_conf); int32_t error = pi_spi_open(&spiram->spi_device); if (error) { POS_WARNING("[SPIRAM] Error during driver opening: failed to open spi driver\n"); goto error3; } // TODO once this can be tested on the board, clean-up these writes // SAFE_PADCFG8 for D2 , A11, B10, A10 - HIGH drive, pull disabled #define SAFE_PADCFG8 ((uint32_t*)0x1A1041A0) *SAFE_PADCFG8 = 0x02020202; // SAFE_PADCFG9 for B8, A8, B7, (A9)- HIGH drive, pull disabled #define SAFE_PADCFG9 ((uint32_t*)0x1A1041A4) *SAFE_PADCFG9 = 0x02020202; volatile int i; //for (i=0; i<1000000; i++); //pi_time_wait_us(100000); __spiram_send_cmd(spiram, 0x66, PI_SPI_CS_AUTO | PI_SPI_LINES_QUAD); //for (i=0; i<1000000; i++); //pi_time_wait_us(100000); __spiram_send_cmd(spiram, 0x99, PI_SPI_CS_AUTO | PI_SPI_LINES_QUAD); //for (i=0; i<1000000; i++); //pi_time_wait_us(100000); __spiram_send_cmd(spiram, 0x35, PI_SPI_CS_AUTO); //for (i=0; i<1000000; i++); //pi_time_wait_us(100000); uint32_t ucode[4]; ucode[0] = SPI_UCODE_CMD_SEND_CMD(0x38, 8, 1); ucode[1] = SPI_UCODE_CMD_SEND_ADDR(24, 1); uint8_t *send_ucode = pi_spi_send_ucode_set(&spiram->spi_device, (uint8_t *)ucode, 3*4); if (send_ucode == NULL) { POS_WARNING("[SPIRAM] Error during driver opening: failed to set microcode\n"); goto error4; } pi_spi_send_ucode_set_addr_info(&spiram->spi_device, send_ucode + 2*4 + 1, 3); ucode[0] = SPI_UCODE_CMD_SEND_CMD(0xEB, 8, 1); ucode[1] = SPI_UCODE_CMD_SEND_ADDR(24, 1); ucode[3] = SPI_CMD_DUMMY(6); uint8_t *receive_ucode = pi_spi_receive_ucode_set(&spiram->spi_device, (uint8_t *)ucode, 4*4); if (receive_ucode == NULL) { POS_WARNING("[SPIRAM] Error during driver opening: failed to set microcode\n"); goto error4; } pi_spi_receive_ucode_set_addr_info(&spiram->spi_device, receive_ucode + 2*4 + 1, 3); RAM_TRACE(POS_LOG_INFO, "Opened SPIRAM device with success (device: %p)\n", device); return 0; error4: pi_spi_close(&spiram->spi_device); error3: extern_alloc_deinit(&spiram->alloc); error2: pi_l2_free(spiram->buffer, sizeof(uint32_t)); error1: pi_fc_l1_free(spiram, sizeof(spiram_t)); error0: return -1; } static void spiram_close(struct pi_device *device) { spiram_t *spiram = (spiram_t *)device->data; RAM_TRACE(POS_LOG_INFO, "Closing SPIRAM device (device: %p)\n", device); pi_spi_close(&spiram->spi_device); extern_alloc_deinit(&spiram->alloc); pi_l2_free(spiram->buffer, sizeof(uint32_t)); pi_fc_l1_free(spiram, sizeof(spiram_t)); } static void spiram_copy_async(struct pi_device *device, uint32_t addr, void *data, uint32_t size, int ext2loc, pi_task_t *task) { spiram_t *spiram = (spiram_t *)device->data; if (__spiram_task_enqueue(spiram, addr, data, size, ext2loc, task)) { return; } __spiram_copy_async_exec(device, task); } static void spiram_copy_2d_async(struct pi_device *device, uint32_t addr, void *data, uint32_t size, uint32_t stride, uint32_t length, int ext2loc, pi_task_t *task) { spiram_t *spiram = (spiram_t *)device->data; int flags = ext2loc ? PI_SPI_COPY_EXT2LOC : PI_SPI_COPY_LOC2EXT; pi_spi_copy_2d_async(&spiram->spi_device, addr, data, size, stride, length, flags | PI_SPI_CS_AUTO | PI_SPI_LINES_QUAD, task); } int spiram_alloc(struct pi_device *device, uint32_t *addr, uint32_t size) { void *chunk; spiram_t *spiram = (spiram_t *)device->data; int err = extern_alloc(&spiram->alloc, size, &chunk); *addr = (uint32_t)chunk; return err; } int spiram_free(struct pi_device *device, uint32_t addr, uint32_t size) { spiram_t *spiram = (spiram_t *)device->data; return extern_free(&spiram->alloc, size, (void *)addr); } #if 0 void __pi_spiram_alloc_cluster_req(void *_req) { pi_cl_spiram_alloc_req_t *req = (pi_cl_spiram_alloc_req_t *)_req; req->result = pi_spiram_alloc(req->device, req->size); req->done = 1; __pi_cluster_notif_req_done(req->cid); } void __pi_spiram_free_cluster_req(void *_req) { pi_cl_spiram_free_req_t *req = (pi_cl_spiram_free_req_t *)_req; pi_spiram_free(req->device, req->chunk, req->size); req->done = 1; __pi_cluster_notif_req_done(req->cid); } void pi_cl_spiram_alloc(struct pi_device *device, uint32_t size, pi_cl_spiram_alloc_req_t *req) { req->device = device; req->size = size; req->cid = pi_cluster_id(); req->done = 0; __pi_task_init_from_cluster(&req->event); pi_task_callback(&req->event, __pi_spiram_alloc_cluster_req, (void* )req); pi_cl_send_task_to_fc(&req->event); } void pi_cl_spiram_free(struct pi_device *device, uint32_t chunk, uint32_t size, pi_cl_spiram_free_req_t *req) { req->device = device; req->size = size; req->chunk = chunk; req->cid = pi_cluster_id(); req->done = 0; __pi_task_init_from_cluster(&req->event); pi_task_callback(&req->event, __pi_spiram_free_cluster_req, (void* )req); pi_cl_send_task_to_fc(&req->event); } #endif static pi_ram_api_t spiram_api = { .open = &spiram_open, .close = &spiram_close, .copy_async = &spiram_copy_async, .copy_2d_async = &spiram_copy_2d_async, .alloc = &spiram_alloc, .free = &spiram_free, }; void pi_spiram_conf_init(struct pi_spiram_conf *conf) { conf->ram.api = &spiram_api; conf->baudrate = 24000000; bsp_spiram_conf_init(conf); }
439420310331fc789aba6a9191bf2ff555e03580
5eff7a36d9a9917dce9111f0c3074375fe6f7656
/driver/xf86-video-openchrome/src/via_exa_h2.c
05f0d46fa25e4f41b29504892a75ec8d5d1fb47c
[ "MIT" ]
permissive
openbsd/xenocara
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
a012b5de33ea0b977095d77316a521195b26cc6b
refs/heads/master
2023-08-25T12:16:58.862008
2023-08-12T16:16:25
2023-08-12T16:16:25
66,967,384
177
66
null
2023-07-22T18:12:37
2016-08-30T18:36:01
C
UTF-8
C
false
false
16,462
c
via_exa_h2.c
/* * Copyright 1998-2008 VIA Technologies, Inc. All Rights Reserved. * Copyright 2001-2003 S3 Graphics, Inc. All Rights Reserved. * Copyright 2006 Thomas Hellström. All Rights Reserved. * * 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, sub license, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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. */ /* * 2D acceleration functions for the VIA/S3G UniChrome IGPs. * * Mostly rewritten, and modified for EXA support, by Thomas Hellström. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <X11/Xarch.h> #include "miline.h" #include "via_driver.h" #include "via_regs.h" #include "via_dmabuffer.h" #include "via_rop.h" /* * Check if we can use a planeMask and update the 2D context accordingly. */ static Bool viaAccelPlaneMaskHelper_H2(ViaTwodContext * tdc, CARD32 planeMask) { CARD32 modeMask = (1 << ((1 << tdc->bytesPPShift) << 3)) - 1; CARD32 curMask = 0x00000000; CARD32 curByteMask; int i; if ((planeMask & modeMask) != modeMask) { /* Masking doesn't work in 8bpp. */ if (modeMask == 0xFF) { tdc->keyControl &= 0x0FFFFFFF; return FALSE; } /* Translate the bit planemask to a byte planemask. */ for (i = 0; i < (1 << tdc->bytesPPShift); ++i) { curByteMask = (0xFF << (i << 3)); if ((planeMask & curByteMask) == 0) { curMask |= (1 << i); } else if ((planeMask & curByteMask) != curByteMask) { tdc->keyControl &= 0x0FFFFFFF; return FALSE; } } ErrorF("DEBUG: planeMask 0x%08x, curMask 0%02x\n", (unsigned)planeMask, (unsigned)curMask); tdc->keyControl = (tdc->keyControl & 0x0FFFFFFF) | (curMask << 28); } return TRUE; } /* * Emit transparency state and color to the command buffer. */ static void viaAccelTransparentHelper_H2(VIAPtr pVia, CARD32 keyControl, CARD32 transColor, Bool usePlaneMask) { ViaTwodContext *tdc = &pVia->td; RING_VARS; tdc->keyControl &= ((usePlaneMask) ? 0xF0000000 : 0x00000000); tdc->keyControl |= (keyControl & 0x0FFFFFFF); BEGIN_RING(4); OUT_RING_H1(VIA_REG_KEYCONTROL, tdc->keyControl); if (keyControl) { OUT_RING_H1(VIA_REG_SRCCOLORKEY, transColor); } } /* * Mark Sync using the 2D blitter for AGP. NoOp for PCI. * In the future one could even launch a NULL PCI DMA command * to have an interrupt generated, provided it is possible to * write to the PCI DMA engines from the AGP command stream. */ int viaAccelMarkSync_H2(ScreenPtr pScreen) { ScrnInfoPtr pScrn = xf86ScreenToScrn(pScreen); VIAPtr pVia = VIAPTR(pScrn); RING_VARS; ++pVia->curMarker; /* Wrap around without affecting the sign bit. */ pVia->curMarker &= 0x7FFFFFFF; if (pVia->agpDMA) { BEGIN_RING(16); OUT_RING_H1(VIA_REG_KEYCONTROL, 0x00); OUT_RING_H1(VIA_REG_GEMODE, VIA_GEM_32bpp); OUT_RING_H1(VIA_REG_DSTBASE, pVia->markerOffset >> 3); OUT_RING_H1(VIA_REG_PITCH, VIA_PITCH_ENABLE); OUT_RING_H1(VIA_REG_DSTPOS, 0); OUT_RING_H1(VIA_REG_DIMENSION, 0); OUT_RING_H1(VIA_REG_FGCOLOR, pVia->curMarker); OUT_RING_H1(VIA_REG_GECMD, (0xF0 << 24) | VIA_GEC_BLT | VIA_GEC_FIXCOLOR_PAT); ADVANCE_RING; } return pVia->curMarker; } /* * Exa functions. It is assumed that EXA does not exceed the blitter limits. */ Bool viaExaPrepareSolid_H2(PixmapPtr pPixmap, int alu, Pixel planeMask, Pixel fg) { ScrnInfoPtr pScrn = xf86ScreenToScrn(pPixmap->drawable.pScreen); VIAPtr pVia = VIAPTR(pScrn); ViaTwodContext *tdc = &pVia->td; if (exaGetPixmapPitch(pPixmap) & 7) return FALSE; if (!viaAccelSetMode(pPixmap->drawable.depth, tdc)) return FALSE; if (!viaAccelPlaneMaskHelper_H2(tdc, planeMask)) return FALSE; viaAccelTransparentHelper_H2(pVia, 0x0, 0x0, TRUE); tdc->cmd = VIA_GEC_BLT | VIA_GEC_FIXCOLOR_PAT | VIAACCELPATTERNROP(alu); tdc->fgColor = fg; return TRUE; } void viaExaSolid_H2(PixmapPtr pPixmap, int x1, int y1, int x2, int y2) { ScrnInfoPtr pScrn = xf86ScreenToScrn(pPixmap->drawable.pScreen); CARD32 dstOffset = exaGetPixmapOffset(pPixmap); CARD32 dstPitch = exaGetPixmapPitch(pPixmap); int w = x2 - x1, h = y2 - y1; VIAPtr pVia = VIAPTR(pScrn); ViaTwodContext *tdc = &pVia->td; RING_VARS; BEGIN_RING(14); OUT_RING_H1(VIA_REG_GEMODE, tdc->mode); OUT_RING_H1(VIA_REG_DSTBASE, dstOffset >> 3); OUT_RING_H1(VIA_REG_PITCH, VIA_PITCH_ENABLE | (dstPitch >> 3) << 16); OUT_RING_H1(VIA_REG_DSTPOS, (y1 << 16) | (x1 & 0xFFFF)); OUT_RING_H1(VIA_REG_DIMENSION, ((h - 1) << 16) | (w - 1)); OUT_RING_H1(VIA_REG_FGCOLOR, tdc->fgColor); OUT_RING_H1(VIA_REG_GECMD, tdc->cmd); ADVANCE_RING; } void viaExaDoneSolidCopy_H2(PixmapPtr pPixmap) { } Bool viaExaPrepareCopy_H2(PixmapPtr pSrcPixmap, PixmapPtr pDstPixmap, int xdir, int ydir, int alu, Pixel planeMask) { ScrnInfoPtr pScrn = xf86ScreenToScrn(pDstPixmap->drawable.pScreen); VIAPtr pVia = VIAPTR(pScrn); ViaTwodContext *tdc = &pVia->td; if (pSrcPixmap->drawable.bitsPerPixel != pDstPixmap->drawable.bitsPerPixel) return FALSE; if ((tdc->srcPitch = exaGetPixmapPitch(pSrcPixmap)) & 3) return FALSE; if (exaGetPixmapPitch(pDstPixmap) & 7) return FALSE; tdc->srcOffset = exaGetPixmapOffset(pSrcPixmap); tdc->cmd = VIA_GEC_BLT | VIAACCELCOPYROP(alu); if (xdir < 0) tdc->cmd |= VIA_GEC_DECX; if (ydir < 0) tdc->cmd |= VIA_GEC_DECY; if (!viaAccelSetMode(pDstPixmap->drawable.bitsPerPixel, tdc)) return FALSE; if (!viaAccelPlaneMaskHelper_H2(tdc, planeMask)) return FALSE; viaAccelTransparentHelper_H2(pVia, 0x0, 0x0, TRUE); return TRUE; } void viaExaCopy_H2(PixmapPtr pDstPixmap, int srcX, int srcY, int dstX, int dstY, int width, int height) { ScrnInfoPtr pScrn = xf86ScreenToScrn(pDstPixmap->drawable.pScreen); CARD32 dstOffset = exaGetPixmapOffset(pDstPixmap), val; CARD32 dstPitch = exaGetPixmapPitch(pDstPixmap); VIAPtr pVia = VIAPTR(pScrn); ViaTwodContext *tdc = &pVia->td; RING_VARS; if (!width || !height) return; if (tdc->cmd & VIA_GEC_DECY) { srcY += height - 1; dstY += height - 1; } if (tdc->cmd & VIA_GEC_DECX) { srcX += width - 1; dstX += width - 1; } val = VIA_PITCH_ENABLE | (dstPitch >> 3) << 16 | (tdc->srcPitch >> 3); BEGIN_RING(16); OUT_RING_H1(VIA_REG_GEMODE, tdc->mode); OUT_RING_H1(VIA_REG_SRCBASE, tdc->srcOffset >> 3); OUT_RING_H1(VIA_REG_DSTBASE, dstOffset >> 3); OUT_RING_H1(VIA_REG_PITCH, val); OUT_RING_H1(VIA_REG_SRCPOS, (srcY << 16) | (srcX & 0xFFFF)); OUT_RING_H1(VIA_REG_DSTPOS, (dstY << 16) | (dstX & 0xFFFF)); OUT_RING_H1(VIA_REG_DIMENSION, ((height - 1) << 16) | (width - 1)); OUT_RING_H1(VIA_REG_GECMD, tdc->cmd); ADVANCE_RING; } Bool viaExaCheckComposite_H2(int op, PicturePtr pSrcPicture, PicturePtr pMaskPicture, PicturePtr pDstPicture) { ScrnInfoPtr pScrn = xf86ScreenToScrn(pDstPicture->pDrawable->pScreen); VIAPtr pVia = VIAPTR(pScrn); Via3DState *v3d = &pVia->v3d; if (!pSrcPicture->pDrawable) return FALSE; /* Reject small composites early. They are done much faster in software. */ if (!pSrcPicture->repeat && pSrcPicture->pDrawable->width * pSrcPicture->pDrawable->height < VIA_MIN_COMPOSITE) return FALSE; if (pMaskPicture && pMaskPicture->pDrawable && !pMaskPicture->repeat && pMaskPicture->pDrawable->width * pMaskPicture->pDrawable->height < VIA_MIN_COMPOSITE) return FALSE; if (pMaskPicture && pMaskPicture->repeat && pMaskPicture->repeatType != RepeatNormal) return FALSE; if (pMaskPicture && pMaskPicture->componentAlpha) { #ifdef VIA_DEBUG_COMPOSITE viaExaPrintCompositeInfo("Component Alpha operation", op, pSrcPicture, pMaskPicture, pDstPicture); #endif return FALSE; } if (!v3d->opSupported(op)) { #ifdef VIA_DEBUG_COMPOSITE viaExaPrintCompositeInfo("Operator not supported", op, pSrcPicture, pMaskPicture, pDstPicture); #endif return FALSE; } /* * FIXME: A8 destination formats are currently not supported and do not * seem supported by the hardware, although there are some leftover * register settings apparent in the via_3d_reg.h file. We need to fix this * (if important), by using component ARGB8888 operations with bitmask. */ if (!v3d->dstSupported(pDstPicture->format)) { #ifdef VIA_DEBUG_COMPOSITE viaExaPrintCompositeInfo(" Destination format not supported", op, pSrcPicture, pMaskPicture, pDstPicture); #endif return FALSE; } if (v3d->texSupported(pSrcPicture->format)) { if (pMaskPicture && (PICT_FORMAT_A(pMaskPicture->format) == 0 || !v3d->texSupported(pMaskPicture->format))) { #ifdef VIA_DEBUG_COMPOSITE viaExaPrintCompositeInfo("Mask format not supported", op, pSrcPicture, pMaskPicture, pDstPicture); #endif return FALSE; } return TRUE; } #ifdef VIA_DEBUG_COMPOSITE viaExaPrintCompositeInfo("Src format not supported", op, pSrcPicture, pMaskPicture, pDstPicture); #endif return FALSE; } Bool viaExaPrepareComposite_H2(int op, PicturePtr pSrcPicture, PicturePtr pMaskPicture, PicturePtr pDstPicture, PixmapPtr pSrc, PixmapPtr pMask, PixmapPtr pDst) { CARD32 height, width; ScrnInfoPtr pScrn = xf86ScreenToScrn(pDst->drawable.pScreen); VIAPtr pVia = VIAPTR(pScrn); Via3DState *v3d = &pVia->v3d; int curTex = 0; ViaTexBlendingModes srcMode; Bool isAGP; unsigned long offset; /* Workaround: EXA crash with new libcairo2 on a VIA VX800 (#298) */ /* TODO Add real source only pictures */ if (!pSrc) { ErrorF("pSrc is NULL\n"); return FALSE; } v3d->setDestination(v3d, exaGetPixmapOffset(pDst), exaGetPixmapPitch(pDst), pDstPicture->format); v3d->setCompositeOperator(v3d, op); v3d->setDrawing(v3d, 0x0c, 0xFFFFFFFF, 0x000000FF, 0xFF); viaOrder(pSrc->drawable.width, &width); viaOrder(pSrc->drawable.height, &height); /* * For one-pixel repeat mask pictures we avoid using multitexturing by * modifying the src's texture blending equation and feed the pixel * value as a constant alpha for the src's texture. Multitexturing on the * Unichromes seems somewhat slow, so this speeds up translucent windows. */ srcMode = via_src; pVia->maskP = NULL; if (pMaskPicture && (pMaskPicture->pDrawable->height == 1) && (pMaskPicture->pDrawable->width == 1) && pMaskPicture->repeat && viaExpandablePixel(pMaskPicture->format)) { pVia->maskP = pMask->devPrivate.ptr; pVia->maskFormat = pMaskPicture->format; pVia->componentAlpha = pMaskPicture->componentAlpha; srcMode = ((pMaskPicture->componentAlpha) ? via_src_onepix_comp_mask : via_src_onepix_mask); } /* * One-Pixel repeat src pictures go as solid color instead of textures. * Speeds up window shadows. */ pVia->srcP = NULL; if (pSrcPicture && pSrcPicture->repeat && (pSrcPicture->pDrawable->height == 1) && (pSrcPicture->pDrawable->width == 1) && viaExpandablePixel(pSrcPicture->format)) { pVia->srcP = pSrc->devPrivate.ptr; pVia->srcFormat = pSrcPicture->format; } /* Exa should be smart enough to eliminate this IN operation. */ if (pVia->srcP && pVia->maskP) { ErrorF("Bad one-pixel IN composite operation. " "EXA needs to be smarter.\n"); return FALSE; } if (!pVia->srcP) { offset = exaGetPixmapOffset(pSrc); isAGP = viaIsAGP(pVia, pSrc, &offset); if (!isAGP && !viaExaIsOffscreen(pSrc)) return FALSE; if (!v3d->setTexture(v3d, curTex, offset, exaGetPixmapPitch(pSrc), pVia->nPOT[curTex], 1 << width, 1 << height, pSrcPicture->format, via_repeat, via_repeat, srcMode, isAGP)) { return FALSE; } curTex++; } if (pMaskPicture && !pVia->maskP) { offset = exaGetPixmapOffset(pMask); isAGP = viaIsAGP(pVia, pMask, &offset); if (!isAGP && !viaExaIsOffscreen(pMask)) return FALSE; viaOrder(pMask->drawable.width, &width); viaOrder(pMask->drawable.height, &height); if (!v3d->setTexture(v3d, curTex, offset, exaGetPixmapPitch(pMask), pVia->nPOT[curTex], 1 << width, 1 << height, pMaskPicture->format, via_repeat, via_repeat, ((pMaskPicture->componentAlpha) ? via_comp_mask : via_mask), isAGP)) { return FALSE; } curTex++; } v3d->setFlags(v3d, curTex, FALSE, TRUE, TRUE); v3d->emitState(v3d, &pVia->cb, viaCheckUpload(pScrn, v3d)); v3d->emitClipRect(v3d, &pVia->cb, 0, 0, pDst->drawable.width, pDst->drawable.height); return TRUE; } void viaExaComposite_H2(PixmapPtr pDst, int srcX, int srcY, int maskX, int maskY, int dstX, int dstY, int width, int height) { ScrnInfoPtr pScrn = xf86ScreenToScrn(pDst->drawable.pScreen); VIAPtr pVia = VIAPTR(pScrn); Via3DState *v3d = &pVia->v3d; CARD32 col; if (pVia->maskP) { viaPixelARGB8888(pVia->maskFormat, pVia->maskP, &col); v3d->setTexBlendCol(v3d, 0, pVia->componentAlpha, col); } if (pVia->srcP) { viaPixelARGB8888(pVia->srcFormat, pVia->srcP, &col); v3d->setDrawing(v3d, 0x0c, 0xFFFFFFFF, col & 0x00FFFFFF, col >> 24); srcX = maskX; srcY = maskY; } if (pVia->maskP || pVia->srcP) v3d->emitState(v3d, &pVia->cb, viaCheckUpload(pScrn, v3d)); v3d->emitQuad(v3d, &pVia->cb, dstX, dstY, srcX, srcY, maskX, maskY, width, height); } void viaAccelTextureBlit(ScrnInfoPtr pScrn, unsigned long srcOffset, unsigned srcPitch, unsigned w, unsigned h, unsigned srcX, unsigned srcY, unsigned srcFormat, unsigned long dstOffset, unsigned dstPitch, unsigned dstX, unsigned dstY, unsigned dstFormat, int rotate) { VIAPtr pVia = VIAPTR(pScrn); CARD32 wOrder, hOrder; Via3DState *v3d = &pVia->v3d; viaOrder(w, &wOrder); viaOrder(h, &hOrder); v3d->setDestination(v3d, dstOffset, dstPitch, dstFormat); v3d->setDrawing(v3d, 0x0c, 0xFFFFFFFF, 0x000000FF, 0x00); v3d->setFlags(v3d, 1, TRUE, TRUE, FALSE); v3d->setTexture(v3d, 0, srcOffset, srcPitch, TRUE, 1 << wOrder, 1 << hOrder, srcFormat, via_single, via_single, via_src, FALSE); v3d->emitState(v3d, &pVia->cb, viaCheckUpload(pScrn, v3d)); v3d->emitClipRect(v3d, &pVia->cb, dstX, dstY, w, h); v3d->emitQuad(v3d, &pVia->cb, dstX, dstY, srcX, srcY, 0, 0, w, h); }
a9e219b50ff78e544e4a674e9c9ba85579ba9f8f
4ba76056c744ada0a01fb27b7cad8464cefc7aa0
/supports/toolchains/LiveEditor/PainterEngine_LiveEditorModules_Exportlive.h
c8eb2a2806bba79fe4b2a6470612d7de9ef8c342
[ "BSD-3-Clause" ]
permissive
matrixcascade/PainterEngine
23e110e25a39e1d016ed7936eac23e06932456b4
1d3e6e85f337e8a8db44680094ab3f4b988507cb
refs/heads/master
2023-08-29T11:29:26.934779
2023-08-23T09:23:04
2023-08-23T09:23:04
190,119,926
1,989
253
BSD-3-Clause
2023-09-05T12:19:31
2019-06-04T03:08:26
C
UTF-8
C
false
false
757
h
PainterEngine_LiveEditorModules_Exportlive.h
#ifndef PX_LIVEFRAMEWORKMODULES_EXPORTLIVE_H #define PX_LIVEFRAMEWORKMODULES_EXPORTLIVE_H #include "PainterEngine_Startup.h" #define PX_LIVEEDITORMODULE_EXPORTLIVE_EVENT_MESSAGE 0x00100000 typedef struct { PX_LiveFramework *pLiveFramework; PX_Runtime *pruntime; PX_Object *explorer; PX_FontModule *fontmodule; PX_Json *pLanguageJson; }PX_LiveEditorModule_ExportLive; PX_Object * PX_LiveEditorModule_ExportLiveInstall(PX_Object *parent,PX_Runtime *pruntime,PX_FontModule *fm,PX_LiveFramework *pLiveFramework,PX_Json *pLanguageJson); px_void PX_LiveEditorModule_ExportLiveUninstall(PX_Object *pObject); px_void PX_LiveEditorModule_ExportLiveEnable(PX_Object *pObject); px_void PX_LiveEditorModule_ExportLiveDisable(PX_Object *pObject); #endif
e12965ef8e67553df85f4969e3985954d0f35289
4c690b473a2fd8baa53377195933c2b996a01244
/duration.c
abff9a074fc34b4c9b26b826e0b76c0f5291b372
[ "BSD-3-Clause" ]
permissive
NLnetLabs/ldns
77bdf4bf6f814fe8d7e274a1754e9bbf23ae0a4a
67b9f0ae98910df882ca77f503673929a9e1db9b
refs/heads/develop
2023-08-28T07:19:23.088018
2023-06-03T13:08:41
2023-06-03T13:09:04
72,740,793
248
103
BSD-3-Clause
2023-09-14T14:40:58
2016-11-03T11:57:12
C
UTF-8
C
false
false
6,568
c
duration.c
/* * $Id: duration.c 4518 2011-02-24 15:39:09Z matthijs $ * * Copyright (c) 2009 NLNet Labs. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * */ /** * * This file is copied from the OpenDNSSEC source repository * and only slightly adapted to make it fit. */ /** * * Durations. */ #include <ldns/config.h> #include <ldns/duration.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> /** * Create a new 'instant' duration. * */ ldns_duration_type* ldns_duration_create(void) { ldns_duration_type* duration; duration = malloc(sizeof(ldns_duration_type)); if (!duration) { return NULL; } duration->years = 0; duration->months = 0; duration->weeks = 0; duration->days = 0; duration->hours = 0; duration->minutes = 0; duration->seconds = 0; return duration; } /** * Compare durations. * */ int ldns_duration_compare(const ldns_duration_type* d1, const ldns_duration_type* d2) { if (!d1 && !d2) { return 0; } if (!d1 || !d2) { return d1?-1:1; } if (d1->years != d2->years) { return (int) (d1->years - d2->years); } if (d1->months != d2->months) { return (int) (d1->months - d2->months); } if (d1->weeks != d2->weeks) { return (int) (d1->weeks - d2->weeks); } if (d1->days != d2->days) { return (int) (d1->days - d2->days); } if (d1->hours != d2->hours) { return (int) (d1->hours - d2->hours); } if (d1->minutes != d2->minutes) { return (int) (d1->minutes - d2->minutes); } if (d1->seconds != d2->seconds) { return (int) (d1->seconds - d2->seconds); } return 0; } /** * Create a duration from string. * */ ldns_duration_type* ldns_duration_create_from_string(const char* str) { ldns_duration_type* duration = ldns_duration_create(); char* P, *X, *T, *W; int not_weeks = 0; if (!duration) { return NULL; } if (!str) { return duration; } P = strchr(str, 'P'); if (!P) { ldns_duration_cleanup(duration); return NULL; } T = strchr(str, 'T'); X = strchr(str, 'Y'); if (X) { duration->years = (time_t) atoi(str+1); str = X; not_weeks = 1; } X = strchr(str, 'M'); if (X && (!T || (size_t) (X-P) < (size_t) (T-P))) { duration->months = (time_t) atoi(str+1); str = X; not_weeks = 1; } X = strchr(str, 'D'); if (X) { duration->days = (time_t) atoi(str+1); str = X; not_weeks = 1; } if (T) { str = T; not_weeks = 1; } X = strchr(str, 'H'); if (X && T) { duration->hours = (time_t) atoi(str+1); str = X; not_weeks = 1; } X = strrchr(str, 'M'); if (X && T && (size_t) (X-P) > (size_t) (T-P)) { duration->minutes = (time_t) atoi(str+1); str = X; not_weeks = 1; } X = strchr(str, 'S'); if (X && T) { duration->seconds = (time_t) atoi(str+1); str = X; not_weeks = 1; } W = strchr(str, 'W'); if (W) { if (not_weeks) { ldns_duration_cleanup(duration); return NULL; } else { duration->weeks = (time_t) atoi(str+1); } } return duration; } /** * Helper func for ldns_duration2string below. If t > 0, * scan print t and c on buf, forwarding buf. Return 0 on success. */ static inline int dur_scan_print(char **buf, char *eob, char c, time_t t) { if (t > 0) { int r = snprintf(*buf, eob - *buf, "%u%c", (unsigned)t, c); if (r < 0 || (*buf += r) >= eob) return -1; } return 0; } /** * Convert a duration to a string. * */ char* ldns_duration2string(const ldns_duration_type* d) { /* Max string size should be 7 * 40 + 3 on a 127 bits machine * So 300 (< 273) is more than enough. */ char buf[300] = "P0D", *eob = buf + sizeof(buf), *p = buf + 1; if (!d) return NULL; if (dur_scan_print(&p, eob, 'Y', d->years) || dur_scan_print(&p, eob, 'M', d->months) || dur_scan_print(&p, eob, 'W', d->weeks) || dur_scan_print(&p, eob, 'D', d->days)) return NULL; if (d->hours || d->minutes || d->seconds) { if (p > (eob - 2)) return NULL; /* Error; no space left on buf for 'T' */ *p++ = 'T'; *p = 0; if (dur_scan_print(&p, eob, 'H', d->hours) || dur_scan_print(&p, eob, 'M', d->minutes) || dur_scan_print(&p, eob, 'S', d->seconds)) return NULL; } return strdup(buf); } /** * Convert a duration to a time. * */ time_t ldns_duration2time(const ldns_duration_type* duration) { time_t period = 0; if (duration) { period += (duration->seconds); period += (duration->minutes)*60; period += (duration->hours)*3600; period += (duration->days)*86400; period += (duration->weeks)*86400*7; period += (duration->months)*86400*31; period += (duration->years)*86400*365; /* [TODO] calculate correct number of days in this month/year */ /* if (duration->months || duration->years) { } */ } return period; } /** * Clean up duration. * */ void ldns_duration_cleanup(ldns_duration_type* duration) { if (!duration) { return; } free(duration); return; }
fdaa875b151408e595bb2273706cc4f669f3a005
bec5d52c5185d032b2b81eccd008aa8e4e045790
/ncd/modules/net_ipv4_addr_in_network.c
516b6815fd6e8d338c71674751472988927e80a1
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
shadowsocks/badvpn
2993b0da7c59870f0a550a842cabe3312761d541
40a0e5010aa4adb6d3ca1d1418dfde345c50107d
refs/heads/shadowsocks-android
2021-12-08T06:17:04.546977
2021-08-23T04:05:27
2021-08-23T04:05:27
45,686,048
166
154
NOASSERTION
2021-08-23T04:05:28
2015-11-06T14:18:20
C
UTF-8
C
false
false
5,853
c
net_ipv4_addr_in_network.c
/** * @file net_ipv4_addr_in_network.c * @author Ambroz Bizjak <ambrop7@gmail.com> * * @section LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author 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 AUTHOR 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. * * @section DESCRIPTION * * Synopsis: * net.ipv4.addr_in_network(string addr, string net_addr, string net_prefix) * net.ipv4.addr_in_network(string addr, string cidr_net_addr) * net.ipv4.ifnot_addr_in_network(string addr, string net_addr, string net_prefix) * net.ipv4.ifnot_addr_in_network(string addr, string cidr_net_addr) * * Description: * Checks if two IPv4 addresses belong to the same subnet. * The prefix length is given either in the a separate argument or along with * the second address in CIDR notation (address/prefix). * This can be used to check whether an address belongs to a certain * subnet, hence the name. * * Variables: * (empty) - "true" if addresses belong to the same subnet, "false" if not */ #include <string.h> #include <misc/ipaddr.h> #include <ncd/module_common.h> #include <generated/blog_channel_ncd_net_ipv4_addr_in_network.h> struct instance { NCDModuleInst *i; int value; }; static void func_new_common (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params, int is_ifnot) { struct instance *o = vo; o->i = i; // read arguments NCDValRef arg_addr; NCDValRef arg_net_addr; NCDValRef arg_net_prefix = NCDVal_NewInvalid(); if (!NCDVal_ListRead(params->args, 2, &arg_addr, &arg_net_addr) && !NCDVal_ListRead(params->args, 3, &arg_addr, &arg_net_addr, &arg_net_prefix) ) { ModuleLog(o->i, BLOG_ERROR, "wrong arity"); goto fail0; } if (!NCDVal_IsString(arg_addr) || !NCDVal_IsString(arg_net_addr) || (!NCDVal_IsInvalid(arg_net_prefix) && !NCDVal_IsString(arg_net_prefix)) ) { ModuleLog(o->i, BLOG_ERROR, "wrong type"); goto fail0; } // parse addr uint32_t addr; if (!ipaddr_parse_ipv4_addr(NCDVal_StringMemRef(arg_addr), &addr)) { ModuleLog(o->i, BLOG_ERROR, "bad address"); goto fail0; } // parse network struct ipv4_ifaddr network; if (NCDVal_IsInvalid(arg_net_prefix)) { if (!ipaddr_parse_ipv4_ifaddr(NCDVal_StringMemRef(arg_net_addr), &network)) { ModuleLog(o->i, BLOG_ERROR, "bad network in CIDR notation"); goto fail0; } } else { if (!ipaddr_parse_ipv4_addr(NCDVal_StringMemRef(arg_net_addr), &network.addr)) { ModuleLog(o->i, BLOG_ERROR, "bad network address"); goto fail0; } if (!ipaddr_parse_ipv4_prefix(NCDVal_StringMemRef(arg_net_prefix), &network.prefix)) { ModuleLog(o->i, BLOG_ERROR, "bad network prefix"); goto fail0; } } // test o->value = ipaddr_ipv4_addrs_in_network(addr, network.addr, network.prefix); if (is_ifnot && o->value) { ModuleLog(o->i, BLOG_ERROR, "addresses belong to same subnet, not proceeding"); } // signal up if (!is_ifnot || !o->value) { NCDModuleInst_Backend_Up(o->i); } return; fail0: NCDModuleInst_Backend_DeadError(i); } static void func_new_normal (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { func_new_common(vo, i, params, 0); } static void func_new_ifnot (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { func_new_common(vo, i, params, 1); } static int func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out) { struct instance *o = vo; if (!strcmp(name, "")) { *out = ncd_make_boolean(mem, o->value); return 1; } return 0; } static struct NCDModule modules[] = { { .type = "net.ipv4.addr_in_network", .func_new2 = func_new_normal, .func_getvar = func_getvar, .alloc_size = sizeof(struct instance) }, { .type = "ip_in_network", // compatibility name .func_new2 = func_new_normal, .func_getvar = func_getvar, .alloc_size = sizeof(struct instance) }, { .type = "net.ipv4.ifnot_addr_in_network", .func_new2 = func_new_ifnot, .func_getvar = func_getvar, .alloc_size = sizeof(struct instance) }, { .type = NULL } }; const struct NCDModuleGroup ncdmodule_net_ipv4_addr_in_network = { .modules = modules };
b918f0857250d08e5cd2422efd041f060484ac6e
a24c9a4fe4c912200e694e46992789c7e2f82dd1
/machine/tools/asm_struct_macro_generator.c
de7f66f18a23bf791a5c2f21757ef2bd3395e17e
[ "BSD-2-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
cksystemsteaching/selfie
0e94758b0bfb69baa630dc4f073bed5dfc5027bb
cdd7c68e1fcaf3608527a4a85a50f57627afe9d6
refs/heads/main
2023-09-02T17:31:39.471055
2023-08-29T16:31:48
2023-08-29T16:31:48
41,832,998
2,406
485
BSD-2-Clause
2023-08-10T17:18:35
2015-09-02T23:40:53
Jupyter Notebook
UTF-8
C
false
false
2,427
c
asm_struct_macro_generator.c
#include <stdio.h> #include "context.h" #define PRINT_SIZE_DEF(prefix, name, stru) printf("#define %s%s %lu\n", #prefix, #name, sizeof(stru)) #define PRINT_OFFSET_DEF(prefix, name, stru, memb) printf("#define %s%s %lu\n", #prefix, #name, offsetof(stru, memb)) int main() { PRINT_SIZE_DEF(SIZEOF_, REGISTERS_STRUCT, struct registers); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, RA, struct registers, ra); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, SP, struct registers, sp); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, GP, struct registers, gp); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, TP, struct registers, tp); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, T0, struct registers, t0); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, T1, struct registers, t1); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, T2, struct registers, t2); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, S0, struct registers, s0); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, S1, struct registers, s1); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, A0, struct registers, a0); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, A1, struct registers, a1); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, A2, struct registers, a2); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, A3, struct registers, a3); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, A4, struct registers, a4); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, A5, struct registers, a5); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, A6, struct registers, a6); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, A7, struct registers, a7); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, S2, struct registers, s2); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, S3, struct registers, s3); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, S4, struct registers, s4); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, S5, struct registers, s5); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, S6, struct registers, s6); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, S7, struct registers, s7); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, S8, struct registers, s8); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, S9, struct registers, s9); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, S10, struct registers, s10); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, S11, struct registers, s11); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, T3, struct registers, t3); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, T4, struct registers, t4); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, T5, struct registers, t5); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, T6, struct registers, t6); PRINT_OFFSET_DEF(REGISTERS_OFFSET_, PC, struct registers, pc); }
9eb9c11a1772f5fc5494fb67478d6f026546f8b2
60b0251bee63fef9c87633dd98f0c2be3841e92e
/swap-ssdb-1.9.2/src/redis/crc64.h
00e13a62b30bb46085a8677d6fbb67d2f4e299d6
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
JingchengLi/swapdb
a88855b884e89a761bd2fb7ad9147e46f7997a80
079361aea394424bf1edf75e2f97fba719e5348f
refs/heads/master
2023-03-12T11:47:11.086624
2023-03-02T15:06:03
2023-03-02T15:06:03
99,323,866
264
52
null
null
null
null
UTF-8
C
false
false
1,020
h
crc64.h
#ifndef CRC64_H #define CRC64_H #include "redis/crc/crc64speed.h" /* Run the init() function exactly once. If pthread.h is not included, then this macro will use a simple static state variable for the purpose, which is not thread-safe. The init function must be of the type void init(void). */ #ifdef PTHREAD_ONCE_INIT # define ONCE(init) \ do { \ static pthread_once_t once = PTHREAD_ONCE_INIT; \ pthread_once(&once, init); \ } while (0) #else # define ONCE(init) \ do { \ static volatile int once = 1; \ if (once) { \ if (once++ == 1) { \ init(); \ once = 0; \ } \ else \ while (once) \ ; \ } \ } while (0) #endif inline void init_crc64speed_table(){ crc64speed_init_native(); } inline uint64_t crc64_fast(uint64_t crc, const void *s, const uint64_t l) { ONCE(init_crc64speed_table); return crc64speed_native(crc, s, l); } #endif
f03888279f0d2a12e6ae10d45454e5e98ed79437
5eff7a36d9a9917dce9111f0c3074375fe6f7656
/lib/mesa/src/imagination/vulkan/usc/programs/pvr_vdm_load_sr.h
ab9709655f12eda809d5922918ae805a4b9fb1a8
[]
no_license
openbsd/xenocara
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
a012b5de33ea0b977095d77316a521195b26cc6b
refs/heads/master
2023-08-25T12:16:58.862008
2023-08-12T16:16:25
2023-08-12T16:16:25
66,967,384
177
66
null
2023-07-22T18:12:37
2016-08-30T18:36:01
C
UTF-8
C
false
false
2,975
h
pvr_vdm_load_sr.h
/* * Copyright © 2022 Imagination Technologies Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /* Auto-generated file - don't edit */ #ifndef PVR_VDM_LOAD_SR_H #define PVR_VDM_LOAD_SR_H #include <stdint.h> /* clang-format off */ static const uint8_t pvr_vdm_load_sr_code[] = { 0x25, 0x02, 0x87, 0x81, 0x04, 0x00, 0x00, 0x00, 0x84, 0x04, 0x25, 0x02, 0x87, 0x80, 0x04, 0x00, 0x00, 0x00, 0x85, 0x04, 0x25, 0x02, 0x87, 0x83, 0x04, 0x00, 0x00, 0x00, 0x86, 0x04, 0x25, 0x02, 0x87, 0x82, 0x04, 0x00, 0x00, 0x00, 0x87, 0x04, 0x56, 0x20, 0xF1, 0x85, 0x02, 0x80, 0x81, 0xD0, 0xC4, 0x08, 0x00, 0xFF, 0x02, 0x80, 0x6A, 0xFF, 0x67, 0xF0, 0x40, 0x20, 0x41, 0x8C, 0x80, 0x40, 0x00, 0x50, 0x8F, 0xC0, 0x80, 0x02, 0x04, 0x81, 0x60, 0x00, 0x9A, 0x00, 0x00, 0x00, 0x25, 0x36, 0x87, 0x87, 0x00, 0x00, 0x40, 0x05, 0xD1, 0x06, 0x55, 0x20, 0xF1, 0x81, 0x02, 0x00, 0xC0, 0xC6, 0x08, 0x00, 0x02, 0x80, 0x6A, 0xFF, 0x46, 0x42, 0xD0, 0x03, 0xEA, 0xD1, 0x41, 0x00, 0x01, 0x00, 0x00, 0x51, 0x27, 0x06, 0xEB, 0x84, 0x50, 0x20, 0x86, 0x87, 0x04, 0x00, 0xC0, 0x06, 0x87, 0x22, 0x25, 0x32, 0x87, 0x87, 0x00, 0x1F, 0x40, 0xC5, 0x0C, 0xFF, 0x25, 0x02, 0x87, 0xC0, 0x0C, 0x00, 0x00, 0x00, 0x83, 0x0C, 0x47, 0x42, 0xD0, 0x03, 0xEA, 0x85, 0x41, 0x90, 0x01, 0x08, 0x00, 0x00, 0x85, 0x0C, 0x47, 0x42, 0xD0, 0x03, 0xEA, 0xC5, 0x41, 0x90, 0x01, 0x08, 0x00, 0x00, 0xC5, 0x0C, 0x67, 0xF0, 0x40, 0x28, 0x42, 0x8C, 0x80, 0x40, 0x80, 0xC5, 0x80, 0x90, 0x80, 0xFF, 0x04, 0x81, 0x60, 0x00, 0xCC, 0xFF, 0xFF, 0xFF, 0x66, 0xF0, 0x40, 0x28, 0x42, 0x8C, 0x80, 0x40, 0x00, 0x51, 0xD0, 0x80, 0x07, 0x81, 0x60, 0x00, 0x86, 0xFF, 0xFF, 0xFF, 0xF3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x04, 0x80, 0xEE, 0x00, 0xF2, 0xFF, 0xFF, 0xFF }; /* clang-format on */ #endif /* PVR_VDM_LOAD_SR_H */
2d32973ad29fd1452532c0d971bcf47326c97ccc
909095842af0bbf2e769aff361b5af344abc7433
/engine/source/io/fileStreamObject_ScriptBinding.h
971aff524578b98503601b2724e35c4b4c781785
[ "MIT" ]
permissive
TorqueGameEngines/Torque2D
316105e8b91cebf8660ff43871440e1c4d0b1c5e
2c555d6dd0172a05ddb6a14f014d22f335b4ccad
refs/heads/master
2023-09-01T02:22:53.663431
2023-05-02T20:45:37
2023-05-02T20:45:37
268,352,960
1,001
117
MIT
2023-05-02T20:19:19
2020-05-31T19:51:55
C
UTF-8
C
false
false
2,558
h
fileStreamObject_ScriptBinding.h
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- static const struct { const char *strMode; FileStream::AccessMode mode; } gModeMap[]= { { "read", FileStream::Read }, { "write", FileStream::Write }, { "readwrite", FileStream::ReadWrite }, { "writeappend", FileStream::WriteAppend }, { NULL, (FileStream::AccessMode)0 } }; ConsoleMethodGroupBeginWithDocs(FileStreamObject, StreamObject) /*! Open a file. Mode can be one of Read, Write, ReadWrite or WriteAppend. */ ConsoleMethodWithDocs(FileStreamObject, open, ConsoleBool, 4, 4, (filename, mode)) { FileStream::AccessMode mode; bool found = false; for(S32 i = 0;gModeMap[i].strMode;++i) { if(dStricmp(gModeMap[i].strMode, argv[3]) == 0) { mode = gModeMap[i].mode; found = true; break; } } if(! found) { Con::errorf("FileStreamObject::open - Mode must be one of Read, Write, ReadWrite or WriteAppend."); return false; } char buffer[1024]; Con::expandPath(buffer, sizeof(buffer), argv[2]); return object->open(buffer, mode); } /*! Close the file. */ ConsoleMethodWithDocs(FileStreamObject, close, ConsoleVoid, 2, 2, ()) { object->close(); } ConsoleMethodGroupEndWithDocs(FileStreamObject)
be4824ccf3ec3944e9dd4ce6eacf81e9f3d7a422
94b153fe49c2e7bd901c4f26d3cc4134920b4ccf
/src/soter/ed25519/api.h
d88dae0c32c0241f6d9bcd48acafe7862a0d3e3d
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0" ]
permissive
cossacklabs/themis
d6d39836fcebe88d228d25a670a35c556b6a117d
86096502c48a80edb11f567c92e26eb463eae36c
refs/heads/master
2023-08-17T03:48:03.760843
2023-07-10T19:57:46
2023-07-10T19:57:46
35,159,920
1,831
168
Apache-2.0
2023-09-14T04:05:12
2015-05-06T13:25:25
C
UTF-8
C
false
false
121
h
api.h
#define CRYPTO_SECRETKEYBYTES 64 #define CRYPTO_PUBLICKEYBYTES 32 #define CRYPTO_BYTES 64 #define CRYPTO_DETERMINISTIC 1
82986780b72b4d04553a56e759f8c77d6dc4603f
ff44afc42082479d929e59c0100457f63cdf1028
/dart-impl/shmem/src/dart_memarea.c
17a99bb6073e50e95264c4572eb5849e05ea53c0
[ "BSD-3-Clause" ]
permissive
dash-project/dash
122f3f3106c4d6b0215908a3a28c565d46d66f56
99f299572bbb42f6668fbe704b179b9b5d0da92b
refs/heads/development
2021-08-19T13:28:46.595300
2021-04-28T08:24:20
2021-04-28T08:24:20
45,930,061
178
47
NOASSERTION
2021-06-09T12:24:54
2015-11-10T17:56:37
C++
UTF-8
C
false
false
1,088
c
dart_memarea.c
#include <dash/dart/shmem/dart_memarea.h> dart_memarea_t memarea; void dart_memarea_init() { int i; memarea.next_free = 0; for (i = 0; i < MAXNUM_MEMPOOLS; i++) { dart_mempool_init( &((memarea.mempools)[i]) ); } } dart_mempoolptr dart_memarea_get_mempool_by_id(int id) { dart_mempoolptr res = 0; if (0 <= id && id < MAXNUM_MEMPOOLS) { res = &((memarea.mempools)[id]); } return res; } int dart_memarea_create_mempool( dart_team_t teamid, size_t teamsize, dart_unit_t myid, size_t localsize, int is_aligned) { dart_ret_t ret; int res =- 1; if (0 <= memarea.next_free && memarea.next_free < MAXNUM_MEMPOOLS) { dart_mempoolptr pool = &((memarea.mempools)[memarea.next_free]); ret = dart_mempool_create( pool, teamid, teamsize, myid, localsize); if (ret == DART_OK) { res = memarea.next_free; pool->state = (is_aligned?MEMPOOL_ALIGNED:MEMPOOL_UNALIGNED); pool->teamid = teamid; memarea.next_free++; } } return res; }
26cc66320ded8143277515257b1add9994ad64f9
8a51a96f61699f0318315ccc89cef39f6866f2b5
/src/bin/pg_upgrade/tablespace.c
69cef7fa6b95fb909af0c3c73c6792574baba057
[ "PostgreSQL" ]
permissive
postgres/postgres
979febf2b41c00090d1256228f768f33e7ef3b6f
b5934bfd6071fed3a38cea0cfaa93afda63d9c0c
refs/heads/master
2023-08-31T00:10:01.373472
2023-08-30T23:07:48
2023-08-30T23:07:48
927,442
13,691
4,807
NOASSERTION
2023-09-09T13:59:15
2010-09-21T11:35:45
C
UTF-8
C
false
false
3,081
c
tablespace.c
/* * tablespace.c * * tablespace functions * * Copyright (c) 2010-2023, PostgreSQL Global Development Group * src/bin/pg_upgrade/tablespace.c */ #include "postgres_fe.h" #include "pg_upgrade.h" static void get_tablespace_paths(void); static void set_tablespace_directory_suffix(ClusterInfo *cluster); void init_tablespaces(void) { get_tablespace_paths(); set_tablespace_directory_suffix(&old_cluster); set_tablespace_directory_suffix(&new_cluster); if (os_info.num_old_tablespaces > 0 && strcmp(old_cluster.tablespace_suffix, new_cluster.tablespace_suffix) == 0) pg_fatal("Cannot upgrade to/from the same system catalog version when\n" "using tablespaces."); } /* * get_tablespace_paths() * * Scans pg_tablespace and returns a malloc'ed array of all tablespace * paths. It's the caller's responsibility to free the array. */ static void get_tablespace_paths(void) { PGconn *conn = connectToServer(&old_cluster, "template1"); PGresult *res; int tblnum; int i_spclocation; char query[QUERY_ALLOC]; snprintf(query, sizeof(query), "SELECT pg_catalog.pg_tablespace_location(oid) AS spclocation " "FROM pg_catalog.pg_tablespace " "WHERE spcname != 'pg_default' AND " " spcname != 'pg_global'"); res = executeQueryOrDie(conn, "%s", query); if ((os_info.num_old_tablespaces = PQntuples(res)) != 0) os_info.old_tablespaces = (char **) pg_malloc(os_info.num_old_tablespaces * sizeof(char *)); else os_info.old_tablespaces = NULL; i_spclocation = PQfnumber(res, "spclocation"); for (tblnum = 0; tblnum < os_info.num_old_tablespaces; tblnum++) { struct stat statBuf; os_info.old_tablespaces[tblnum] = pg_strdup(PQgetvalue(res, tblnum, i_spclocation)); /* * Check that the tablespace path exists and is a directory. * Effectively, this is checking only for tables/indexes in * non-existent tablespace directories. Databases located in * non-existent tablespaces already throw a backend error. * Non-existent tablespace directories can occur when a data directory * that contains user tablespaces is moved as part of pg_upgrade * preparation and the symbolic links are not updated. */ if (stat(os_info.old_tablespaces[tblnum], &statBuf) != 0) { if (errno == ENOENT) report_status(PG_FATAL, "tablespace directory \"%s\" does not exist", os_info.old_tablespaces[tblnum]); else report_status(PG_FATAL, "could not stat tablespace directory \"%s\": %s", os_info.old_tablespaces[tblnum], strerror(errno)); } if (!S_ISDIR(statBuf.st_mode)) report_status(PG_FATAL, "tablespace path \"%s\" is not a directory", os_info.old_tablespaces[tblnum]); } PQclear(res); PQfinish(conn); } static void set_tablespace_directory_suffix(ClusterInfo *cluster) { /* This cluster has a version-specific subdirectory */ /* The leading slash is needed to start a new directory. */ cluster->tablespace_suffix = psprintf("/PG_%s_%d", cluster->major_version_str, cluster->controldata.cat_ver); }
fc61e5f18b6e5ab3cba423595da058c8539d2244
0577a46d8d28e1fd8636893bbdd2b18270bb8eb8
/update_notifier/thirdparty/wxWidgets/docs/doxygen/groups/funcmacro_rtti.h
420d5948f2290770a59f6899c2f3283fb8fe004c
[ "BSD-3-Clause", "LicenseRef-scancode-other-copyleft", "WxWindows-exception-3.1", "LGPL-2.0-or-later", "GPL-1.0-or-later", "IJG", "GPL-2.0-only", "LGPL-2.0-only" ]
permissive
ric2b/Vivaldi-browser
388a328b4cb838a4c3822357a5529642f86316a5
87244f4ee50062e59667bf8b9ca4d5291b6818d7
refs/heads/master
2022-12-21T04:44:13.804535
2022-12-17T16:30:35
2022-12-17T16:30:35
86,637,416
166
41
BSD-3-Clause
2021-03-31T18:49:30
2017-03-29T23:09:05
null
UTF-8
C
false
false
1,030
h
funcmacro_rtti.h
///////////////////////////////////////////////////////////////////////////// // Name: funcmacro_rtti.h // Purpose: Runtime Type Information function and macro group docs // Author: wxWidgets team // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// /** @defgroup group_funcmacro_rtti Runtime Type Information (RTTI) @ingroup group_funcmacro wxWidgets uses its own RTTI ("run-time type identification") system which predates the current standard C++ RTTI and so is kept for backwards compatibility reasons but also because it allows some things which the standard RTTI doesn't directly support (such as creating a class from its name). The standard C++ RTTI can be used in the user code without any problems and in general you shouldn't need to use the functions and the macros in this section unless you are thinking of modifying or adding any wxWidgets classes. Related Overviews: @ref overview_rtti Related class group: @ref group_class_rtti */
3fa3a64e1d8dced7d6482284eff270f3e38d02b9
a12b448f44beb4d521cb7e31677281f41df35f0b
/benchmarks/halide/wrapper_divergence2d.h
cfc4f2e6824034f4b44d38051ce8b859db5e63c9
[ "MIT" ]
permissive
Tiramisu-Compiler/tiramisu
d45f65dd9c35f643b3531ec79df1203c7ea3371d
f13e480f0ddb142cec371b7d7431a41d8ca885ec
refs/heads/master
2023-08-25T12:21:26.889736
2023-05-09T18:40:52
2023-05-09T18:40:52
58,378,976
906
168
MIT
2023-09-08T11:47:06
2016-05-09T13:33:51
C++
UTF-8
C
false
false
689
h
wrapper_divergence2d.h
#ifndef HALIDE__build___wrapper_divergence2d_o_h #define HALIDE__build___wrapper_divergence2d_o_h #include <tiramisu/utils.h> #ifdef __cplusplus extern "C" { #endif int divergence2d_tiramisu(halide_buffer_t *_b_input_buffer, halide_buffer_t *_b_blury_buffer); int divergence2d_tiramisu_argv(void **args); int divergence2d_ref(halide_buffer_t *_b_input_buffer, halide_buffer_t *_b_blury_buffer); int divergence2d_ref_argv(void **args); // Result is never null and points to constant static data const struct halide_filter_metadata_t *divergence2d_tiramisu_metadata(); const struct halide_filter_metadata_t *divergence2d_ref_metadata(); #ifdef __cplusplus } // extern "C" #endif #endif
cdc3511fda1fa1375e8e89ec28d9c4240dcd519b
8023a4ffb780d18f77766744668e05a246ed7f8e
/windows/project/part10/test/p4_test.c
5988bdf3588286a045ef36962ccd5728ea058fd9
[ "MIT" ]
permissive
Manistein/dummylua-tutorial
e6768ac28c525b0a9ef7523d18f4dd1768e96572
c8158625ac5665f9726515ccb3a835f6474641b3
refs/heads/master
2023-05-12T22:14:49.160230
2023-04-26T07:31:29
2023-04-26T07:31:29
153,052,447
395
59
MIT
2022-06-08T01:58:02
2018-10-15T04:17:50
C
UTF-8
C
false
false
3,919
c
p4_test.c
#include "p4_test.h" #include "../clib/luaaux.h" #include "../common/luatable.h" #include "../vm/luagc.h" #include "../common/luastring.h" static void print_object(struct lua_State* L, TValue* o) { switch(o->tt_) { case LUA_TNIL: { printf("nil\n"); } break; case LUA_NUMINT: { printf("type:int value:%d\n", (int)o->value_.i); } break; case LUA_TBOOLEAN: { printf("type:boolean value:%d\n", (int)o->value_.b); } break; case LUA_NUMFLT: { printf("type:float value:%f\n", (float)o->value_.n); } break; case LUA_SHRSTR:; case LUA_LNGSTR: { printf("type string value:%s\n", getstr(gco2ts(gcvalue(o)))); } break; case LUA_TLCF: { printf("type cfunc value:%d\n", point2uint(o->value_.f)); } break; default : break; } } static int test_func(struct lua_State* L) { printf("this is a test func hahaha! \n"); return 0; } static void test_kv(struct lua_State* L) { int tbl_idx = luaL_stacksize(L); printf("stack_size:%d tbl_idx:%d\n", luaL_stacksize(L), tbl_idx); // push integer key luaL_pushinteger(L, 1); luaL_pushstring(L, "test integer key"); luaL_settable(L, tbl_idx); // push short string key luaL_pushstring(L, "short string key"); luaL_pushstring(L, "test short string key"); luaL_settable(L, tbl_idx); // push long string key luaL_pushstring(L, "This is long string key! This is long string key! This is long string key! This is long string key! "); luaL_pushstring(L, "This is long string key! This is long string key! This is long string key! This is long string key! "); luaL_settable(L, tbl_idx); // push float key luaL_pushnumber(L, 2.0f); luaL_pushstring(L, "test float key"); luaL_settable(L, tbl_idx); // push boolean key luaL_pushboolean(L, 1); luaL_pushstring(L, "test boolean key"); luaL_settable(L, tbl_idx); // push function key(test pointer) luaL_pushcfunction(L, &test_func); luaL_pushstring(L, "test pointer key"); luaL_settable(L, tbl_idx); luaL_pushinteger(L, 1); // luaL_pushstring(L, "short string key"); luaL_gettable(L, tbl_idx); print_object(L, L->top - 1); luaL_pop(L); // now top is table TValue* tbl_object = luaL_index2addr(L, tbl_idx); struct Table* t = gco2tbl(gcvalue(tbl_object)); printf("test t->tt_:%d stack_size:%d\n", t->tt_, luaL_stacksize(L)); luaL_pushinteger(L, 1); // push nil, this slot is for key luaL_pushnil(L); // push nil, this slot is for value while(luaH_next(L, t, L->top - 2) == LUA_OK) { printf("key:"); print_object(L, L->top - 2); printf("value:"); print_object(L, L->top - 1); } printf("getn = %d\n", luaH_getn(L, t)); luaL_pop(L); luaL_pop(L); } static void test_gc(struct lua_State* L) { int start_time = (int)time(NULL); int end_time = (int)time(NULL); size_t max_bytes = 0; struct global_State* g = G(L); int j = 0; for (; j < 50000; j ++) { luaL_createtable(L); test_kv(L); luaL_pop(L); luaC_checkgc(L); if ((g->totalbytes + g->GCdebt) > max_bytes) { max_bytes = g->totalbytes + g->GCdebt; } if (j % 1000 == 0) { printf("timestamp:%d totalbytes:%f kb \n", (int)time(NULL), (float)(g->totalbytes + g->GCdebt) / 1024.0f); } } end_time = (int)time(NULL); printf("finish test start_time:%d end_time:%d max_bytes:%f kb j:%d\n", start_time, end_time, (float)max_bytes / 1024.0f, j); } void p4_test_main() { struct lua_State* L = luaL_newstate(); luaL_createtable(L); test_kv(L); luaL_pop(L); // pop table luaL_getglobal(L); test_kv(L); luaL_pop(L); test_gc(L); luaL_close(L); }
13cbd37cbaffc98cecbccd8ff6855ae96e44dd8e
85ccd32aa73eecf274a937f1fc3b6f4d484b77da
/test cases/common/168 preserve gendir/testprog.c
b6a99268ab89e3d6619acdee394b1ec7419b3bad
[ "Apache-2.0" ]
permissive
mesonbuild/meson
48321cf4235dfcc0194fed90ff43a57367592bf7
cf5adf0c646474f0259d123fad60ca5ed38ec891
refs/heads/master
2023-09-01T05:58:50.807952
2023-03-17T20:27:37
2023-08-31T11:52:41
19,784,232
5,122
1,848
Apache-2.0
2023-09-14T15:47:23
2014-05-14T15:08:16
Python
UTF-8
C
false
false
101
c
testprog.c
#include"base.h" #include"com/mesonbuild/subbie.h" int main(void) { return base() + subbie(); }
4843479194a129f8bcd0f0419b22313e915d8ebb
2247493654c160426c1655281aa7f1dca2bc98dd
/src/kernel/MomentumSymmetryElemKernel.C
4bec303d517a11df2ae54c818ce0e93e1e9f7464
[ "BSD-2-Clause" ]
permissive
NaluCFD/Nalu
12999b0e3b76dbeab8fc184f38b65a13b1180bce
3286651e494894ac5948c41bf985f987d20c2370
refs/heads/master
2023-08-10T02:48:04.179859
2023-08-02T19:02:46
2023-08-02T19:02:46
69,712,764
138
185
NOASSERTION
2023-09-14T16:42:19
2016-10-01T01:25:20
C
UTF-8
C
false
false
6,354
c
MomentumSymmetryElemKernel.C
/*------------------------------------------------------------------------*/ /* Copyright 2014 Sandia Corporation. */ /* This software is released under the license detailed */ /* in the file, LICENSE, which is located in the top-level Nalu */ /* directory structure */ /*------------------------------------------------------------------------*/ #include "kernel/MomentumSymmetryElemKernel.h" #include "master_element/MasterElement.h" #include "SolutionOptions.h" // template and scratch space #include "BuildTemplates.h" #include "ScratchViews.h" // stk_mesh/base/fem #include <stk_mesh/base/Entity.hpp> #include <stk_mesh/base/MetaData.hpp> #include <stk_mesh/base/Field.hpp> namespace sierra { namespace nalu { template<typename BcAlgTraits> MomentumSymmetryElemKernel<BcAlgTraits>::MomentumSymmetryElemKernel( const stk::mesh::MetaData &metaData, const SolutionOptions &solnOpts, VectorFieldType *velocity, ScalarFieldType *viscosity, ElemDataRequests &faceDataPreReqs, ElemDataRequests &elemDataPreReqs) : Kernel(), viscosity_(viscosity), includeDivU_(solnOpts.includeDivU_), shiftedGradOp_(solnOpts.get_shifted_grad_op(velocity->name())), meSCS_(sierra::nalu::MasterElementRepo::get_surface_master_element(BcAlgTraits::elemTopo_)) { velocityNp1_ = &(velocity->field_of_state(stk::mesh::StateNP1)); coordinates_ = metaData.get_field<double>(stk::topology::NODE_RANK, solnOpts.get_coordinates_name()); exposedAreaVec_ = metaData.get_field<double>(metaData.side_rank(), "exposed_area_vector"); // extract master elements MasterElement* meFC = sierra::nalu::MasterElementRepo::get_surface_master_element(BcAlgTraits::faceTopo_); // add master elements faceDataPreReqs.add_cvfem_face_me(meFC); elemDataPreReqs.add_cvfem_surface_me(meSCS_); // fields and data; face and then element faceDataPreReqs.add_gathered_nodal_field(*viscosity_, 1); faceDataPreReqs.add_face_field(*exposedAreaVec_, BcAlgTraits::numFaceIp_, BcAlgTraits::nDim_); elemDataPreReqs.add_coordinates_field(*coordinates_, BcAlgTraits::nDim_, CURRENT_COORDINATES); elemDataPreReqs.add_gathered_nodal_field(*velocityNp1_, BcAlgTraits::nDim_); if ( shiftedGradOp_ ) elemDataPreReqs.add_master_element_call(SCS_SHIFTED_FACE_GRAD_OP, CURRENT_COORDINATES); else elemDataPreReqs.add_master_element_call(SCS_FACE_GRAD_OP, CURRENT_COORDINATES); // never shift properties get_face_shape_fn_data<BcAlgTraits>([&](double* ptr){meFC->shape_fcn(ptr);}, vf_shape_function_); } template<typename BcAlgTraits> MomentumSymmetryElemKernel<BcAlgTraits>::~MomentumSymmetryElemKernel() {} template<typename BcAlgTraits> void MomentumSymmetryElemKernel<BcAlgTraits>::execute( SharedMemView<DoubleType**> &lhs, SharedMemView<DoubleType *> &rhs, ScratchViews<DoubleType> &faceScratchViews, ScratchViews<DoubleType> &elemScratchViews, int elemFaceOrdinal) { NALU_ALIGNED DoubleType w_nx[BcAlgTraits::nDim_]; // face SharedMemView<DoubleType*>& vf_viscosity = faceScratchViews.get_scratch_view_1D(*viscosity_); SharedMemView<DoubleType**>& vf_exposedAreaVec = faceScratchViews.get_scratch_view_2D(*exposedAreaVec_); // element SharedMemView<DoubleType**>& v_uNp1 = elemScratchViews.get_scratch_view_2D(*velocityNp1_); SharedMemView<DoubleType***>& v_dndx_fc_elem = shiftedGradOp_ ? elemScratchViews.get_me_views(CURRENT_COORDINATES).dndx_shifted_fc_elem : elemScratchViews.get_me_views(CURRENT_COORDINATES).dndx_fc_elem; for (int ip=0; ip < BcAlgTraits::numFaceIp_; ++ip) { const int nearestNode = meSCS_->ipNodeMap(elemFaceOrdinal)[ip]; // "Right" // form unit normal DoubleType asq = 0.0; for ( int j = 0; j < BcAlgTraits::nDim_; ++j ) { const DoubleType axj = vf_exposedAreaVec(ip,j); asq += axj*axj; } const DoubleType amag = stk::math::sqrt(asq); for ( int i = 0; i < BcAlgTraits::nDim_; ++i ) { w_nx[i] = vf_exposedAreaVec(ip,i)/amag; } DoubleType viscBip = 0.0; for ( int ic = 0; ic < BcAlgTraits::nodesPerFace_; ++ic ) { const DoubleType r = vf_shape_function_(ip,ic); viscBip += r*vf_viscosity(ic); } for ( int ic = 0; ic < BcAlgTraits::nodesPerElement_; ++ic ) { const int icNdim = ic*BcAlgTraits::nDim_; for ( int j = 0; j < BcAlgTraits::nDim_; ++j ) { const DoubleType axj = vf_exposedAreaVec(ip,j); const DoubleType dndxj = v_dndx_fc_elem(ip,ic,j); const DoubleType uxj = v_uNp1(ic,j); const DoubleType divUstress = 2.0/3.0*viscBip*dndxj*uxj*axj*includeDivU_; for ( int i = 0; i < BcAlgTraits::nDim_; ++i ) { const int indexR = nearestNode*BcAlgTraits::nDim_ +i; const DoubleType dndxi = v_dndx_fc_elem(ip,ic,i); const DoubleType uxi = v_uNp1(ic,i); const DoubleType nxi = w_nx[i]; const DoubleType nxinxi = nxi*nxi; // -mu*dui/dxj*Aj*ni*ni; sneak in divU (explicit) DoubleType lhsfac = -viscBip*dndxj*axj*nxinxi; lhs(indexR,icNdim+i) += lhsfac; rhs(indexR) -= lhsfac*uxi + divUstress*nxinxi; // -mu*duj/dxi*Aj*ni*ni lhsfac = -viscBip*dndxi*axj*nxinxi; lhs(indexR,icNdim+j) += lhsfac; rhs(indexR) -= lhsfac*uxj; // now we need the +nx*ny*Fy + nx*nz*Fz part for ( int l = 0; l < BcAlgTraits::nDim_; ++l ) { if ( i != l ) { const DoubleType nxinxl = nxi*w_nx[l]; const DoubleType uxl = v_uNp1(ic,l); const DoubleType dndxl = v_dndx_fc_elem(ip,ic,l); // -ni*nl*mu*dul/dxj*Aj; sneak in divU (explicit) lhsfac = -viscBip*dndxj*axj*nxinxl; lhs(indexR,icNdim+l) += lhsfac; rhs(indexR) -= lhsfac*uxl + divUstress*nxinxl; // -ni*nl*mu*duj/dxl*Aj lhsfac = -viscBip*dndxl*axj*nxinxl; lhs(indexR,icNdim+j) += lhsfac; rhs(indexR) -= lhsfac*uxj; } } } } } } } INSTANTIATE_KERNEL_FACE_ELEMENT(MomentumSymmetryElemKernel); } // nalu } // sierra
5907adcf9476409b3d4f20d5364f070306985fbe
bcb62f36caa6ab1f92715cffae29cf4353d247e8
/src/course_yoshi_valley_offsets.c
a4224cb431db4137501735c9ae3051d89c6f2d0c
[]
no_license
n64decomp/mk64
4b74ffb8c896e739b908534b74bc1cb79a21ae60
c4c00f159845fddd1eced906c14cc25a0cb7a10b
refs/heads/master
2023-09-01T02:48:30.111868
2023-09-01T02:28:49
2023-09-01T02:28:49
304,205,548
476
88
null
2023-09-14T04:36:28
2020-10-15T04:01:57
C
UTF-8
C
false
false
1,222
c
course_yoshi_valley_offsets.c
#include <PR/ultratypes.h> #include "course_offsets.h" extern u8 gTexture66EBF0[]; extern u8 gTextureWoodBridgeSlats[]; extern u8 gTexture65E2EC[]; extern u8 gTexture6846DC[]; extern u8 gTextureFenceRope[]; extern u8 gTexture685108[]; extern u8 gTexture64CC20[]; extern u8 gTextureGrass4[]; extern u8 gTexture6775EC[]; extern u8 gTexture68E2D0[]; extern u8 gTextureCheckerboardBlackWhite[]; extern u8 gTexture643B3C[]; extern u8 gTextureSignWoodRedArrow[]; extern u8 gTexture68DEC0[]; const course_texture yoshi_valley_textures[] = { {gTexture66EBF0, 0x0146, 0x0800, 0x0}, {gTextureWoodBridgeSlats, 0x0DAB, 0x1000, 0x0}, {gTexture65E2EC, 0x02B0, 0x0800, 0x0}, {gTexture6846DC, 0x04EA, 0x0800, 0x0}, {gTextureFenceRope, 0x0540, 0x0800, 0x0}, {gTexture685108, 0x04D4, 0x0800, 0x0}, {gTexture64CC20, 0x0EC3, 0x1000, 0x0}, {gTextureGrass4, 0x05C3, 0x0800, 0x0}, {gTexture6775EC, 0x0233, 0x1000, 0x0}, {gTexture68E2D0, 0x087F, 0x0800, 0x0}, {gTextureCheckerboardBlackWhite, 0x0107, 0x0800, 0x0}, {gTexture643B3C, 0x0798, 0x0800, 0x0}, {gTextureSignWoodRedArrow, 0x04E1, 0x1000, 0x0}, {gTexture68DEC0, 0x0410, 0x0800, 0x0}, {0x00000000 , 0x0000, 0x0000, 0x0}, };
01083f32c83b6e69ab0c008064dfb7810fb35c23
d38ed5f31d74a79a054ed55dd9123a8d615283b9
/third_party/libgit2/src/diff_parse.c
b4c76a3eb7074e69b1515907628a2453a34e87e0
[ "Apache-2.0", "GPL-2.0-only", "LicenseRef-scancode-public-domain", "GCC-exception-2.0", "LGPL-2.0-or-later", "Zlib", "LGPL-2.1-or-later", "LGPL-2.1-only", "ISC", "MIT" ]
permissive
chigraph/chigraph
8ff76a14337da29fa2b2a84d5c35f2eac4156c6e
6981bdd6763db54edfe284c1f7d223193584c69a
refs/heads/master
2022-12-21T13:46:57.273039
2022-12-17T18:41:19
2022-12-17T18:41:19
60,776,831
364
65
Apache-2.0
2019-12-13T14:46:43
2016-06-09T13:27:37
C++
UTF-8
C
false
false
2,378
c
diff_parse.c
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "diff_parse.h" #include "diff.h" #include "patch.h" #include "patch_parse.h" static void diff_parsed_free(git_diff *d) { git_diff_parsed *diff = (git_diff_parsed *)d; git_patch *patch; size_t i; git_vector_foreach(&diff->patches, i, patch) git_patch_free(patch); git_vector_free(&diff->patches); git_vector_free(&diff->base.deltas); git_pool_clear(&diff->base.pool); git__memzero(diff, sizeof(*diff)); git__free(diff); } static git_diff_parsed *diff_parsed_alloc(void) { git_diff_parsed *diff; if ((diff = git__calloc(1, sizeof(git_diff_parsed))) == NULL) return NULL; GIT_REFCOUNT_INC(&diff->base); diff->base.type = GIT_DIFF_TYPE_PARSED; diff->base.strcomp = git__strcmp; diff->base.strncomp = git__strncmp; diff->base.pfxcomp = git__prefixcmp; diff->base.entrycomp = git_diff__entry_cmp; diff->base.patch_fn = git_patch_parsed_from_diff; diff->base.free_fn = diff_parsed_free; if (git_diff_init_options(&diff->base.opts, GIT_DIFF_OPTIONS_VERSION) < 0) { git__free(diff); return NULL; } diff->base.opts.flags &= ~GIT_DIFF_IGNORE_CASE; git_pool_init(&diff->base.pool, 1); if (git_vector_init(&diff->patches, 0, NULL) < 0 || git_vector_init(&diff->base.deltas, 0, git_diff_delta__cmp) < 0) { git_diff_free(&diff->base); return NULL; } git_vector_set_cmp(&diff->base.deltas, git_diff_delta__cmp); return diff; } int git_diff_from_buffer( git_diff **out, const char *content, size_t content_len) { git_diff_parsed *diff; git_patch *patch; git_patch_parse_ctx *ctx = NULL; int error = 0; *out = NULL; diff = diff_parsed_alloc(); GIT_ERROR_CHECK_ALLOC(diff); ctx = git_patch_parse_ctx_init(content, content_len, NULL); GIT_ERROR_CHECK_ALLOC(ctx); while (ctx->parse_ctx.remain_len) { if ((error = git_patch_parse(&patch, ctx)) < 0) break; git_vector_insert(&diff->patches, patch); git_vector_insert(&diff->base.deltas, patch->delta); } if (error == GIT_ENOTFOUND && git_vector_length(&diff->patches) > 0) { git_error_clear(); error = 0; } git_patch_parse_ctx_free(ctx); if (error < 0) git_diff_free(&diff->base); else *out = &diff->base; return error; }
1416146b85c9517c1a8149857d84bc9fee98c5c7
08d6e4a36de09b2aff205d83178440e4ddf30b6b
/tkvdb.h
a580c01c2f44eae2655bf0083e5c5eeba9feb64c
[ "ISC" ]
permissive
vmxdev/tkvdb
315f7c0b42b0e795ce2d3b625bdc89259f93fe81
701c29a11dd9aee12a0023127a3b7e76e9a9176c
refs/heads/master
2023-03-09T00:08:36.193426
2022-02-18T20:25:11
2022-02-18T20:25:11
70,838,515
330
27
ISC
2018-07-23T09:49:51
2016-10-13T18:59:37
C
UTF-8
C
false
false
4,911
h
tkvdb.h
#ifndef tkvdb_h_included #define tkvdb_h_included #include <limits.h> #include <stdint.h> #include <stddef.h> typedef struct tkvdb tkvdb; typedef struct tkvdb_params tkvdb_params; typedef struct tkvdb_triggers tkvdb_triggers; typedef enum TKVDB_RES { TKVDB_OK = 0, TKVDB_IO_ERROR, TKVDB_LOCKED, TKVDB_EMPTY, TKVDB_NOT_FOUND, TKVDB_ENOMEM, TKVDB_CORRUPTED, TKVDB_NOT_STARTED, TKVDB_MODIFIED } TKVDB_RES; typedef enum TKVDB_SEEK { TKVDB_SEEK_EQ, TKVDB_SEEK_LE, TKVDB_SEEK_GE } TKVDB_SEEK; /* database (or transaction) parameters */ typedef enum TKVDB_PARAM { /* dynamically allocate space for nodes (using system malloc() for each node) */ TKVDB_PARAM_TR_DYNALLOC, /* transaction size limit, default SIZE_MAX, e.g. no limit */ TKVDB_PARAM_TR_LIMIT, /* align value in memory (0 or 1 for none), must be power of two */ TKVDB_PARAM_ALIGNVAL, /* automatically start transaction after commit() and rollback(), transaction created in started state, begin() is ignored */ TKVDB_PARAM_AUTOBEGIN, /* dynamically allocate space for cursors stacks, default 1 */ TKVDB_PARAM_CURSOR_STACK_DYNALLOC, /* cursors stacks size limit, default SIZE_MAX */ TKVDB_PARAM_CURSOR_STACK_LIMIT, /* dynamically allocate space for cursor key, default 1 */ TKVDB_PARAM_CURSOR_KEY_DYNALLOC, /* cursor key size limit, default SIZE_MAX */ TKVDB_PARAM_CURSOR_KEY_LIMIT, /* flags passed to open() function */ TKVDB_PARAM_DBFILE_OPEN_FLAGS } TKVDB_PARAM; typedef struct tkvdb_datum { void *data; size_t size; } tkvdb_datum; typedef struct tkvdb_tr tkvdb_tr; struct tkvdb_tr { TKVDB_RES (*begin)(tkvdb_tr *tr); TKVDB_RES (*commit)(tkvdb_tr *tr); TKVDB_RES (*rollback)(tkvdb_tr *tr); TKVDB_RES (*put)(tkvdb_tr *tr, const tkvdb_datum *key, const tkvdb_datum *val); TKVDB_RES (*get)(tkvdb_tr *tr, const tkvdb_datum *key, tkvdb_datum *val); TKVDB_RES (*del)(tkvdb_tr *tr, const tkvdb_datum *key, int del_pfx); /* get size of memory used by transaction */ size_t (*mem)(tkvdb_tr *tr); void (*free)(tkvdb_tr *tr); void *data; /* triggers and metadata */ TKVDB_RES (*putx)(tkvdb_tr *tr, const tkvdb_datum *key, const tkvdb_datum *val, tkvdb_triggers *triggers); TKVDB_RES (*delx)(tkvdb_tr *tr, const tkvdb_datum *key, int del_pfx, tkvdb_triggers *triggers); TKVDB_RES (*subnode)(tkvdb_tr *tr, void *node, int n, void **subnode, tkvdb_datum *prefix, tkvdb_datum *val, tkvdb_datum *meta); }; typedef struct tkvdb_cursor tkvdb_cursor; struct tkvdb_cursor { void *(*key)(tkvdb_cursor *c); size_t (*keysize)(tkvdb_cursor *c); void *(*val)(tkvdb_cursor *c); size_t (*valsize)(tkvdb_cursor *c); /* alternate way to get key/value */ tkvdb_datum (*key_datum)(tkvdb_cursor *c); tkvdb_datum (*val_datum)(tkvdb_cursor *c); TKVDB_RES (*seek)(tkvdb_cursor *c, const tkvdb_datum *key, TKVDB_SEEK seek); TKVDB_RES (*first)(tkvdb_cursor *c); TKVDB_RES (*last)(tkvdb_cursor *c); TKVDB_RES (*next)(tkvdb_cursor *c); TKVDB_RES (*prev)(tkvdb_cursor *c); void (*free)(tkvdb_cursor *c); void *data; }; /* triggers */ /* types of modification */ enum TKVDB_TRIGGER_MOD_TYPE { TKVDB_TRIGGER_UPDATE, TKVDB_TRIGGER_INSERT_NEWROOT, TKVDB_TRIGGER_INSERT_SUBKEY, TKVDB_TRIGGER_INSERT_NEWNODE, TKVDB_TRIGGER_INSERT_SHORTER, TKVDB_TRIGGER_INSERT_LONGER, TKVDB_TRIGGER_INSERT_SPLIT, TKVDB_TRIGGER_DELETE_ROOT, TKVDB_TRIGGER_DELETE_PREFIX, TKVDB_TRIGGER_DELETE_LEAF, TKVDB_TRIGGER_DELETE_INTNODE }; typedef struct tkvdb_trigger_stack { size_t size, limit; void **meta; } tkvdb_trigger_stack; typedef struct tkvdb_trigger_info { tkvdb_trigger_stack *stack; enum TKVDB_TRIGGER_MOD_TYPE type; void *newroot, *subnode1, *subnode2; void *userdata; } tkvdb_trigger_info; typedef TKVDB_RES (*tkvdb_trigger_func)(tkvdb_trigger_info *info); #ifdef __cplusplus extern "C" { #endif /* allocate and fill db params with default values */ tkvdb_params *tkvdb_params_create(void); /* change parameter */ void tkvdb_param_set(tkvdb_params *params, TKVDB_PARAM p, int64_t val); /* free */ void tkvdb_params_free(tkvdb_params *params); /* database */ tkvdb *tkvdb_open(const char *path, tkvdb_params *params); TKVDB_RES tkvdb_close(tkvdb *db); /* fsync() db file */ TKVDB_RES tkvdb_sync(tkvdb *db); /* in-memory transaction */ tkvdb_tr *tkvdb_tr_create(tkvdb *db, tkvdb_params *params); /* cursors */ tkvdb_cursor *tkvdb_cursor_create(tkvdb_tr *tr); /* vacuum */ TKVDB_RES tkvdb_vacuum(tkvdb_tr *tr, tkvdb_tr *vac, tkvdb_tr *tres, tkvdb_cursor *c); /* get database file information */ TKVDB_RES tkvdb_dbinfo(tkvdb *db, uint64_t *root_off, uint64_t *gap_begin, uint64_t *gap_end); /* triggers */ tkvdb_triggers *tkvdb_triggers_create(size_t stack_limit); void tkvdb_triggers_free(tkvdb_triggers *triggers); TKVDB_RES tkvdb_triggers_add(tkvdb_triggers *triggers, tkvdb_trigger_func t, size_t meta_size, void *userdata); #ifdef __cplusplus } #endif #endif
6ee394af85d96d98ac518e3a2fca42657b6ee2fc
7d3d2af0389f9c0dee5d7ca789660bf21d97249d
/examples/example_d_lu_factorization.c
ddad1c01470ac8bcc9d21c2a67555f58f4e39cbc
[ "BSD-2-Clause" ]
permissive
giaf/blasfeo
0ecbcd67429d0507d7f462c090037c388e84a49e
b85a0c3121eae491480f07774fedf67e76b1f038
refs/heads/master
2023-07-22T15:40:53.961071
2023-07-18T15:42:08
2023-07-18T15:42:08
70,173,581
248
78
NOASSERTION
2022-11-25T15:42:08
2016-10-06T16:48:09
Assembly
UTF-8
C
false
false
9,180
c
example_d_lu_factorization.c
/************************************************************************************************** * * * This file is part of BLASFEO. * * * * BLASFEO -- BLAS For Embedded Optimization. * * Copyright (C) 2019 by Gianluca Frison. * * Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * * All rights reserved. * * * * The 2-Clause BSD License * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * * 1. Redistributions of source code must retain the above copyright notice, this * * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * * this list of conditions and the following disclaimer in the documentation * * and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * * * **************************************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <blasfeo.h> int main() { printf("\nExample of LU factorization and backsolve\n\n"); #if defined(LA_HIGH_PERFORMANCE) printf("\nLA provided by BLASFEO\n\n"); #elif defined(LA_REFERENCE) printf("\nLA provided by REFERENCE\n\n"); #elif defined(LA_EXTERNAL_BLAS_WRAPPER) printf("\nLA provided by EXTERNAL_BLAS_WRAPPER\n\n"); #else printf("\nLA provided by ???\n\n"); exit(2); #endif printf( "Testing processor\n" ); char supportString[50]; blasfeo_processor_library_string( supportString ); printf( "Library requires processor features:%s\n", supportString ); int features = 0; int procCheckSucceed = blasfeo_processor_cpu_features( &features ); blasfeo_processor_feature_string( features, supportString ); printf( "Processor supports features:%s\n", supportString ); if( !procCheckSucceed ) { printf("Current processor does not support the current compiled BLASFEO library.\n"); printf("Please get a BLASFEO library compatible with this processor.\n"); exit(3); } int ii; int n = 16; // // matrices in column-major format // double *A; d_zeros(&A, n, n); for(ii=0; ii<n*n; ii++) A[ii] = ii; // d_print_mat(n, n, A, n); // spd matrix double *B; d_zeros(&B, n, n); for(ii=0; ii<n; ii++) B[ii*(n+1)] = 1.0; // d_print_mat(n, n, B, n); // identity double *I; d_zeros(&I, n, n); for(ii=0; ii<n; ii++) I[ii*(n+1)] = 1.0; // d_print_mat(n, n, B, n); // result matrix double *D; d_zeros(&D, n, n); // d_print_mat(n, n, D, n); // permutation indeces int *ipiv; int_zeros(&ipiv, n, 1); // // matrices in matrix struct format // // work space enough for 6 matrix structs for size n times n int size_strmat = 6*blasfeo_memsize_dmat(n, n); void *memory_strmat; v_zeros_align(&memory_strmat, size_strmat); char *ptr_memory_strmat = (char *) memory_strmat; struct blasfeo_dmat sA; // blasfeo_allocate_dmat(n, n, &sA); blasfeo_create_dmat(n, n, &sA, ptr_memory_strmat); ptr_memory_strmat += sA.memsize; // convert from column major matrix to strmat blasfeo_pack_dmat(n, n, A, n, &sA, 0, 0); printf("\nA = \n"); blasfeo_print_dmat(n, n, &sA, 0, 0); struct blasfeo_dmat sB; // blasfeo_allocate_dmat(n, n, &sB); blasfeo_create_dmat(n, n, &sB, ptr_memory_strmat); ptr_memory_strmat += sB.memsize; // convert from column major matrix to strmat blasfeo_pack_dmat(n, n, B, n, &sB, 0, 0); printf("\nB = \n"); blasfeo_print_dmat(n, n, &sB, 0, 0); struct blasfeo_dmat sI; // blasfeo_allocate_dmat(n, n, &sI); blasfeo_create_dmat(n, n, &sI, ptr_memory_strmat); ptr_memory_strmat += sI.memsize; // convert from column major matrix to strmat struct blasfeo_dmat sD; // blasfeo_allocate_dmat(n, n, &sD); blasfeo_create_dmat(n, n, &sD, ptr_memory_strmat); ptr_memory_strmat += sD.memsize; struct blasfeo_dmat sLU; // blasfeo_allocate_dmat(n, n, &sD); blasfeo_create_dmat(n, n, &sLU, ptr_memory_strmat); ptr_memory_strmat += sLU.memsize; struct blasfeo_dmat sLUt; // blasfeo_allocate_dmat(n, n, &sD); blasfeo_create_dmat(n, n, &sLUt, ptr_memory_strmat); ptr_memory_strmat += sLUt.memsize; blasfeo_dgemm_nt(n, n, n, 1.0, &sA, 0, 0, &sA, 0, 0, 1.0, &sB, 0, 0, &sD, 0, 0); printf("\nB+A*A' = \n"); blasfeo_print_dmat(n, n, &sD, 0, 0); // blasfeo_dgetrf_nopivot(n, n, &sD, 0, 0, &sD, 0, 0); blasfeo_dgetrf_rp(n, n, &sD, 0, 0, &sLU, 0, 0, ipiv); printf("\nLU = \n"); blasfeo_print_dmat(n, n, &sLU, 0, 0); printf("\nipiv = \n"); int_print_mat(1, n, ipiv, 1); #if 0 // solve A X = P L U X = B => L U X = P^T B blasfeo_pack_dmat(n, n, I, n, &sI, 0, 0); printf("\nI = \n"); blasfeo_print_dmat(n, n, &sI, 0, 0); blasfeo_drowpe(n, ipiv, &sI); printf("\nperm(I) = \n"); blasfeo_print_dmat(n, n, &sI, 0, 0); blasfeo_dtrsm_llnu(n, n, 1.0, &sLU, 0, 0, &sI, 0, 0, &sD, 0, 0); printf("\nperm(inv(L)) = \n"); blasfeo_print_dmat(n, n, &sD, 0, 0); blasfeo_dtrsm_lunn(n, n, 1.0, &sLU, 0, 0, &sD, 0, 0, &sD, 0, 0); printf("\ninv(A) = \n"); blasfeo_print_dmat(n, n, &sD, 0, 0); // convert from strmat to column major matrix blasfeo_unpack_dmat(n, n, &sD, 0, 0, D, n); #elif 0 // solve X^T A^T = X^T (P L U)^T = B^T => X^T U^T L^T = B^T P blasfeo_pack_tran_dmat(n, n, I, n, &sI, 0, 0); printf("\nI' = \n"); blasfeo_print_dmat(n, n, &sI, 0, 0); blasfeo_dcolpe(n, ipiv, &sB); printf("\nperm(I') = \n"); blasfeo_print_dmat(n, n, &sB, 0, 0); blasfeo_dtrsm_rltu(n, n, 1.0, &sLU, 0, 0, &sB, 0, 0, &sD, 0, 0); printf("\nperm(inv(L')) = \n"); blasfeo_print_dmat(n, n, &sD, 0, 0); blasfeo_dtrsm_rutn(n, n, 1.0, &sLU, 0, 0, &sD, 0, 0, &sD, 0, 0); printf("\ninv(A') = \n"); blasfeo_print_dmat(n, n, &sD, 0, 0); // convert from strmat to column major matrix blasfeo_unpack_tran_dmat(n, n, &sD, 0, 0, D, n); #else // solve A^T X = (P L U)^T X = U^T L^T P^T X = B blasfeo_dgetr(n, n, &sLU, 0, 0, &sLUt, 0, 0); blasfeo_pack_dmat(n, n, I, n, &sI, 0, 0); printf("\nI = \n"); blasfeo_print_dmat(n, n, &sI, 0, 0); blasfeo_dtrsm_llnn(n, n, 1.0, &sLUt, 0, 0, &sI, 0, 0, &sD, 0, 0); printf("\ninv(U^T) = \n"); blasfeo_print_dmat(n, n, &sD, 0, 0); blasfeo_dtrsm_lunu(n, n, 1.0, &sLUt, 0, 0, &sD, 0, 0, &sD, 0, 0); printf("\n(inv(L^T)*inv(U^T)) = \n"); blasfeo_print_dmat(n, n, &sD, 0, 0); blasfeo_drowpei(n, ipiv, &sD); printf("\nperm(inv(L^T)*inv(U^T)) = \n"); blasfeo_print_dmat(n, n, &sD, 0, 0); // convert from strmat to column major matrix blasfeo_unpack_dmat(n, n, &sD, 0, 0, D, n); #endif // print matrix in column-major format printf("\ninv(A) = \n"); d_print_mat(n, n, D, n); // // free memory // d_free(A); d_free(B); d_free(D); d_free(I); int_free(ipiv); // blasfeo_free_dmat(&sA); // blasfeo_free_dmat(&sB); // blasfeo_free_dmat(&sD); // blasfeo_free_dmat(&sI); v_free_align(memory_strmat); return 0; }
52c6fabc74cedecf0d38e9e876fa4db4ca0b919d
c6759b857e55991fea3ef0b465dbcee53fa38714
/rtos/freeRTOS/vendors/gwt/vega/pmsis/drivers/pad/pad.c
63328b5995e9ecd129ae01008cee6855649e71ba
[ "MIT", "Apache-2.0" ]
permissive
GreenWaves-Technologies/gap_sdk
1b343bba97b7a5ce62a24162bd72eef5cc67e269
3fea306d52ee33f923f2423c5a75d9eb1c07e904
refs/heads/master
2023-09-01T14:38:34.270427
2023-08-10T09:04:44
2023-08-10T09:04:44
133,324,605
145
96
Apache-2.0
2023-08-27T19:03:52
2018-05-14T07:50:29
C
UTF-8
C
false
false
4,512
c
pad.c
/* * Copyright (c) 2019, GreenWaves Technologies, 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: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o Neither the name of GreenWaves Technologies, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #include "pmsis/chips/vega/pad.h" #include "pmsis/drivers/pad.h" #include "pmsis.h" #include "pmsis/implem/hal/hal.h" /******************************************************************************* * Definitions ******************************************************************************/ /******************************************************************************* * Driver data *****************************************************************************/ /******************************************************************************* * Function declaration ******************************************************************************/ #if defined(TRACE_PAD) /* Print pad info. */ void pi_pad_print(); #endif /* TRACE_PAD */ /******************************************************************************* * Internal functions ******************************************************************************/ #if defined(TRACE_PAD) void pi_pad_print() { printf("\nPadfun :\n"); for (uint32_t i=0; i<(uint32_t) ARCHI_PAD_NB_PADFUNC_REG; i+=4) { printf("%x %x %x %x\n", hal_pad_padfunc_get(i + 0), hal_pad_padfunc_get(i + 1), hal_pad_padfunc_get(i + 2), hal_pad_padfunc_get(i + 3)); } printf("Padcfg :\n"); for (uint32_t i=0; i<(uint32_t) ARCHI_PAD_NB_PADCFG_REG; i+=4) { printf("%x %x %x %x\n", hal_pad_padcfg_config_get(i + 0), hal_pad_padcfg_config_get(i + 1), hal_pad_padcfg_config_get(i + 2), hal_pad_padcfg_config_get(i + 3)); } } #endif /* TRACE_PAD */ /******************************************************************************* * API implementation ******************************************************************************/ void pi_pad_set_function(pi_pad_e pad, pi_pad_func_e function) { PAD_TRACE("Setting pad=%d func=%d\n", pad, function); hal_pad_pad_function_set(pad, function); } void pi_pad_init(uint32_t pad_values[]) { for (uint32_t pad_reg = 0; pad_reg < (uint32_t) ARCHI_PAD_NB_PADFUNC_REG; pad_reg++) { PAD_TRACE("Setting padfunc_%d=%lx\n", pad_reg, pad_values[pad_reg]); hal_pad_padfunc_set(pad_reg, pad_values[pad_reg]); } } void pi_pad_set_configuration(pi_pad_e pad, pi_pad_flags_e cfg) { uint8_t pe = (cfg >> PI_PAD_PULL_OFFSET); uint8_t ds = (cfg >> PI_PAD_DRIVE_OFFSET); hal_pad_padcfg_config_set(pad, pe, ds); PAD_TRACE("Pad=%ld, pe=%x, ds=%x\n", (uint32_t) pad, pe, ds); } void pi_pad_sleepcfg_set(uint32_t sleepcfg[], uint8_t sleep_ena) { for (uint32_t pad_reg = 0; pad_reg < (uint32_t) ARCHI_PAD_NB_SLEEPPADCFG_REG; pad_reg++) { PAD_TRACE("Setting pad sleepcfg_%d=%lx\n", pad_reg, sleepcfg[pad_reg]); hal_pad_sleeppadcfg_set(pad_reg, sleepcfg[pad_reg]); } PAD_TRACE("Pad sleep enable=%d\n", sleep_ena); hal_pad_padsleep_enable(sleep_ena); }
0ba7514e730a0b755fbcc730c2aea445658aa124
07bbe7a0a829cfbc9789831d981aedf36e4e94d9
/examples/lexbor/html/tokenizer/tag_attributes.c
065c2368a30db8bd3c0bed23f616570e04acc600
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lexbor/lexbor
0bf3a22898d8e295fa20cc1391e31a68502c458a
31e3d9d7f9032cd475d5afa788999de2d4b891dd
refs/heads/master
2023-08-31T23:25:49.903737
2023-08-30T08:25:12
2023-08-30T08:25:12
122,375,902
758
95
Apache-2.0
2023-08-30T08:25:13
2018-02-21T18:28:52
C
UTF-8
C
false
false
2,966
c
tag_attributes.c
/* * Copyright (C) 2019-2020 Alexander Borisov * * Author: Alexander Borisov <borisov@lexbor.com> */ #include "lexbor/html/tokenizer.h" #include "lexbor/html/token_attr.h" #define FAILED(...) \ do { \ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, "\n"); \ exit(EXIT_FAILURE); \ } \ while (0) static lxb_html_token_t * token_callback(lxb_html_tokenizer_t *tkz, lxb_html_token_t *token, void *ctx) { const lxb_char_t *tag, *name; lxb_html_token_attr_t *attr; attr = token->attr_first; /* Skip all #text or without attributes tokens */ if (token->tag_id == LXB_TAG__TEXT || attr == NULL) { return token; } tag = lxb_tag_name_by_id(lxb_html_tokenizer_tags(tkz), token->tag_id, NULL); if (tag == NULL) { FAILED("Failed to get token name"); } printf("\"%s\" attributes:\n", tag); while (attr != NULL) { name = lxb_html_token_attr_name(attr, NULL); if (name != NULL) { printf(" Name: %s; ", name); } else { /* This can only happen for the DOCTYPE token. */ printf(" Name: <NOT SET>; \n"); } if (attr->value != NULL) { printf("Value: %.*s\n", (int) attr->value_size, attr->value); } else { printf("Value: <NOT SET>\n"); } attr = attr->next; } return token; } int main(int argc, const char *argv[]) { lxb_status_t status; lxb_html_tokenizer_t *tkz; const lxb_char_t data[] = "<div id=one-id class=silent ref='some &copy; a'>" "<option-one enabled>" "<option-two enabled='&#81'>" "</div>"; printf("HTML:\n%s\n\n", (char *) data); printf("Result:\n"); tkz = lxb_html_tokenizer_create(); status = lxb_html_tokenizer_init(tkz); if (status != LXB_STATUS_OK) { FAILED("Failed to create tokenizer object"); } /* Set callback for token */ lxb_html_tokenizer_callback_token_done_set(tkz, token_callback, NULL); status = lxb_html_tokenizer_begin(tkz); if (status != LXB_STATUS_OK) { FAILED("Failed to prepare tokenizer object for parsing"); } status = lxb_html_tokenizer_chunk(tkz, data, (sizeof(data) - 1)); if (status != LXB_STATUS_OK) { FAILED("Failed to parse the html data"); } status = lxb_html_tokenizer_end(tkz); if (status != LXB_STATUS_OK) { FAILED("Failed to ending of parsing the html data"); } lxb_html_tokenizer_destroy(tkz); return 0; }
f4c2696ca967294f2ee604c37b6295c48d10b3c0
07bbe7a0a829cfbc9789831d981aedf36e4e94d9
/source/lexbor/css/state.h
0a2abd80363400420c352a6d070588af83508dae
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lexbor/lexbor
0bf3a22898d8e295fa20cc1391e31a68502c458a
31e3d9d7f9032cd475d5afa788999de2d4b891dd
refs/heads/master
2023-08-31T23:25:49.903737
2023-08-30T08:25:12
2023-08-30T08:25:12
122,375,902
758
95
Apache-2.0
2023-08-30T08:25:13
2018-02-21T18:28:52
C
UTF-8
C
false
false
693
h
state.h
/* * Copyright (C) 2021-2022 Alexander Borisov * * Author: Alexander Borisov <borisov@lexbor.com> */ #ifndef LXB_CSS_STATE_H #define LXB_CSS_STATE_H #ifdef __cplusplus extern "C" { #endif #include "lexbor/css/base.h" LXB_API bool lxb_css_state_success(lxb_css_parser_t *parser, const lxb_css_syntax_token_t *token, void *ctx); LXB_API bool lxb_css_state_failed(lxb_css_parser_t *parser, const lxb_css_syntax_token_t *token, void *ctx); LXB_API bool lxb_css_state_stop(lxb_css_parser_t *parser, const lxb_css_syntax_token_t *token, void *ctx); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* LXB_CSS_STATE_H */
79bf2f5a51a1bd7963e8546b1686d8d5c5146fb1
e814383d36a10839104efaa4df277996ab220fa3
/3rd-party/romio341/mpi-io/fortran/get_extentf.c
42f252cae2128d8f1b4aab65724c20aa1eadd956
[ "mpich2", "BSD-3-Clause-Open-MPI" ]
permissive
open-mpi/ompi
a1d7483ae1d83dd8fd8ae3ee95e832e0a0ee04e3
1edfdb025c4450f694600083ad871cf06c8d45cd
refs/heads/main
2023-09-01T01:30:02.040705
2023-08-29T17:32:18
2023-08-29T17:32:18
24,107,001
2,008
973
NOASSERTION
2023-09-14T20:59:26
2014-09-16T16:08:30
C
UTF-8
C
false
false
4,755
c
get_extentf.c
/* * Copyright (C) by Argonne National Laboratory * See COPYRIGHT in top-level directory */ #include "adio.h" #include "mpio.h" #if defined(MPIO_BUILD_PROFILING) || defined(HAVE_WEAK_SYMBOLS) #if defined(HAVE_WEAK_SYMBOLS) #if defined(HAVE_PRAGMA_WEAK) #if defined(FORTRANCAPS) extern FORTRAN_API void FORT_CALL MPI_FILE_GET_TYPE_EXTENT(MPI_Fint *, MPI_Fint *, MPI_Fint *, MPI_Fint *); #pragma weak MPI_FILE_GET_TYPE_EXTENT = PMPI_FILE_GET_TYPE_EXTENT #elif defined(FORTRANDOUBLEUNDERSCORE) extern FORTRAN_API void FORT_CALL mpi_file_get_type_extent__(MPI_Fint *, MPI_Fint *, MPI_Fint *, MPI_Fint *); #pragma weak mpi_file_get_type_extent__ = pmpi_file_get_type_extent__ #elif !defined(FORTRANUNDERSCORE) extern FORTRAN_API void FORT_CALL mpi_file_get_type_extent(MPI_Fint *, MPI_Fint *, MPI_Fint *, MPI_Fint *); #pragma weak mpi_file_get_type_extent = pmpi_file_get_type_extent #else extern FORTRAN_API void FORT_CALL mpi_file_get_type_extent_(MPI_Fint *, MPI_Fint *, MPI_Fint *, MPI_Fint *); #pragma weak mpi_file_get_type_extent_ = pmpi_file_get_type_extent_ #endif #elif defined(HAVE_PRAGMA_HP_SEC_DEF) #if defined(FORTRANCAPS) #pragma _HP_SECONDARY_DEF PMPI_FILE_GET_TYPE_EXTENT MPI_FILE_GET_TYPE_EXTENT #elif defined(FORTRANDOUBLEUNDERSCORE) #pragma _HP_SECONDARY_DEF pmpi_file_get_type_extent__ mpi_file_get_type_extent__ #elif !defined(FORTRANUNDERSCORE) #pragma _HP_SECONDARY_DEF pmpi_file_get_type_extent mpi_file_get_type_extent #else #pragma _HP_SECONDARY_DEF pmpi_file_get_type_extent_ mpi_file_get_type_extent_ #endif #elif defined(HAVE_PRAGMA_CRI_DUP) #if defined(FORTRANCAPS) #pragma _CRI duplicate MPI_FILE_GET_TYPE_EXTENT as PMPI_FILE_GET_TYPE_EXTENT #elif defined(FORTRANDOUBLEUNDERSCORE) #pragma _CRI duplicate mpi_file_get_type_extent__ as pmpi_file_get_type_extent__ #elif !defined(FORTRANUNDERSCORE) #pragma _CRI duplicate mpi_file_get_type_extent as pmpi_file_get_type_extent #else #pragma _CRI duplicate mpi_file_get_type_extent_ as pmpi_file_get_type_extent_ #endif /* end of weak pragmas */ #endif /* Include mapping from MPI->PMPI */ #include "mpioprof.h" #endif #ifdef FORTRANCAPS #define mpi_file_get_type_extent_ PMPI_FILE_GET_TYPE_EXTENT #elif defined(FORTRANDOUBLEUNDERSCORE) #define mpi_file_get_type_extent_ pmpi_file_get_type_extent__ #elif !defined(FORTRANUNDERSCORE) #if defined(HPUX) || defined(SPPUX) #pragma _HP_SECONDARY_DEF pmpi_file_get_type_extent pmpi_file_get_type_extent_ #endif #define mpi_file_get_type_extent_ pmpi_file_get_type_extent #else #if defined(HPUX) || defined(SPPUX) #pragma _HP_SECONDARY_DEF pmpi_file_get_type_extent_ pmpi_file_get_type_extent #endif #define mpi_file_get_type_extent_ pmpi_file_get_type_extent_ #endif #else #ifdef FORTRANCAPS #define mpi_file_get_type_extent_ MPI_FILE_GET_TYPE_EXTENT #elif defined(FORTRANDOUBLEUNDERSCORE) #define mpi_file_get_type_extent_ mpi_file_get_type_extent__ #elif !defined(FORTRANUNDERSCORE) #if defined(HPUX) || defined(SPPUX) #pragma _HP_SECONDARY_DEF mpi_file_get_type_extent mpi_file_get_type_extent_ #endif #define mpi_file_get_type_extent_ mpi_file_get_type_extent #else #if defined(HPUX) || defined(SPPUX) #pragma _HP_SECONDARY_DEF mpi_file_get_type_extent_ mpi_file_get_type_extent #endif #endif #endif #if defined(MPIHP) /* Prototype to keep compiler happy */ void mpi_file_get_type_extent_(MPI_Fint * fh, MPI_Fint * datatype, MPI_Fint * extent, MPI_Fint * ierr); void mpi_file_get_type_extent_(MPI_Fint * fh, MPI_Fint * datatype, MPI_Fint * extent, MPI_Fint * ierr) { MPI_File fh_c; MPI_Datatype datatype_c; MPI_Aint extent_c; fh_c = MPI_File_f2c(*fh); datatype_c = MPI_Type_f2c(*datatype); *ierr = MPI_File_get_type_extent(fh_c, datatype_c, &extent_c); *(MPI_Aint *) extent = extent_c; /* Have to assume it's really an MPI_Aint? */ } #else /* Prototype to keep compiler happy */ FORTRAN_API void FORT_CALL mpi_file_get_type_extent_(MPI_Fint * fh, MPI_Datatype * datatype, MPI_Fint * extent, MPI_Fint * ierr); FORTRAN_API void FORT_CALL mpi_file_get_type_extent_(MPI_Fint * fh, MPI_Datatype * datatype, MPI_Fint * extent, MPI_Fint * ierr) { MPI_File fh_c; MPI_Aint extent_c; fh_c = MPI_File_f2c(*fh); *ierr = MPI_File_get_type_extent(fh_c, *datatype, &extent_c); *(MPI_Aint *) extent = extent_c; /* Have to assume it's really an MPI_Aint? */ } #endif
da9b86c98f528f376c948fabf88eb06520437e40
9d352d0c8dd440acbcce280e542d3bf7973ccbe6
/c/tskit/stats.c
1c1aeea682f40c7bc670238d24e08f6b4f7c5d67
[ "MIT" ]
permissive
tskit-dev/tskit
3ab0ddadaf369abd9c757dbadd27f95b38ed8ba2
d6c9cf79ea02600d0474a9dc11ec0ae280a75f0b
refs/heads/main
2023-08-31T16:01:28.000908
2023-08-23T13:59:26
2023-08-23T13:59:26
120,805,786
131
68
MIT
2023-09-04T15:58:14
2018-02-08T19:16:31
Python
UTF-8
C
false
false
8,164
c
stats.c
/* * MIT License * * Copyright (c) 2018-2022 Tskit Developers * Copyright (c) 2016-2017 University of Oxford * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <tskit/stats.h> void tsk_ld_calc_print_state(const tsk_ld_calc_t *self, FILE *out) { fprintf(out, "tree = %p\n", (const void *) &self->tree); fprintf(out, "max_sites = %d\n", (int) self->max_sites); fprintf(out, "max_distance = %f\n", self->max_distance); } int TSK_WARN_UNUSED tsk_ld_calc_init(tsk_ld_calc_t *self, const tsk_treeseq_t *tree_sequence) { int ret = 0; tsk_memset(self, 0, sizeof(*self)); ret = tsk_tree_init(&self->tree, tree_sequence, 0); if (ret != 0) { goto out; } self->tree_sequence = tree_sequence; self->total_samples = tsk_treeseq_get_num_samples(self->tree_sequence); self->sample_buffer = tsk_malloc(self->total_samples * sizeof(*self->sample_buffer)); if (self->sample_buffer == NULL) { goto out; } out: return ret; } int tsk_ld_calc_free(tsk_ld_calc_t *self) { tsk_tree_free(&self->tree); tsk_safe_free(self->sample_buffer); return 0; } static int tsk_ld_calc_check_site(tsk_ld_calc_t *TSK_UNUSED(self), const tsk_site_t *site) { int ret = 0; /* These are both limitations in the current implementation, there's no * fundamental reason why we can't support them */ if (site->mutations_length != 1) { ret = TSK_ERR_ONLY_INFINITE_SITES; goto out; } if (site->ancestral_state_length == site->mutations[0].derived_state_length && tsk_memcmp(site->ancestral_state, site->mutations[0].derived_state, site->ancestral_state_length) == 0) { ret = TSK_ERR_SILENT_MUTATIONS_NOT_SUPPORTED; goto out; } out: return ret; } static int tsk_ld_calc_set_focal_samples(tsk_ld_calc_t *self) { int ret = 0; tsk_id_t focal_node = self->focal_site.mutations[0].node; ret = tsk_tree_track_descendant_samples(&self->tree, focal_node); if (ret != 0) { goto out; } self->focal_samples = self->tree.num_tracked_samples[focal_node]; out: return ret; } static int tsk_ld_calc_initialise(tsk_ld_calc_t *self, tsk_id_t a) { int ret = 0; ret = tsk_treeseq_get_site(self->tree_sequence, a, &self->focal_site); if (ret != 0) { goto out; } ret = tsk_ld_calc_check_site(self, &self->focal_site); if (ret != 0) { goto out; } ret = tsk_tree_seek(&self->tree, self->focal_site.position, 0); if (ret != 0) { goto out; } ret = tsk_ld_calc_set_focal_samples(self); if (ret != 0) { goto out; } out: return ret; } static int tsk_ld_calc_compute_r2(tsk_ld_calc_t *self, const tsk_site_t *target_site, double *r2) { const double n = (double) self->total_samples; double f_a, f_b, f_ab, D, denom; tsk_id_t node; int ret = tsk_ld_calc_check_site(self, target_site); if (ret != 0) { goto out; } node = target_site->mutations[0].node; f_a = ((double) self->focal_samples) / n; f_b = ((double) self->tree.num_samples[node]) / n; f_ab = ((double) self->tree.num_tracked_samples[node]) / n; D = f_ab - f_a * f_b; denom = f_a * f_b * (1 - f_a) * (1 - f_b); *r2 = (D * D) / denom; out: return ret; } static int tsk_ld_calc_compute_and_append( tsk_ld_calc_t *self, const tsk_site_t *target_site, bool *ret_done) { int ret = 0; double r2; double distance = fabs(self->focal_site.position - target_site->position); bool done = true; if (distance <= self->max_distance && self->result_length < self->max_sites) { ret = tsk_ld_calc_compute_r2(self, target_site, &r2); if (ret != 0) { goto out; } self->result[self->result_length] = r2; self->result_length++; done = false; } *ret_done = done; out: return ret; } static int tsk_ld_calc_run_forward(tsk_ld_calc_t *self) { int ret = 0; tsk_size_t j; bool done = false; for (j = 0; j < self->tree.sites_length; j++) { if (self->tree.sites[j].id > self->focal_site.id) { ret = tsk_ld_calc_compute_and_append(self, &self->tree.sites[j], &done); if (ret != 0) { goto out; } if (done) { break; } } } while (((ret = tsk_tree_next(&self->tree)) == TSK_TREE_OK) && !done) { for (j = 0; j < self->tree.sites_length; j++) { ret = tsk_ld_calc_compute_and_append(self, &self->tree.sites[j], &done); if (ret != 0) { goto out; } if (done) { break; } } } if (ret < 0) { goto out; } ret = 0; out: return ret; } static int tsk_ld_calc_run_reverse(tsk_ld_calc_t *self) { int ret = 0; tsk_id_t j; bool done = false; for (j = (tsk_id_t) self->tree.sites_length - 1; j >= 0; j--) { if (self->tree.sites[j].id < self->focal_site.id) { ret = tsk_ld_calc_compute_and_append(self, &self->tree.sites[j], &done); if (ret != 0) { goto out; } if (done) { break; } } } while (((ret = tsk_tree_prev(&self->tree)) == TSK_TREE_OK) && !done) { for (j = (tsk_id_t) self->tree.sites_length - 1; j >= 0; j--) { ret = tsk_ld_calc_compute_and_append(self, &self->tree.sites[j], &done); if (ret != 0) { goto out; } if (done) { break; } } } if (ret < 0) { goto out; } ret = 0; out: return ret; } int tsk_ld_calc_get_r2(tsk_ld_calc_t *self, tsk_id_t a, tsk_id_t b, double *r2) { int ret = 0; tsk_site_t target_site; ret = tsk_ld_calc_initialise(self, a); if (ret != 0) { goto out; } ret = tsk_treeseq_get_site(self->tree_sequence, b, &target_site); if (ret != 0) { goto out; } ret = tsk_tree_seek(&self->tree, target_site.position, 0); if (ret != 0) { goto out; } ret = tsk_ld_calc_compute_r2(self, &target_site, r2); if (ret != 0) { goto out; } out: return ret; } int tsk_ld_calc_get_r2_array(tsk_ld_calc_t *self, tsk_id_t a, int direction, tsk_size_t max_sites, double max_distance, double *r2, tsk_size_t *num_r2_values) { int ret = tsk_ld_calc_initialise(self, a); if (ret != 0) { goto out; } self->max_sites = max_sites; self->max_distance = max_distance; self->result_length = 0; self->result = r2; if (direction == TSK_DIR_FORWARD) { ret = tsk_ld_calc_run_forward(self); } else if (direction == TSK_DIR_REVERSE) { ret = tsk_ld_calc_run_reverse(self); } else { ret = TSK_ERR_BAD_PARAM_VALUE; } if (ret != 0) { goto out; } *num_r2_values = self->result_length; out: return ret; }
0df116254a4505ea9ed6d0e5caec515532038114
76f7459a09acb9be2d52407132f5ff8955627da2
/frame/compat/f2c/bla_rotmg.c
11ccc6f3339faa3177b1bb8a6300484b7f63b160
[ "BSD-3-Clause" ]
permissive
flame/blis
448bc0ad139b726188129c5627c304274b41c3c1
6dcf7666eff14348e82fbc2750be4b199321e1b9
refs/heads/master
2023-09-01T14:56:11.920485
2023-08-27T19:18:57
2023-08-27T19:18:57
16,143,904
1,696
361
NOASSERTION
2023-08-27T19:18:58
2014-01-22T15:58:24
C
UTF-8
C
false
false
11,542
c
bla_rotmg.c
/* BLIS An object-based framework for developing high-performance BLAS-like libraries. Copyright (C) 2014, The University of Texas at Austin 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(s) of the copyright holder(s) 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. */ #include "blis.h" #ifdef BLIS_ENABLE_BLAS /* srotmg.f -- translated by f2c (version 19991025). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Subroutine */ int PASTEF77(s,rotmg)(bla_real *sd1, bla_real *sd2, bla_real *sx1, const bla_real *sy1, bla_real *sparam) { /* Initialized data */ static bla_real zero = 0.f; static bla_real one = 1.f; static bla_real two = 2.f; static bla_real gam = 4096.f; static bla_real gamsq = 16777200.f; static bla_real rgamsq = 5.96046e-8f; /* Format strings */ /* System generated locals */ bla_real r__1; /* Local variables */ bla_real sflag, stemp, su, sp1, sp2, sq2, sq1, sh11 = 0.f, sh21 = 0.f, sh12 = 0.f, sh22 = 0.f; bla_integer igo; /* Assigned format variables */ /* CONSTRUCT THE MODIFIED GIVENS TRANSFORMATION MATRIX H WHICH ZEROS */ /* THE SECOND COMPONENT OF THE 2-VECTOR (SQRT(SD1)*SX1,SQRT(SD2)* */ /* SY2)**T. */ /* WITH SPARAM(1)=SFLAG, H HAS ONE OF THE FOLLOWING FORMS.. */ /* SFLAG=-1.E0 SFLAG=0.E0 SFLAG=1.E0 SFLAG=-2.E0 */ /* (SH11 SH12) (1.E0 SH12) (SH11 1.E0) (1.E0 0.E0) */ /* H=( ) ( ) ( ) ( ) */ /* (SH21 SH22), (SH21 1.E0), (-1.E0 SH22), (0.E0 1.E0). */ /* LOCATIONS 2-4 OF SPARAM CONTAIN SH11,SH21,SH12, AND SH22 */ /* RESPECTIVELY. (VALUES OF 1.E0, -1.E0, OR 0.E0 IMPLIED BY THE */ /* VALUE OF SPARAM(1) ARE NOT STORED IN SPARAM.) */ /* THE VALUES OF GAMSQ AND RGAMSQ SET IN THE DATA STATEMENT MAY BE */ /* INEXACT. THIS IS OK AS THEY ARE ONLY USED FOR TESTING THE SIZE */ /* OF SD1 AND SD2. ALL ACTUAL SCALING OF DATA IS DONE USING GAM. */ /* Parameter adjustments */ --sparam; /* Function Body */ if (! (*sd1 < zero)) { goto L10; } /* GO ZERO-H-D-AND-SX1.. */ goto L60; L10: /* CASE-SD1-NONNEGATIVE */ sp2 = *sd2 * *sy1; if (! (sp2 == zero)) { goto L20; } sflag = -two; goto L260; /* REGULAR-CASE.. */ L20: sp1 = *sd1 * *sx1; sq2 = sp2 * *sy1; sq1 = sp1 * *sx1; if (! (bli_fabs(sq1) > bli_fabs(sq2))) { goto L40; } sh21 = -(*sy1) / *sx1; sh12 = sp2 / sp1; su = one - sh12 * sh21; if (! (su <= zero)) { goto L30; } /* GO ZERO-H-D-AND-SX1.. */ goto L60; L30: sflag = zero; *sd1 /= su; *sd2 /= su; *sx1 *= su; /* GO SCALE-CHECK.. */ goto L100; L40: if (! (sq2 < zero)) { goto L50; } /* GO ZERO-H-D-AND-SX1.. */ goto L60; L50: sflag = one; sh11 = sp1 / sp2; sh22 = *sx1 / *sy1; su = one + sh11 * sh22; stemp = *sd2 / su; *sd2 = *sd1 / su; *sd1 = stemp; *sx1 = *sy1 * su; /* GO SCALE-CHECK */ goto L100; /* PROCEDURE..ZERO-H-D-AND-SX1.. */ L60: sflag = -one; sh11 = zero; sh12 = zero; sh21 = zero; sh22 = zero; *sd1 = zero; *sd2 = zero; *sx1 = zero; /* RETURN.. */ goto L220; /* PROCEDURE..FIX-H.. */ L70: if (! (sflag >= zero)) { goto L90; } if (! (sflag == zero)) { goto L80; } sh11 = one; sh22 = one; sflag = -one; goto L90; L80: sh21 = -one; sh12 = one; sflag = -one; L90: switch (igo) { case 0: goto L120; case 1: goto L150; case 2: goto L180; case 3: goto L210; } /* PROCEDURE..SCALE-CHECK */ L100: L110: if (! (*sd1 <= rgamsq)) { goto L130; } if (*sd1 == zero) { goto L160; } igo = 0; /* FIX-H.. */ goto L70; L120: /* Computing 2nd power */ r__1 = gam; *sd1 *= r__1 * r__1; *sx1 /= gam; sh11 /= gam; sh12 /= gam; goto L110; L130: L140: if (! (*sd1 >= gamsq)) { goto L160; } igo = 1; /* FIX-H.. */ goto L70; L150: /* Computing 2nd power */ r__1 = gam; *sd1 /= r__1 * r__1; *sx1 *= gam; sh11 *= gam; sh12 *= gam; goto L140; L160: L170: if (! (bli_fabs(*sd2) <= rgamsq)) { goto L190; } if (*sd2 == zero) { goto L220; } igo = 2; /* FIX-H.. */ goto L70; L180: /* Computing 2nd power */ r__1 = gam; *sd2 *= r__1 * r__1; sh21 /= gam; sh22 /= gam; goto L170; L190: L200: if (! (bli_fabs(*sd2) >= gamsq)) { goto L220; } igo = 3; /* FIX-H.. */ goto L70; L210: /* Computing 2nd power */ r__1 = gam; *sd2 /= r__1 * r__1; sh21 *= gam; sh22 *= gam; goto L200; L220: if (sflag < 0.f) { goto L250; } else if (sflag == 0) { goto L230; } else { goto L240; } L230: sparam[3] = sh21; sparam[4] = sh12; goto L260; L240: sparam[2] = sh11; sparam[5] = sh22; goto L260; L250: sparam[2] = sh11; sparam[3] = sh21; sparam[4] = sh12; sparam[5] = sh22; L260: sparam[1] = sflag; return 0; } /* srotmg_ */ /* drotmg.f -- translated by f2c (version 19991025). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Subroutine */ int PASTEF77(d,rotmg)(bla_double *dd1, bla_double *dd2, bla_double *dx1, const bla_double *dy1, bla_double *dparam) { /* Initialized data */ static bla_double zero = 0.; static bla_double one = 1.; static bla_double two = 2.; static bla_double gam = 4096.; static bla_double gamsq = 16777216.; static bla_double rgamsq = 5.9604645e-8; /* Format strings */ /* System generated locals */ bla_double d__1; /* Local variables */ bla_double dflag, dtemp, du, dp1, dp2, dq2, dq1, dh11 = 0.f, dh21 = 0.f, dh12 = 0.f, dh22 = 0.f; bla_integer igo; /* Assigned format variables */ /* CONSTRUCT THE MODIFIED GIVENS TRANSFORMATION MATRIX H WHICH ZEROS */ /* THE SECOND COMPONENT OF THE 2-VECTOR (DSQRT(DD1)*DX1,DSQRT(DD2)* */ /* DY2)**T. */ /* WITH DPARAM(1)=DFLAG, H HAS ONE OF THE FOLLOWING FORMS.. */ /* DFLAG=-1.D0 DFLAG=0.D0 DFLAG=1.D0 DFLAG=-2.D0 */ /* (DH11 DH12) (1.D0 DH12) (DH11 1.D0) (1.D0 0.D0) */ /* H=( ) ( ) ( ) ( ) */ /* (DH21 DH22), (DH21 1.D0), (-1.D0 DH22), (0.D0 1.D0). */ /* LOCATIONS 2-4 OF DPARAM CONTAIN DH11, DH21, DH12, AND DH22 */ /* RESPECTIVELY. (VALUES OF 1.D0, -1.D0, OR 0.D0 IMPLIED BY THE */ /* VALUE OF DPARAM(1) ARE NOT STORED IN DPARAM.) */ /* THE VALUES OF GAMSQ AND RGAMSQ SET IN THE DATA STATEMENT MAY BE */ /* INEXACT. THIS IS OK AS THEY ARE ONLY USED FOR TESTING THE SIZE */ /* OF DD1 AND DD2. ALL ACTUAL SCALING OF DATA IS DONE USING GAM. */ /* Parameter adjustments */ --dparam; /* Function Body */ if (! (*dd1 < zero)) { goto L10; } /* GO ZERO-H-D-AND-DX1.. */ goto L60; L10: /* CASE-DD1-NONNEGATIVE */ dp2 = *dd2 * *dy1; if (! (dp2 == zero)) { goto L20; } dflag = -two; goto L260; /* REGULAR-CASE.. */ L20: dp1 = *dd1 * *dx1; dq2 = dp2 * *dy1; dq1 = dp1 * *dx1; if (! (bli_fabs(dq1) > bli_fabs(dq2))) { goto L40; } dh21 = -(*dy1) / *dx1; dh12 = dp2 / dp1; du = one - dh12 * dh21; if (! (du <= zero)) { goto L30; } /* GO ZERO-H-D-AND-DX1.. */ goto L60; L30: dflag = zero; *dd1 /= du; *dd2 /= du; *dx1 *= du; /* GO SCALE-CHECK.. */ goto L100; L40: if (! (dq2 < zero)) { goto L50; } /* GO ZERO-H-D-AND-DX1.. */ goto L60; L50: dflag = one; dh11 = dp1 / dp2; dh22 = *dx1 / *dy1; du = one + dh11 * dh22; dtemp = *dd2 / du; *dd2 = *dd1 / du; *dd1 = dtemp; *dx1 = *dy1 * du; /* GO SCALE-CHECK */ goto L100; /* PROCEDURE..ZERO-H-D-AND-DX1.. */ L60: dflag = -one; dh11 = zero; dh12 = zero; dh21 = zero; dh22 = zero; *dd1 = zero; *dd2 = zero; *dx1 = zero; /* RETURN.. */ goto L220; /* PROCEDURE..FIX-H.. */ L70: if (! (dflag >= zero)) { goto L90; } if (! (dflag == zero)) { goto L80; } dh11 = one; dh22 = one; dflag = -one; goto L90; L80: dh21 = -one; dh12 = one; dflag = -one; L90: switch (igo) { case 0: goto L120; case 1: goto L150; case 2: goto L180; case 3: goto L210; } /* PROCEDURE..SCALE-CHECK */ L100: L110: if (! (*dd1 <= rgamsq)) { goto L130; } if (*dd1 == zero) { goto L160; } igo = 0; /* FIX-H.. */ goto L70; L120: /* Computing 2nd power */ d__1 = gam; *dd1 *= d__1 * d__1; *dx1 /= gam; dh11 /= gam; dh12 /= gam; goto L110; L130: L140: if (! (*dd1 >= gamsq)) { goto L160; } igo = 1; /* FIX-H.. */ goto L70; L150: /* Computing 2nd power */ d__1 = gam; *dd1 /= d__1 * d__1; *dx1 *= gam; dh11 *= gam; dh12 *= gam; goto L140; L160: L170: if (! (bli_fabs(*dd2) <= rgamsq)) { goto L190; } if (*dd2 == zero) { goto L220; } igo = 2; /* FIX-H.. */ goto L70; L180: /* Computing 2nd power */ d__1 = gam; *dd2 *= d__1 * d__1; dh21 /= gam; dh22 /= gam; goto L170; L190: L200: if (! (bli_fabs(*dd2) >= gamsq)) { goto L220; } igo = 3; /* FIX-H.. */ goto L70; L210: /* Computing 2nd power */ d__1 = gam; *dd2 /= d__1 * d__1; dh21 *= gam; dh22 *= gam; goto L200; L220: if (dflag < 0.) { goto L250; } else if (dflag == 0) { goto L230; } else { goto L240; } L230: dparam[3] = dh21; dparam[4] = dh12; goto L260; L240: dparam[2] = dh11; dparam[5] = dh22; goto L260; L250: dparam[2] = dh11; dparam[3] = dh21; dparam[4] = dh12; dparam[5] = dh22; L260: dparam[1] = dflag; return 0; } /* drotmg_ */ #endif
09f1de24cd8691468eeda0069a23f95c5a346699
7f6c235b0598353549959c18f69eefd20b766907
/testsuite/Far_Pointer_Call.c
2fdce60b18a522d14bdb5a815097b4fad10b3164
[ "ClArtistic" ]
permissive
z88dk/z88dk
46dfd4905f36d99333173cadd0a660839befc9f0
8b07f37cc43c5d9ffe69b563c80763491d8faff7
refs/heads/master
2023-09-04T19:29:49.254958
2023-09-03T20:51:24
2023-09-03T20:51:24
54,035,569
820
263
NOASSERTION
2023-09-05T11:09:04
2016-03-16T13:48:16
Assembly
UTF-8
C
false
false
183
c
Far_Pointer_Call.c
char *(*__far funcptr)(long val, int id); char *__far(*__far funcptr2)(long val, int id); int func() { return *funcptr(1L, 2); } int func2() { return *funcptr2(1L, 2); }
ea4bbb298fe07a228d542156a891c1c151bc1027
8838eb997879add5759b6dfb23f9a646464e53ca
/src/drivers/net/xen_net/xs_info.h
3919504804284a6be7ff7e8412321d0e438e1815
[ "BSD-2-Clause" ]
permissive
embox/embox
d6aacec876978522f01cdc4b8de37a668c6f4c80
98e3c06e33f3fdac10a29c069c20775568e0a6d1
refs/heads/master
2023-09-04T03:02:20.165042
2023-09-02T14:55:31
2023-09-02T14:55:31
33,078,138
1,087
325
BSD-2-Clause
2023-09-14T16:58:34
2015-03-29T15:27:48
C
UTF-8
C
false
false
447
h
xs_info.h
/** * @file * @brief Shows information from XenStore * * @date * @author */ #ifndef XS_INFO_H_ #define XS_INFO_H_ #define XS_KEY_LEN 256 #define XS_VALUE_LEN 512 #define XS_NAME_LEN 16 #define XS_DOMID_LEN 4 #define XS_LS_N_REC 0 /* List info only about current directory */ #define XS_LS_REC 1 /* List info about current directory * and all its subdirectories */ extern void xenstore_info(); #endif /* XS_INFO_H_ */
79c9b3db52af0872025d906a4410bf56cd6d2d15
b858cbf6411e4dabd088fa65cfe2688c7f11f9ac
/rockchip/mpi_enc_utils.h
f811e1314a833fb8ccf208af2f8e2d0ce5970a39
[]
no_license
MUZLATAN/ffmpeg_rtsp_mpp
d61087a94e485a5429d05de8f11ceef5d5765735
e76a983a75d187bfd51927eed67044a8820b3c44
refs/heads/master
2023-08-29T12:59:34.875878
2021-10-26T07:08:52
2021-10-26T07:08:52
259,519,977
115
41
null
null
null
null
UTF-8
C
false
false
2,069
h
mpi_enc_utils.h
/* * Copyright 2015 Rockchip Electronics Co. LTD * * 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 __MPI_ENC_UTILS_H__ #define __MPI_ENC_UTILS_H__ #include <stdio.h> #include "rk_venc_cmd.h" typedef struct MpiEncTestArgs_t { char *file_input; char *file_output; MppCodingType type; MppFrameFormat format; RK_S32 num_frames; RK_S32 loop_cnt; RK_S32 width; RK_S32 height; RK_S32 hor_stride; RK_S32 ver_stride; RK_S32 bps_target; RK_S32 fps_in_flex; RK_S32 fps_in_num; RK_S32 fps_in_den; RK_S32 fps_out_flex; RK_S32 fps_out_num; RK_S32 fps_out_den; RK_S32 gop_mode; MppEncHeaderMode header_mode; MppEncSliceSplit split; } MpiEncTestArgs; #ifdef __cplusplus extern "C" { #endif MPP_RET mpi_enc_gen_gop_ref(MppEncGopRef *ref, RK_S32 gop_mode); MPP_RET mpi_enc_gen_osd_data(MppEncOSDData *osd_data, MppBuffer osd_buf, RK_U32 frame_cnt); MPP_RET mpi_enc_gen_osd_plt(MppEncOSDPlt *osd_plt, RK_U32 *table); MpiEncTestArgs *mpi_enc_test_cmd_get(void); MPP_RET mpi_enc_test_cmd_update_by_args(MpiEncTestArgs* cmd, int argc, char **argv); MPP_RET mpi_enc_test_cmd_put(MpiEncTestArgs* cmd); MPP_RET mpi_enc_test_cmd_show_opt(MpiEncTestArgs* cmd); void mpi_enc_test_help(void); #ifdef __cplusplus } #endif #endif /*__MPI_ENC_UTILS_H__*/
337f1c325a77d924d3ed4c5429213c2d88a33465
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/powerpc/boot/ep88xc.c
a400f540715541ba550a973febe007e9e0a57712
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
1,249
c
ep88xc.c
/* * Embedded Planet EP88xC with PlanetCore firmware * * Author: Scott Wood <scottwood@freescale.com> * * Copyright (c) 2007 Freescale Semiconductor, Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "ops.h" #include "stdio.h" #include "planetcore.h" #include "mpc8xx.h" static char *table; static u64 mem_size; static void platform_fixups(void) { u64 val; dt_fixup_memory(0, mem_size); planetcore_set_mac_addrs(table); if (!planetcore_get_decimal(table, PLANETCORE_KEY_CRYSTAL_HZ, &val)) { printf("No PlanetCore crystal frequency key.\r\n"); return; } mpc885_fixup_clocks(val); } void platform_init(unsigned long r3, unsigned long r4, unsigned long r5, unsigned long r6, unsigned long r7) { table = (char *)r3; planetcore_prepare_table(table); if (!planetcore_get_decimal(table, PLANETCORE_KEY_MB_RAM, &mem_size)) return; mem_size *= 1024 * 1024; simple_alloc_init(_end, mem_size - (unsigned long)_end, 32, 64); fdt_init(_dtb_start); planetcore_set_stdout_path(table); serial_console_init(); platform_ops.fixups = platform_fixups; }
17cf550eb329c14af85503e19be420c4fd618740
1577e1cf4e89584a125cffb855ca50a9654c6d55
/libdispatch/os/workgroup_object_private.h
ec7ebee712acaa013c1fcfe25caf69b571d8c32d
[ "Apache-2.0" ]
permissive
apple-open-source/macos
a4188b5c2ef113d90281d03cd1b14e5ee52ebffb
2d2b15f13487673de33297e49f00ef94af743a9a
refs/heads/master
2023-08-01T11:03:26.870408
2023-03-27T00:00:00
2023-03-27T00:00:00
180,595,052
124
24
null
2022-12-27T14:54:09
2019-04-10T14:06:23
null
UTF-8
C
false
false
11,848
h
workgroup_object_private.h
#ifndef __OS_WORKGROUP_OBJECT_PRIVATE__ #define __OS_WORKGROUP_OBJECT_PRIVATE__ #ifndef __OS_WORKGROUP_PRIVATE_INDIRECT__ #error "Please #include <os/workgroup.h> instead of this file directly." #include <os/workgroup_base.h> // For header doc #endif #include <os/workgroup_object.h> __BEGIN_DECLS OS_WORKGROUP_ASSUME_NONNULL_BEGIN /* Attribute creation and specification */ /* This is for clients who want to build their own workgroup attribute from * scratch instead of configuring their attributes on top of the default set of * attributes */ #define OS_WORKGROUP_ATTR_INITIALIZER_EMPTY { .sig = _OS_WORKGROUP_ATTR_SIG_EMPTY_INIT } /*! * @enum os_workgroup_attr_flags_t * * @abstract A bitfield of flags describing options for workgroup configuration */ OS_ENUM(os_workgroup_attr_flags, uint32_t, /*! * @const OS_WORKGROUP_ATTR_NONPROPAGATING * * Asynchronous work initiated by threads which are members of a * workgroup with OS_WORKGROUP_ATTR_NONPROPAGATING attribute, will not * automatically be tracked as part of the workgroup. This applies to work * initiated by calls such as dispatch_async() that may propagate other * execution context properties. * * os_workgroups which are propagating by default can opt out this behavior * by specifying the OS_WORKGROUP_ATTR_NONPROPAGATING flag. */ OS_WORKGROUP_ATTR_NONPROPAGATING = (1 << 1), /*! * @const OS_WORKGROUP_ATTR_UNDIFFERENTIATED * * Member threads of a workgroup with the attribute flag * OS_WORKGROUP_ATTR_UNDIFFERENTIATED are tracked and measured together with * other threads in their process by the system for scheduling and * performance control. * * os_workgroups which are tracked separately from other threads in * the process by default, can opt out of it by specifying the * OS_WORKGROUP_ATTR_UNDIFFERENTIATED flag. */ OS_WORKGROUP_ATTR_UNDIFFERENTIATED = (1 << 2) ); /*! * @function os_workgroup_attr_set_flags * * @abstract * Sets the user specified flags in the workgroup attribute. If invalid * attributes are specified, this function will set and return an error. */ API_AVAILABLE(macos(10.16), ios(14.0), tvos(14.0), watchos(7.0)) OS_WORKGROUP_EXPORT OS_WORKGROUP_WARN_RESULT int os_workgroup_attr_set_flags(os_workgroup_attr_t wga, os_workgroup_attr_flags_t flags); /*! * @function os_workgroup_create * * @abstract * Creates an os_workgroup_t with the specified name and attributes. * A newly created os_workgroup_t has no initial member threads - in particular * the creating thread does not join the os_workgroup_t implicitly. * * @param name * A client specified string for labelling the workgroup. This parameter is * optional and can be NULL. * * @param wga * The requested set of os_workgroup_t attributes. NULL is to be specified for * the default set of attributes. A workgroup with default attributes is * propagating with asynchronous work and differentiated from other threads in * the process (see os_workgroup_attr_flags_t). * * The attribute flag OS_WORKGROUP_ATTR_NONPROPAGATING MUST currently be * specified. If it isn't or if invalid attributes are specified, this function * will return NULL and set an errno. */ API_AVAILABLE(macos(10.16), ios(14.0), tvos(14.0), watchos(7.0)) OS_WORKGROUP_EXPORT OS_WORKGROUP_RETURNS_RETAINED os_workgroup_t _Nullable os_workgroup_create(const char * _Nullable name, os_workgroup_attr_t _Nullable wga); /*! * @function os_workgroup_create_with_workload_id * * @abstract * Creates an os_workgroup_t with the specified name and workload identifier. * * The newly created os_workgroup_t has no initial member threads - in * particular the creating thread does not join the os_workgroup_t implicitly. * * @param name * A client specified string for labelling the workgroup. This parameter is * optional and can be NULL. * * @param workload_id * A system-defined workload identifier string determining the configuration * parameters to apply to the workgroup and its member threads. * Must not be NULL. * See discussion for the detailed rules used to combine the information * specified by the `workload_id` and `wga` arguments. * * @param wga * The requested set of os_workgroup_t attributes. NULL is to be specified for * the default set of attributes. By default, a workgroup created with workload * identifier is nonpropagating with asynchronous work and differentiated from * other threads in the process (see os_workgroup_attr_flags_t). * Currently NULL or the default set of attributes are the only valid * attributes for this function. * See discussion for the detailed rules used to combine the information * specified by the `workload_id` and `wga` arguments. * * @discussion * Rules used for resolution of configuration parameters potentially specified * by both workload identifier and attributes, applied in order: * - If the provided attributes are NULL or equal to the default set of * attributes, no parameters are considered to be explicitly specified via * attribute. * - If the provided workload identifier is known, and the provided attributes * explicitly specify a parameter that is also configured by the identifier, * the two parameter values must match or this function will fail and return * an error. * - If the provided workload identifier is known, the parameters configured by * the identifier will be used. * - If the provided workload identifier is unknown, the parameters specified * via the provided attributes will be used as a fallback. * - If a given parameter is neither configured by a known workload identifier * or explicitly specified via an attribute, a system-dependent fallback * value will be used. * * @result * The newly created workgroup object, or NULL if invalid arguments were * specified (in which case errno is also set). */ SPI_AVAILABLE(macos(12.0), ios(15.0), tvos(15.0), watchos(8.0)) OS_WORKGROUP_EXPORT OS_WORKGROUP_RETURNS_RETAINED os_workgroup_t _Nullable os_workgroup_create_with_workload_id(const char * _Nullable name, const char *workload_id, os_workgroup_attr_t _Nullable wga); /*! * @function os_workgroup_create_with_workload_id_and_port * * @abstract * Create an os_workgroup_t object with the specified name and workload * identifier from a send right returned by a previous call to * os_workgroup_copy_port, potentially in a different process. * * The newly created os_workgroup_t has no initial member threads - in * particular the creating thread does not join the os_workgroup_t implicitly. * * @param name * A client specified string for labelling the workgroup. This parameter is * optional and can be NULL. * * @param workload_id * A system-defined workload identifier string determining the configuration * parameters to apply to the workgroup and its member threads. * Must not be NULL. * See discussion for the detailed rules used to combine the information * specified by the `workload_id` and `mach_port` arguments. * * @param mach_port * The send right to create the workgroup from. No reference is consumed * on the specified send right. * See discussion for the detailed rules used to combine the information * specified by the `workload_id` and `mach_port` arguments. * * @discussion * Rules used for resolution of configuration parameters potentially specified * by both workload identifier and send right, applied in order: * - If the provided workload identifier is known, and the provided send right * references a workgroup that was created with a parameter that is also * configured by the identifier, the parameter value configured by the * identifier will be used. For certain parameters such as the kernel * work_interval type underlying a workgroup interval type, it is required * that the two parameter values must match, or this function will fail and * return an error. * - If the provided workload identifier is known, the parameters configured by * the identifier will be used. * - If the provided workload identifier is unknown, the parameters used to * create the workgroup referenced by the provided send right are used. * - If a given parameter is neither configured by a known workload identifier * or was used to create the workgroup referenced by the provided send right, * a system-dependent fallback value will be used. * * @result * The newly created workgroup object, or NULL if invalid arguments were * specified (in which case errno is also set). */ SPI_AVAILABLE(macos(12.0), ios(15.0), tvos(15.0), watchos(8.0)) OS_WORKGROUP_EXPORT OS_WORKGROUP_RETURNS_RETAINED os_workgroup_t _Nullable os_workgroup_create_with_workload_id_and_port(const char * _Nullable name, const char *workload_id, mach_port_t mach_port); /*! * @function os_workgroup_create_with_workload_id_and_workgroup * * @abstract * Create a new os_workgroup object with the specified name and workload * identifier from an existing os_workgroup. * * The newly created os_workgroup_t has no initial member threads - in * particular the creating thread does not join the os_workgroup_t implicitly. * * @param name * A client specified string for labelling the workgroup. This parameter is * optional and can be NULL. * * @param workload_id * A system-defined workload identifier string determining the configuration * parameters to apply to the workgroup and its member threads. * Must not be NULL. * See discussion for the detailed rules used to combine the information * specified by the `workload_id` and `wg` arguments. * * @param wg * The existing workgroup to create a new workgroup object from. * See discussion for the detailed rules used to combine the information * specified by the `workload_id` and `wg` arguments. * * @discussion * Rules used for resolution of configuration parameters potentially specified * by both workload identifier and existing workgroup, applied in order: * - If the provided workload identifier is known, and the provided workgroup * was created with a parameter that is also configured by the identifier, * the parameter value configured by the identifier will be used. For certain * parameters such as the kernel work_interval type underlying a workgroup * interval type, it is required that the two parameter values must match, or * this function will fail and return an error. * - If the provided workload identifier is known, the parameters configured by * the identifier will be used. * - If the provided workload identifier is unknown, the parameters used to * create the provided workgroup will be used. * - If a given parameter is neither configured by a known workload identifier * or was used to create the provided workgroup, a system-dependent fallback * value will be used. * * @result * The newly created workgroup object, or NULL if invalid arguments were * specified (in which case errno is also set). */ SPI_AVAILABLE(macos(12.0), ios(15.0), tvos(15.0), watchos(8.0)) OS_WORKGROUP_EXPORT OS_WORKGROUP_RETURNS_RETAINED os_workgroup_t _Nullable os_workgroup_create_with_workload_id_and_workgroup(const char * _Nullable name, const char *workload_id, os_workgroup_t wg); /* To be deprecated once coreaudio adopts */ #define OS_WORKGROUP_ATTR_INITIALIZER OS_WORKGROUP_ATTR_INITIALIZER_DEFAULT typedef uint32_t os_workgroup_index; /* Deprecated in favor of os_workgroup_join */ OS_WORKGROUP_EXPORT OS_WORKGROUP_WARN_RESULT int os_workgroup_join_self(os_workgroup_t wg, os_workgroup_join_token_t token_out, os_workgroup_index *_Nullable id_out); /* Deprecated in favor of os_workgroup_leave */ OS_WORKGROUP_EXPORT void os_workgroup_leave_self(os_workgroup_t wg, os_workgroup_join_token_t token); OS_WORKGROUP_ASSUME_NONNULL_END __END_DECLS #endif /* __OS_WORKGROUP_OBJECT__ */