content
stringlengths
12
2.72M
// // TableViewController_Movie.h // demo_Movie // // Created by <NAME> on 2019/1/8. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import "ViewController.h" #import "Movie_Data.h" NS_ASSUME_NONNULL_BEGIN @interface TableViewController_Movie : UITableViewController { NSMutableArray<Movie_Data *> *arrayMoviedataPastMovies; } -(void)refreshView:(UIRefreshControl *)refresh; @end NS_ASSUME_NONNULL_END
#ifndef LISTEN_H #define LISTEN_H nframes_t acoustic_delay = SAMPLE_RATE / 470; void show_lag(nframes_t lag) { uint16_t width; uint16_t height = ARCADA_TFT_HEIGHT / 2; uint16_t x = ARCADA_TFT_WIDTH / 2; uint16_t y = (ARCADA_TFT_HEIGHT - height) / 2; arcada.display->fillScreen(ARCADA_YELLOW); arcada.display->drawFastVLine(x, y, ARCADA_TFT_HEIGHT / 2, ARCADA_BLACK); if (lag > 0) { width = (x * lag) / half_interval; arcada.display->fillRect(x + 1, y, width, height, ARCADA_RED); } else if (lag < 0) { width = (x * (lag * -1)) / half_interval; arcada.display->fillRect(x - width, y, width, height, ARCADA_RED); } } void listen(bool *first_run) { static nframes_t last_onset = note_onset; static bool light_on = false; static nframes_t light_off_time = frames; static bool metronome_was_playing = metronome_playing; if (!metronome_playing && metronome_was_playing) *first_run = true; metronome_was_playing = metronome_playing; if (light_on && frames > light_off_time) { analogWrite(13, 0); light_on = false; } if (note_onset != last_onset) { last_onset = note_onset; analogWrite(13, 128); light_on = true; light_off_time = frames + SAMPLE_RATE / 10; if (metronome_playing) { keep_screen_on(); nframes_t offset = (last_onset - ticks[0]) - acoustic_delay; if (offset > half_interval) offset -= interval; show_lag(offset); } } } bool calibrating = false; void calibrate_menu() { stop_metronome(); arcada.display->fillScreen(ARCADA_BLACK); arcada.display->setFont(mini_font); const char *menu_items[] = {"Cancel", "Calibrate"}; switch (arcada.menu(menu_items, 2, ARCADA_BLUE, ARCADA_WHITE, true)) { case 1: calibrating = true; start_metronome(); break; default: break; } } void calibrate(bool *first_run, bool *update) { static nframes_t last_onset = note_onset; static bool light_on = false; static nframes_t light_off_time = frames; static bool was_calibrating = calibrating; static nframes_t sum; static nframes_t count; static bool metronome_was_playing = metronome_playing; if (!metronome_playing && metronome_was_playing) *first_run = true; metronome_was_playing = metronome_playing; if (calibrating && !was_calibrating) { sum = 0; count = 0; } was_calibrating = calibrating; if (light_on && frames > light_off_time) { analogWrite(13, 0); light_on = false; } if (note_onset != last_onset) { last_onset = note_onset; analogWrite(13, 128); light_on = true; light_off_time = frames + SAMPLE_RATE / 10; if (calibrating) { if (metronome_playing) { keep_screen_on(); nframes_t offset = last_onset - ticks[0]; if (offset > half_interval) offset -= interval; if (offset > -500 && offset < 500) { // discard outliers sum += offset; count++; acoustic_delay = sum / count; show_lag((offset - acoustic_delay) * 4); *update = true; } } else { calibrating = false; } } else if (metronome_playing) { keep_screen_on(); nframes_t offset = (last_onset - ticks[0]) - acoustic_delay; if (offset > half_interval) offset -= interval; show_lag(offset); } } } #endif
<gh_stars>10-100 /* Generated by RuntimeBrowser Image: /System/Library/Frameworks/QuartzCore.framework/QuartzCore */ @interface CAEAGLLayer : CALayer <EAGLDrawable> { struct _CAEAGLNativeWindow { struct _EAGLNativeWindowObject { int x_1_1_1; unsigned int x_1_1_2; int (*x_1_1_3)(); int (*x_1_1_4)(); int (*x_1_1_5)(); int (*x_1_1_6)(); int (*x_1_1_7)(); int (*x_1_1_8)(); int (*x_1_1_9)(); } x1; void *x2; int (*x3)(); int (*x4)(); int (*x5)(); int (*x6)(); struct x_list_struct {} *x7; unsigned int x8; unsigned long long x9; struct Atomic { struct { int x_1_2_1; } x_10_1_1; } x10; struct Atomic { struct { int x_1_2_1; } x_11_1_1; } x11; struct SpinLock { struct { int x_1_2_1; } x_12_1_1; } x12; struct _CAImageQueue {} *x13; id x14; struct x_list_struct {} x15; unsigned int x16; struct CAEAGLBuffer {} *x17; struct CAEAGLBuffer {} *x18; unsigned int x19; unsigned int x20; unsigned int x21; struct CAEAGLBuffer {} *x22; id x23; /* Warning: Unrecognized filer type: 't' using 'void*' */ void*x24; out void*x25; int x26; BOOL x27; void*x28; struct { int x_29_1_1; } x29; } * _win; } @property (getter=isAsynchronous) bool asynchronous; @property (copy) NSDictionary *drawableProperties; @property bool lowLatency; @property (readonly) struct _EAGLNativeWindowObject { int x1; unsigned int x2; int (*x3)(); int (*x4)(); int (*x5)(); int (*x6)(); int (*x7)(); int (*x8)(); int (*x9)(); }*nativeWindow; @property bool presentsWithTransaction; + (bool)CA_automaticallyNotifiesObservers:(Class)arg1; + (id)defaultValueForKey:(id)arg1; - (bool)_defersDidBecomeVisiblePostCommit; - (void)_didCommitLayer:(struct Transaction { struct Shared {} *x1; int x2; struct HashTable<CA::Layer *, unsigned int *> {} *x3; struct SpinLock {} *x4; unsigned int x5; struct Level {} *x6; struct List<void (^)()> {} *x7; struct Command {} *x8; struct Deleted {} *x9; struct List<const void *> {} *x10; struct Context {} *x11; struct HashTable<CA::Layer *, CA::Layer *> {} *x12; struct __CFRunLoop {} *x13; struct __CFRunLoopObserver {} *x14; struct LayoutList {} *x15; struct List<CA::Layer *> {} *x16; struct Atomic { struct { int x_1_2_1; } x_17_1_1; } x17; unsigned int x18 : 1; unsigned int x19 : 1; unsigned int x20 : 1; unsigned int x21 : 1; unsigned int x22 : 1; }*)arg1; - (void)_display; - (void)dealloc; - (void)didChangeValueForKey:(id)arg1; - (void)discardContents; - (id)drawableProperties; - (bool)isAsynchronous; - (void)layerDidBecomeVisible:(bool)arg1; - (bool)lowLatency; - (struct _EAGLNativeWindowObject { int x1; unsigned int x2; int (*x3)(); int (*x4)(); int (*x5)(); int (*x6)(); int (*x7)(); int (*x8)(); int (*x9)(); }*)nativeWindow; - (bool)presentsWithTransaction; - (void)setAsynchronous:(bool)arg1; - (void)setDrawableProperties:(id)arg1; - (void)setLowLatency:(bool)arg1; - (void)setPresentsWithTransaction:(bool)arg1; - (bool)shouldArchiveValueForKey:(id)arg1; @end
/* { dg-do run } */ /* { dg-options "-O -fno-tree-loop-optimize -fno-tree-ter -static" } */ unsigned int in[8 * 8] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63 }; unsigned char out[8 * 8]; int main (void) { int i; for (i = 0; i < 8 * 4; i++) { out[i * 2] = (unsigned char) in[i * 2] + 1; out[i * 2 + 1] = (unsigned char) in[i * 2 + 1] + 2; } __asm__("":::"memory"); for (i = 0; i < 8 * 4; i++) { if (out[i * 2] != in[i * 2] + 1 || out[i * 2 + 1] != in[i * 2 + 1] + 2) __builtin_abort (); } return 0; }
// Copyright (c) 2015 Recruit Marketing Partners Co.,Ltd. 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, 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. #import <UIKit/UIKit.h> @class RMPZoomTransitionAnimator; /** You need to adopt the RMPZoomTransitionAnimating protocol in source view controller and destination view controller to make transition animations. The animator get the image position from a view controller implemented this protocol. */ @protocol RMPZoomTransitionAnimating <NSObject> @required /** Before the animation occurs, return the UIImageView of transition source view controller. You should create a new UIImageView object again, so this UIImageView is moving. @return source view controller's UIImageView before transition. */ - (UIImageView *)transitionSourceImageView:(BOOL)goingForward; /** Return background color in source view controller. This color will be used for fade in animation. we recommend the background color of source view controller. @return source view controller's bacground color */ - (UIColor *)transitionSourceBackgroundColor:(BOOL)goingForward; /** Returns the UIImageView’s rectangle in a destination view controller. @return destination view controller's frame for UIImageView */ - (CGRect)transitionDestinationImageViewFrame:(BOOL)goingForward; @end /** Delegate handler of viewController which implements transitioning protocol */ @protocol RMPZoomTransitionDelegate <NSObject> @optional /** Notify the end of the forward and backward animations. get the original UIImageView and hide it, while the copy is being animated. And when the animation is done, the original could be shown. That will prevent the original views to be shown while animating. */ - (void)zoomTransitionAnimator:(RMPZoomTransitionAnimator *)animator didCompleteTransition:(BOOL)didComplete animatingSourceImageView:(UIImageView *)imageView; @end /** Animator object that implements UIViewControllerAnimatedTransitioning You need to return this object in transition delegate method */ @interface RMPZoomTransitionAnimator : NSObject <UIViewControllerAnimatedTransitioning> /** A Boolean value that determines whether transition animation is going forward. */ @property (nonatomic) BOOL goingForward; /** The animator's delegate for transition in source view controller. You need to set this property and implement the RMPZoomTransitionAnimating in source view controller. */ @property (nonatomic, weak) id <RMPZoomTransitionAnimating, RMPZoomTransitionDelegate> sourceTransition; /** The animator's delegate for transition in destination view controller. You need to set this property and implement the RMPZoomTransitionAnimating in destination view controller. */ @property (nonatomic, weak) id <RMPZoomTransitionAnimating, RMPZoomTransitionDelegate> destinationTransition; @end
#include "common.h" #include "comm_helper.h" #include "receiver.h" int receiver_init(struct tester_params *data) { return comm_helper_init(data); } int receiver_main(struct tester_params *data) { while(!data->exit_program) { if(comm_helper_recv(data)) return 1; if(comm_helper_send(data)) return 1; if(comm_helper_close_client(data)) return 1; } return 0; } void receiver_cleanup(struct tester_params *data) { comm_helper_cleanup(data); }
#include "seal_sciEStringToDouble_C.h" #include <string.h> #include <math.h> static bool g_error = false, g_printErrorsToSet = false; static FILE *g_printErrorsTo = NULL; static int f_int( const char * const p_string, const size_t p_begin, const size_t p_end, const char * const p_part ) { size_t i = p_end; int multiplier = 1, result = 0; for( ; i > p_begin; i --, multiplier *= 10 ) if(( p_string[ i - 1 ] >= '0' ) && ( p_string[ i - 1 ] <= '9' )) result += (( p_string[ i - 1 ] - '0' ) * multiplier ); else { if( g_printErrorsTo != NULL ) fprintf( g_printErrorsTo, "f_seal_SciEStringToDouble_C - %s contains a non-numerical character ('%c').\n", p_part, p_string[ i - 1 ] ); g_error = true; return 0; } return result; } static double f_double( const char * const p_string, size_t p_begin, const size_t p_end, const char * const p_part ) { const bool has_sign = ( p_string[ p_begin ] == '+' ) || ( p_string[ p_begin ] == '-' ); size_t i; bool has_point = false; size_t point_i = p_end; int i_part; double result = 0; const bool negative = p_string[ p_begin ] == '-'; if( has_sign ) { p_begin ++; if( p_begin == p_end ) { if( g_printErrorsTo != NULL ) fprintf( g_printErrorsTo, "f_seal_SciEStringToDouble_C - %s contains only a sign character ('%c').\n", p_part, p_string[ p_begin - 1 ] ); g_error = true; return 0; } } for( i = p_begin; i < p_end; i ++ ) if( p_string[ i ] == '.' ) { has_point = true; point_i = i; break; } if( has_sign && has_point && ( p_end - p_begin == 1 )) { if( g_printErrorsTo != NULL ) fprintf( g_printErrorsTo, "f_seal_SciEStringToDouble_C - %s contains no non-sign, non-decimal point characters.\n", p_part ); g_error = true; return 0; } if( has_point && ( p_end - p_begin == 1 )) { if( g_printErrorsTo != NULL ) fprintf( g_printErrorsTo, "f_seal_SciEStringToDouble_C - %s contains only a decimal point.\n", p_part ); g_error = true; return 0; } i_part = f_int( p_string, p_begin, point_i, p_part ); if( g_error ) return 0; if( has_point ) { int f_part = f_int( p_string, point_i + 1, p_end, p_part ); size_t l; if( g_error ) return 0; l = p_end - point_i; l --; result += f_part; if( l != 0 ) result /= pow( 10, l ); } result += i_part; if( negative ) result = -result; return result; } double f_seal_SciEStringToDouble_C( const char * const p ) { size_t e_i = 0; bool has_e = false, exponent_has_sign, negative_exponent; int exponent; double coefficient; g_error = false; if( !g_printErrorsToSet ) { g_printErrorsToSet = true; g_printErrorsTo = stderr; } if( p == NULL ) { if( g_printErrorsTo != NULL ) fprintf( g_printErrorsTo, "f_seal_SciEStringToDouble_C - p == NULL.\n" ); g_error = true; return 0; } if( strlen( p ) == 0 ) { if( g_printErrorsTo != NULL ) fprintf( g_printErrorsTo, "f_seal_SciEStringToDouble_C - strlen( p ) == 0.\n" ); g_error = true; return 0; } if(( strlen( p ) == 1 ) && (( p[ 0 ] == 'e' ) || ( p[ 0 ] == 'E' ))) { if( g_printErrorsTo != NULL ) fprintf( g_printErrorsTo, "f_seal_SciEStringToDouble_C - p contains only the '%c' character.\n", p[ 0 ] ); g_error = true; return 0; } for( ; e_i < strlen( p ); e_i ++ ) if(( p[ e_i ] == 'e' ) || ( p[ e_i ] == 'E' )) { has_e = true; break; } if( !has_e ) return f_double( p, 0, strlen( p ), "p" ); if( e_i == 0 ) { if( g_printErrorsTo != NULL ) fprintf( g_printErrorsTo, "f_seal_SciEStringToDouble_C - p contains an exponent but no coefficient.\n" ); g_error = true; return 0; } if( e_i == strlen( p ) - 1 ) { if( g_printErrorsTo != NULL ) fprintf( g_printErrorsTo, "f_seal_SciEStringToDouble_C - p contains a coefficient but no exponent.\n" ); g_error = true; return 0; } exponent_has_sign = ( p[ e_i + 1 ] == '+' ) || ( p[ e_i + 1 ] == '-' ); negative_exponent = p[ e_i + 1 ] == '-'; if( exponent_has_sign && ( e_i + 2 == strlen( p ))) { if( g_printErrorsTo != NULL ) fprintf( g_printErrorsTo, "f_seal_SciEStringToDouble_C - the exponent contains only a sign character ('%c').\n", p[ e_i + 1 ] ); g_error = true; return 0; } exponent = f_int( p, e_i + 1 + (( exponent_has_sign )?1:0 ), strlen( p ), "the exponent" ); if( g_error ) return 0; if( negative_exponent ) exponent = -exponent; coefficient = f_double( p, 0, e_i, "the coefficient" ); if( g_error ) return 0; return coefficient * pow( 10, exponent ); } bool f_seal_SciEStringToDouble_Error_C( void ) { return g_error; } void p_seal_SciEStringToDouble_PrintErrorsTo_C( FILE *p ) { g_printErrorsToSet = true; g_printErrorsTo = p; }
<gh_stars>1-10 #ifndef TIMESTAMP__H #define TIMESTAMP__H #include "rtc.h" //mcg #include "globals.h" #include "stm32f10x.h" //mcg #include <stdbool.h> //mcg enum TimeFormat { TF_HUMAN_SHORT, // ex. 09/07/10-14:36:22.122044 TF_ASCII_UNIX, // ex. 1247028947.122044 TF_ASCII_EXCEL, // # days . frac days since 1900 }; typedef enum TimeFormat TimeFormat; enum TimePrecision { TP_UNKNOWN = 0x00, TP_DATE = 0x01, TP_SECONDS = 0x03, TP_MILLISECONDS = 0x07, TP_MICROSECONDS = 0x0F }; typedef enum TimePrecision TimePrecision; uint16_t format_rtc_time(char * buf, uint16_t buf_size, rtc_time * time, TimeFormat fmt, TimePrecision prec); void display_time(rtc_time * time); void display_cur_time(void); #endif
<reponame>dimomite/brbuttonsystem<gh_stars>0 /* * btctrl.c * * Created on: Aug 22, 2019 * Author: DiMomite */ #include "btctrl.h" #include "main.h" // TODO remove from this file to platform abstraction #include "lcdctrl.h" // TODO remove #include "entertainmentctrl.h" // TODO remove extern LcdCtrl mainLcdCtrl; // TODO remove extern EntertainmentCtrl entCtrl; // TODO remove extern UART_HandleTypeDef huart2; static uint8_t receivingBuffer[1]; void BT_Init(BtCtrl* btctrl) { if (!btctrl) return; btctrl->state = BT_STATE_UNDEFINED; } void BT_EnableBt(BtCtrl* btctrl) { if (!btctrl) return; if (BT_STATE_ENABLED == btctrl->state) return; btctrl->state = BT_STATE_ENABLED; HAL_GPIO_WritePin(BT_POWER_GPIO_Port, BT_POWER_Pin, GPIO_PIN_RESET); HAL_Delay(100); HAL_UART_Receive_IT(&huart2, receivingBuffer, 1); } void BT_DisableBt(BtCtrl* btctrl) { if (!btctrl) return; if (btctrl->state != BT_STATE_ENABLED) return; // further action make sense only for previously enabled controller HAL_GPIO_WritePin(BT_POWER_GPIO_Port, BT_POWER_Pin, GPIO_PIN_SET); HAL_UART_AbortReceive_IT(&huart2); } void BT_SendByte(BtCtrl* btctrl, uint8_t data) { if (!btctrl) return; if (btctrl->state != BT_STATE_ENABLED) return; HAL_UART_Transmit(&huart2, &data, 1, 10); } void BT_SendData(BtCtrl* btctrl, uint8_t* data, const uint16_t size) { if (!btctrl) return; if (!data || !size) return; if (btctrl->state != BT_STATE_ENABLED) return; HAL_UART_Transmit(&huart2, data, size, 10); } void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if (huart != &huart2) return; // not to us uint8_t shift = receivingBuffer[0]; if (0 == shift) { ENT_StartLedOff(&entCtrl); } else { if (shift > 16) shift = 16; uint16_t brightness = 1 << (shift - 1); ENT_StartLedOn(&entCtrl, brightness); } // would be nice to check that controller in "enabled" state, but I don't have access to it here HAL_UART_Receive_IT(&huart2, receivingBuffer, 1); }
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #pragma once #include "MedusaCorePreDeclares.h" MEDUSA_BEGIN; namespace Compile { template <typename THead,typename...Types> struct Typelist //[IGNORE_PRE_DECLARE] { typedef THead Head; typedef Typelist<Types...> Tail; constexpr static size_t Length = 1 + Tail::Length; }; template <typename THead> struct Typelist<THead>//[IGNORE_PRE_DECLARE] { typedef THead Head; typedef void Tail; constexpr static size_t Length = 1; }; template <> struct Typelist<void>//[IGNORE_PRE_DECLARE] { typedef void Head; typedef void Tail; constexpr static size_t Length = 0; }; } MEDUSA_END;
<reponame>afeng11/tomato-arm<gh_stars>10-100 /* * cxgb3i_ddp.h: Chelsio S3xx iSCSI DDP Manager. * * Copyright (c) 2008 Chelsio Communications, 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. * * Written by: <NAME> (<EMAIL>) */ #ifndef __CXGB3I_ULP2_DDP_H__ #define __CXGB3I_ULP2_DDP_H__ #include <linux/slab.h> #include <linux/vmalloc.h> /** * struct cxgb3i_tag_format - cxgb3i ulp tag format for an iscsi entity * * @sw_bits: # of bits used by iscsi software layer * @rsvd_bits: # of bits used by h/w * @rsvd_shift: h/w bits shift left * @rsvd_mask: reserved bit mask */ struct cxgb3i_tag_format { unsigned char sw_bits; unsigned char rsvd_bits; unsigned char rsvd_shift; unsigned char filler[1]; u32 rsvd_mask; }; /** * struct cxgb3i_gather_list - cxgb3i direct data placement memory * * @tag: ddp tag * @length: total data buffer length * @offset: initial offset to the 1st page * @nelem: # of pages * @pages: page pointers * @phys_addr: physical address */ struct cxgb3i_gather_list { u32 tag; unsigned int length; unsigned int offset; unsigned int nelem; struct page **pages; dma_addr_t phys_addr[0]; }; /** * struct cxgb3i_ddp_info - cxgb3i direct data placement for pdu payload * * @list: list head to link elements * @refcnt: ref. count * @tdev: pointer to t3cdev used by cxgb3 driver * @max_txsz: max tx packet size for ddp * @max_rxsz: max rx packet size for ddp * @llimit: lower bound of the page pod memory * @ulimit: upper bound of the page pod memory * @nppods: # of page pod entries * @idx_last: page pod entry last used * @idx_bits: # of bits the pagepod index would take * @idx_mask: pagepod index mask * @rsvd_tag_mask: tag mask * @map_lock: lock to synchonize access to the page pod map * @gl_map: ddp memory gather list * @gl_skb: skb used to program the pagepod */ struct cxgb3i_ddp_info { struct list_head list; struct kref refcnt; struct t3cdev *tdev; struct pci_dev *pdev; unsigned int max_txsz; unsigned int max_rxsz; unsigned int llimit; unsigned int ulimit; unsigned int nppods; unsigned int idx_last; unsigned char idx_bits; unsigned char filler[3]; u32 idx_mask; u32 rsvd_tag_mask; spinlock_t map_lock; struct cxgb3i_gather_list **gl_map; struct sk_buff **gl_skb; }; #define ISCSI_PDU_NONPAYLOAD_LEN 312 /* bhs(48) + ahs(256) + digest(8) */ #define ULP2_MAX_PKT_SIZE 16224 #define ULP2_MAX_PDU_PAYLOAD (ULP2_MAX_PKT_SIZE - ISCSI_PDU_NONPAYLOAD_LEN) #define PPOD_PAGES_MAX 4 #define PPOD_PAGES_SHIFT 2 /* 4 pages per pod */ /* * struct pagepod_hdr, pagepod - pagepod format */ struct pagepod_hdr { u32 vld_tid; u32 pgsz_tag_clr; u32 maxoffset; u32 pgoffset; u64 rsvd; }; struct pagepod { struct pagepod_hdr hdr; u64 addr[PPOD_PAGES_MAX + 1]; }; #define PPOD_SIZE sizeof(struct pagepod) /* 64 */ #define PPOD_SIZE_SHIFT 6 #define PPOD_COLOR_SHIFT 0 #define PPOD_COLOR_SIZE 6 #define PPOD_COLOR_MASK ((1 << PPOD_COLOR_SIZE) - 1) #define PPOD_IDX_SHIFT PPOD_COLOR_SIZE #define PPOD_IDX_MAX_SIZE 24 #define S_PPOD_TID 0 #define M_PPOD_TID 0xFFFFFF #define V_PPOD_TID(x) ((x) << S_PPOD_TID) #define S_PPOD_VALID 24 #define V_PPOD_VALID(x) ((x) << S_PPOD_VALID) #define F_PPOD_VALID V_PPOD_VALID(1U) #define S_PPOD_COLOR 0 #define M_PPOD_COLOR 0x3F #define V_PPOD_COLOR(x) ((x) << S_PPOD_COLOR) #define S_PPOD_TAG 6 #define M_PPOD_TAG 0xFFFFFF #define V_PPOD_TAG(x) ((x) << S_PPOD_TAG) #define S_PPOD_PGSZ 30 #define M_PPOD_PGSZ 0x3 #define V_PPOD_PGSZ(x) ((x) << S_PPOD_PGSZ) /* * large memory chunk allocation/release * use vmalloc() if kmalloc() fails */ static inline void *cxgb3i_alloc_big_mem(unsigned int size, gfp_t gfp) { void *p = kmalloc(size, gfp); if (!p) p = vmalloc(size); if (p) memset(p, 0, size); return p; } static inline void cxgb3i_free_big_mem(void *addr) { if (is_vmalloc_addr(addr)) vfree(addr); else kfree(addr); } /* * cxgb3i ddp tag are 32 bits, it consists of reserved bits used by h/w and * non-reserved bits that can be used by the iscsi s/w. * The reserved bits are identified by the rsvd_bits and rsvd_shift fields * in struct cxgb3i_tag_format. * * The upper most reserved bit can be used to check if a tag is ddp tag or not: * if the bit is 0, the tag is a valid ddp tag */ /** * cxgb3i_is_ddp_tag - check if a given tag is a hw/ddp tag * @tformat: tag format information * @tag: tag to be checked * * return true if the tag is a ddp tag, false otherwise. */ static inline int cxgb3i_is_ddp_tag(struct cxgb3i_tag_format *tformat, u32 tag) { return !(tag & (1 << (tformat->rsvd_bits + tformat->rsvd_shift - 1))); } /** * cxgb3i_sw_tag_usable - check if s/w tag has enough bits left for hw bits * @tformat: tag format information * @sw_tag: s/w tag to be checked * * return true if the tag can be used for hw ddp tag, false otherwise. */ static inline int cxgb3i_sw_tag_usable(struct cxgb3i_tag_format *tformat, u32 sw_tag) { sw_tag >>= (32 - tformat->rsvd_bits); return !sw_tag; } /** * cxgb3i_set_non_ddp_tag - mark a given s/w tag as an invalid ddp tag * @tformat: tag format information * @sw_tag: s/w tag to be checked * * insert 1 at the upper most reserved bit to mark it as an invalid ddp tag. */ static inline u32 cxgb3i_set_non_ddp_tag(struct cxgb3i_tag_format *tformat, u32 sw_tag) { unsigned char shift = tformat->rsvd_bits + tformat->rsvd_shift - 1; u32 mask = (1 << shift) - 1; if (sw_tag && (sw_tag & ~mask)) { u32 v1 = sw_tag & ((1 << shift) - 1); u32 v2 = (sw_tag >> (shift - 1)) << shift; return v2 | v1 | 1 << shift; } return sw_tag | 1 << shift; } /** * cxgb3i_ddp_tag_base - shift s/w tag bits so that reserved bits are not used * @tformat: tag format information * @sw_tag: s/w tag to be checked */ static inline u32 cxgb3i_ddp_tag_base(struct cxgb3i_tag_format *tformat, u32 sw_tag) { u32 mask = (1 << tformat->rsvd_shift) - 1; if (sw_tag && (sw_tag & ~mask)) { u32 v1 = sw_tag & mask; u32 v2 = sw_tag >> tformat->rsvd_shift; v2 <<= tformat->rsvd_shift + tformat->rsvd_bits; return v2 | v1; } return sw_tag; } /** * cxgb3i_tag_rsvd_bits - get the reserved bits used by the h/w * @tformat: tag format information * @tag: tag to be checked * * return the reserved bits in the tag */ static inline u32 cxgb3i_tag_rsvd_bits(struct cxgb3i_tag_format *tformat, u32 tag) { if (cxgb3i_is_ddp_tag(tformat, tag)) return (tag >> tformat->rsvd_shift) & tformat->rsvd_mask; return 0; } /** * cxgb3i_tag_nonrsvd_bits - get the non-reserved bits used by the s/w * @tformat: tag format information * @tag: tag to be checked * * return the non-reserved bits in the tag. */ static inline u32 cxgb3i_tag_nonrsvd_bits(struct cxgb3i_tag_format *tformat, u32 tag) { unsigned char shift = tformat->rsvd_bits + tformat->rsvd_shift - 1; u32 v1, v2; if (cxgb3i_is_ddp_tag(tformat, tag)) { v1 = tag & ((1 << tformat->rsvd_shift) - 1); v2 = (tag >> (shift + 1)) << tformat->rsvd_shift; } else { u32 mask = (1 << shift) - 1; tag &= ~(1 << shift); v1 = tag & mask; v2 = (tag >> 1) & ~mask; } return v1 | v2; } int cxgb3i_ddp_tag_reserve(struct t3cdev *, unsigned int tid, struct cxgb3i_tag_format *, u32 *tag, struct cxgb3i_gather_list *, gfp_t gfp); void cxgb3i_ddp_tag_release(struct t3cdev *, u32 tag); struct cxgb3i_gather_list *cxgb3i_ddp_make_gl(unsigned int xferlen, struct scatterlist *sgl, unsigned int sgcnt, struct pci_dev *pdev, gfp_t gfp); void cxgb3i_ddp_release_gl(struct cxgb3i_gather_list *gl, struct pci_dev *pdev); int cxgb3i_setup_conn_host_pagesize(struct t3cdev *, unsigned int tid, int reply); int cxgb3i_setup_conn_pagesize(struct t3cdev *, unsigned int tid, int reply, unsigned long pgsz); int cxgb3i_setup_conn_digest(struct t3cdev *, unsigned int tid, int hcrc, int dcrc, int reply); int cxgb3i_ddp_find_page_index(unsigned long pgsz); int cxgb3i_adapter_ddp_info(struct t3cdev *, struct cxgb3i_tag_format *, unsigned int *txsz, unsigned int *rxsz); void cxgb3i_ddp_init(struct t3cdev *); void cxgb3i_ddp_cleanup(struct t3cdev *); #endif
#include <stdlib.h> struct s { char c1, c2; }; void foo (struct s s) { static struct s s1; s1 = s; } int main () { static struct s s2; foo (s2); exit (0); }
<filename>sandbox/linux/services/credentials.h // Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SANDBOX_LINUX_SERVICES_CREDENTIALS_H_ #define SANDBOX_LINUX_SERVICES_CREDENTIALS_H_ #include "build/build_config.h" // Link errors are tedious to track, raise a compile-time error instead. #if defined(OS_ANDROID) #error "Android is not supported." #endif // defined(OS_ANDROID). #include <string> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/memory/scoped_ptr.h" #include "sandbox/sandbox_export.h" namespace sandbox { // This class should be used to manipulate the current process' credentials. // It is currently a stub used to manipulate POSIX.1e capabilities as // implemented by the Linux kernel. class SANDBOX_EXPORT Credentials { public: // Drop all capabilities in the effective, inheritable and permitted sets for // the current process. static bool DropAllCapabilities() WARN_UNUSED_RESULT; // Return true iff there is any capability in any of the capabilities sets // of the current process. static bool HasAnyCapability(); // Returns the capabilities of the current process in textual form, as // documented in libcap2's cap_to_text(3). This is mostly useful for // debugging and tests. static scoped_ptr<std::string> GetCurrentCapString(); // Returns whether the kernel supports CLONE_NEWUSER and whether it would be // possible to immediately move to a new user namespace. There is no point // in using this method right before calling MoveToNewUserNS(), simply call // MoveToNewUserNS() immediately. This method is only useful to test the // ability to move to a user namespace ahead of time. static bool CanCreateProcessInNewUserNS(); // Move the current process to a new "user namespace" as supported by Linux // 3.8+ (CLONE_NEWUSER). // The uid map will be set-up so that the perceived uid and gid will not // change. // If this call succeeds, the current process will be granted a full set of // capabilities in the new namespace. static bool MoveToNewUserNS() WARN_UNUSED_RESULT; // Remove the ability of the process to access the file system. File // descriptors which are already open prior to calling this API remain // available. // The implementation currently uses chroot(2) and requires CAP_SYS_CHROOT. // CAP_SYS_CHROOT can be acquired by using the MoveToNewUserNS() API. // Make sure to call DropAllCapabilities() after this call to prevent // escapes. // To be secure, the caller must ensure that any directory file descriptors // are closed (for example, by checking the result of // ProcUtil::HasOpenDirectory with a file descriptor for /proc, then closing // that file descriptor). Otherwise it may be possible to escape the chroot. static bool DropFileSystemAccess() WARN_UNUSED_RESULT; private: DISALLOW_IMPLICIT_CONSTRUCTORS(Credentials); }; } // namespace sandbox. #endif // SANDBOX_LINUX_SERVICES_CREDENTIALS_H_
<filename>src/steg/http_steg_mods/file_steg.h #ifndef FILE_STEG_H #define FILE_STEG_H #define SWF_SAVE_HEADER_LEN 1500 #define SWF_SAVE_FOOTER_LEN 1500 #include <list> #include <math.h> using namespace std; extern const unsigned int c_no_of_steg_protocol; /** This is an abstract class that all steg modules should inherit from, and implemenet its virtual function so http steg module can use them to embed into the inherited file type */ class FileStegMod { protected: /** Constants */ //Constants const int RESPONSE_GOOD = 0 ; const int RESPONSE_INCOMPLETE = -1; const int RESPONSE_BAD = -2; PayloadServer* _payload_server; double noise2signal; //making sure that the cover is bigger enough than the //the data to protect against statistical analysis const int c_content_type; //The inheriting class will set the type uint8_t* outbuf; //this is where the payload sit after being injected by the //the message. it is define as class member to avoid allocation and delocation //const int pgenflag; //tells us whether we are dealing with a payload taken from the database (0) or a generated on the fly one (1, for SWF only atm) //not clear if we need this at all /** Finds a payload of approperiate type and size @param data_len: the payload should be able to accomodate this length @param payload_buf: the evbuffer that is going to contain the chosen payload @return payload size or < 0 in case of error */ ssize_t pick_appropriate_cover_payload(size_t data_len, char** payload_buf, string& cover_id_hash); /** Encapsulate the repetative task of checking for the respones of content_type choosing one with appropriate size and extracting the body from header @param data_len: the length of data being embed should be < capacity @param payload_buf: the http response (header+body) corresponding going to cover the data @param payload_size: the size of the payload_buf @return the offset of the body content of payload_buf or < 0 in case of error, that is RESPONSE_INCOMPLETE (<0) if it is incomplete (can't find the start of body) or RESPONSE_BAD (<0) in case of other errors */ static ssize_t extract_appropriate_respones_body(char* payload_buf, size_t payload_size); /** The overloaded version with evbuffer */ ssize_t extract_appropriate_respones_body(evbuffer* payload_buf); /** changes the size of Content Length in HTTTP response header, in case the steg module changes the size of the coverafter emebedding data */ size_t alter_length_in_response_header(uint8_t* original_header, size_t original_header_length, ssize_t new_content_length, uint8_t new_header[]); public: static const size_t c_HTTP_PAYLOAD_BUF_SIZE = HTTP_PAYLOAD_BUF_SIZE; //TODO: one constant //maximum //size of buffer which stores the whole http response static const size_t c_MAX_MSG_BUF_SIZE = 131103; //max size of the message to be embeded //static const size_t c_NO_BYTES_TO_STORE_MSG_SIZE = (static_cast<int>((log2(c_MAX_MSG_BUF_SIZE) + 31) / 32)) * 4; //no of bytes needed to store the message size rounded up to 4 bytes chunks // no of bits in multiple of 32: n = [log2(c_MAX_MSG_BUF_SIZE) + 31) / 32]*32 => // no of bytes = n / 8 //or it is just simpler to limit ourselves to 4G per message typedef uint32_t message_size_t; static const size_t c_NO_BYTES_TO_STORE_MSG_SIZE = sizeof(message_size_t); static const size_t c_HIGH_BYTES_DISCARDER; //pow(2, c_NO_BYTES_TO_STORE_MSG_SIZE * 8); /** * indicates if the steg mod is cover length preserving which is true * by default. needs to be overrriden for unit testing of the steg modules * * @return true if the steg module doesn't change the length of cover * after inserting the data, false otherwise */ virtual bool cover_lenght_preserving() { return true; }; /** embed the data in the cover buffer, the assumption is that the function doesn't expand the buffer size @param data: the data to be embeded @param data_len: the length of the data @param cover_payload: the cover to embed the data into @param cover_len: cover size in byte @return < 0 in case of error or length of the cover with embedded dat at success */ virtual int encode(uint8_t* data, size_t data_len, uint8_t* cover_payload, size_t cover_len) = 0; /** Embed the data in the cover buffer, need to be implemented by the different steg modules. The steg_modules should make sure that that the data is not larger than _MAX_MSG_BUF_SIZE @param data: the pointer to the buffer that is going to contain the data @param cover_payload: the cover to embed the data into @param cover_len: cover size in byte @return the length of recovered data or < 0 in case of error */ virtual ssize_t decode(const uint8_t *cover_payload, size_t cover_len, uint8_t* data) = 0; const list<string> extensions; /** Returns the capacity which can be encoded in the buffer assuming that the buffer starts with the HTTP response header */ virtual ssize_t capacity(const uint8_t* buffer, size_t len) = 0; /** Returns the capacity which can be encoded in the cover_body when cover_body does not include the HTTP response header */ virtual ssize_t headless_capacity(char *cover_body, int body_length) = 0; /** Find appropriate payload calls virtual embed to embed it appropriate to its typex @param source the data to be transmitted @param conn the connection over which the data is going to be transmitted @return the actual number of bytes (cover size) transmitted */ virtual int http_server_transmit(evbuffer *source, conn_t *conn); /** Tries to extract the embeded data in source buffer and put them in dest. It returns INCOMPLETE or BAD if it fails @param source the received buffer over http conncetion @param dest will contain the extracted data from http cover @return RECV_GOOD if the extraction is successful, RECV_INCOMPLETE In case it can't find all the data in the cover (body etc) or bad. */ virtual int http_client_receive(conn_t *conn, evbuffer *dest, evbuffer *source); /** constructor, sets the playoad server @param the payload server that is going to be used to provide cover to this module. @child_type? */ FileStegMod(PayloadServer* payload_provider, double noise2signal, int child_type); /** Destructor, just releases the http buffer */ virtual ~FileStegMod(); }; #endif //FILE_STEG_H
// // OSVSequence.h // OpenStreetView // // Created by <NAME> on 20/09/15. // Copyright (c) 2015 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> @protocol OSVPhoto; @protocol OSVSequence <NSObject> @property (nonatomic, assign) NSInteger uid; @property (nonatomic, strong) NSDate *dateAdded; @property (nonatomic, strong) NSMutableArray<id<OSVPhoto>> *photos; // an array containing all the photo objects @property (nonatomic, strong) NSArray *track; // an array of locations representing the tack @property (nonatomic, assign) CLLocationCoordinate2D topLeftCoordinate; @property (nonatomic, assign) CLLocationCoordinate2D bottomRightCoordinate; @property (nonatomic, assign) long long sizeOnDisk; @property (nonatomic, assign) double length; // the lenght of the track expresed in meters @property (nonatomic, assign) BOOL hasOBD; @property (nonatomic, strong) NSString *location; @property (nonatomic, strong) NSString *previewImage; @property (nonatomic, assign) NSInteger coverage; - (BOOL)intersectWithTopLeftCoordinate:(CLLocationCoordinate2D)topLeftCoordinate andBottomRightCoordinate:(CLLocationCoordinate2D)bottomRightCoordinate; @end @interface OSVSequence : NSObject <OSVSequence> @property (nonatomic, assign) NSInteger uploadID; // the id used to upload a sequence of photos @property (nonatomic, assign) NSInteger points; @property (nonatomic, strong) NSMutableArray *scoreHistory; @property (nonatomic, strong) NSMutableDictionary *videos; @end
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Jun 10 2020 10:03:13). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @class SSIndicatorLight; @interface PRESystemIndicator : NSObject { SSIndicatorLight *_sil; // 8 = 0x8 } + (id)sharedInstance; // IMP=0x0000000100005ab4 - (void).cxx_destruct; // IMP=0x0000000100005fe4 @property(retain, nonatomic) SSIndicatorLight *sil; // @synthesize sil=_sil; - (void)off; // IMP=0x0000000100005ec0 - (void)on; // IMP=0x0000000100005df4 - (void)flashMorseCodePattern:(id)arg1; // IMP=0x0000000100005c4c - (id)init; // IMP=0x0000000100005b84 @end
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Public License (Ms-PL). // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. // All other rights reserved. // // Declarations of classes CTraceAndLog, CEventLog, and CDebugTrace // Being base class of CEventLog and CDebugTrace, CTraceAndLog provides common // implementation of log and trace. CEventLog is designed for write events to // log files. CDebugTrace use ATLTRACE to output debug information. // #pragma once #include "resource.h" #include "TextFile.h" #include "MemoryRef.h" BEGIN_DEFAULT_NAMESPACE #define EventReportInfo CEventLog(IDS_EVENT_LEVEL_INFO, __FILE__, __LINE__) #define EventReportWarning CEventLog(IDS_EVENT_LEVEL_WARNING, __FILE__, __LINE__) #define EventReportError CEventLog(IDS_EVENT_LEVEL_ERROR, __FILE__, __LINE__) #if defined(_DEBUG) #define DebugTrace CDebugTrace(IDS_EVENT_LEVEL_TRACE, __FILE__, __LINE__) #define DebugDump CDebugTrace(IDS_EVENT_LEVEL_DUMP, __FILE__, __LINE__) #else #define DebugTrace #define DebugDump #endif #pragma region Declaration of CTraceAndLog class CTraceAndLog { protected: CTraceAndLog() {}; CTraceAndLog(UINT nEventLevelId, const char *pszSourceFileName, int nSourceLineNumber); protected: CString m_szPrefix; UINT m_nEventLevelId; }; #pragma endregion #pragma region Declaration of CDebugTrace class CDebugTrace : public CTraceAndLog { public: CDebugTrace(UINT nEventLevel, const char *pstrSourceFile, int nSourceLine) : CTraceAndLog(nEventLevel, pstrSourceFile, nSourceLine){}; public: CDebugTrace& _cdecl operator ()(LPCTSTR pstrMessage, ...); CDebugTrace& _cdecl operator ()(CMemoryRef xMemoryDump, LPCTSTR pstrMessage, ...); }; #pragma endregion #pragma region Declaration of CEventLog class CEventLog : public CTraceAndLog { public: CEventLog(UINT nEventLevel, const char *pstrSourceFile, int nSourceLine) : CTraceAndLog(nEventLevel, pstrSourceFile, nSourceLine){}; public: CEventLog& _cdecl operator ()(UINT nMessageId, ...); public: static BOOL Initialize(void); private: static void LockEventLogFile(void); static void UnlockEventLogFile(void); static BOOL CarefullyWriteLogFile(LPCTSTR pstrText); private: static LONG m_nEventLogFileLock; // Help to make log-file writing critical section. static CWriteTextFile m_xEventLogFile; }; #pragma endregion END_DEFAULT_NAMESPACE
#pragma once #include <opencv2/core.hpp> double launchImageFilteringCpu(const cv::Mat& src, cv::Mat& dst, const cv::Mat& kernel, const int border_size, const int loop_num); double launchImageFilteringCV(const cv::Mat& src, cv::Mat& dst, const cv::Mat& kernel, const int border_size, const int loop_num);
#ifndef TC_CTX_H #define TC_CTX_H #include <inttypes.h> #include <stdbool.h> struct TCError; enum TC_ERR_KIND { //the kinds of type errors that are possible in a smalldragon program TC_ERR_ARG_NUM_MISMATCH, TC_ERR_ARG_TYPE_MISMATCH, TC_ERR_WRONG_RETURN_TYPE, TC_ERR_BINOP_TYPE_MISMATCH, TC_ERR_SUBR_NOT_FOUND, TC_ERR_VAR_NOT_FOUND, TC_ERR_VAR_READONLY, TC_ERR_ASSIGN_TYPE_MISMATCH, TC_ERR_CALLED_THROWING_WRONG, TC_ERR_RANGE_REQUIRES_INT, TC_ERR_THROW_WRONG_USAGE, TC_ERR_CONDITION_REQUIRES_BOOL, //switch, case TC_ERR_SWITCH_REQUIRES_PRIMITIVE_TYPE, TC_ERR_SWITCH_CASE_TYPE_MISMATCH, //unary operator TC_ERR_WRONG_OP_UNOP, //indices TC_ERR_INDEX_NOT_INTEGER_TYPE, TC_ERR_TOO_MANY_INDICES, TC_ERR_LOCAL_VAR_NOT_A_SUBROUTINE, TC_ERR_SIDE_EFFECT_IN_PURE_CONTEXT, TC_ERR_OTHER, TC_ERR_END }; struct TCError{ char* opt_msg; //may be NULL enum TC_ERR_KIND err_kind; char* filename; uint32_t line_num; char* opt_snippet; //may be NULL struct TCError* next; }; struct TCCtx { struct ST* st; struct Method* current_fn; //are we typechecking inside a try-block? uint16_t depth_inside_try_stmt; uint16_t depth_inside_loop; //linked list of errors struct TCError* tc_first_err; struct TCError* tc_last_err; uint32_t tc_err_count; bool print_errors; char* current_filename; uint32_t current_line_num; }; #endif
<gh_stars>1-10 /* ======================================== * * Copyright YOUR COMPANY, THE YEAR * All Rights Reserved * UNPUBLISHED, LICENSED SOFTWARE. * * CONFIDENTIAL AND PROPRIETARY INFORMATION * WHICH IS THE PROPERTY OF your company. * * ======================================== */ #include "datalogger.h" void logger_init(Log_ts * log){ int i; for(i = 0; i < LOG_BUFF_SIZE; i++){ log->CircBuff.data[i] = 0; } log->num_vars = 0; log->CircBuff.data_index = 0; log->CircBuff.data_size = LOG_BUFF_SIZE; } void attach_variable(void * var, enum types_e type, const char * name, Log_ts * log){ Var_ts temp_var; temp_var.type = type; temp_var.var_ptr = var; if(log->num_vars < LOG_SIZE){ log->vars[log->num_vars] = temp_var; memcpy(log->vars[log->num_vars].name,name,strlen(name)+1); log->num_vars++; } return; } void logger(Log_ts * log){ //fetch most recent values of all vars, store in data array //separate by a delimiter //important to do this with a circular buffer int i; int max_size; for(i = 0; i < log->num_vars; i++){ //add each logged var to the data array circbuff_add((log->vars[i].var_ptr),var_size(log->vars[i].type),&log->CircBuff); } return; } void circbuff_add(void * data, int size, CircBuff_ts * circbuff){ int i; for(i = 0; i < size; i++){ switch(size){ case 1: circbuff_add_byte(*((uint8 *)data),circbuff); break; case 2: circbuff_add_byte((uint8)(*((uint16 *)data)>>i*8),circbuff); break; case 4: circbuff_add_byte((uint8)(*((uint32 *)data)>>i*8),circbuff); break; case 8: circbuff_add_byte((uint8)(*((uint64 *)data)>>i*8),circbuff); break; default: ; } } } void circbuff_add_byte(uint8 data, CircBuff_ts * circbuff){ //will store data until the buffer is full, then do nothing if(circbuff->data_index < circbuff->data_size){ circbuff->data[circbuff->data_index] = data; circbuff->data_index = circbuff->data_index + 1; } } uint8 * get_buffer(Log_ts * log){ return (log->CircBuff.data); } int get_buffer_size(Log_ts * log){ return (int) log->CircBuff.data_index; } int var_size(enum types_e type){ int size; switch (type){ case UINT8: size = 1; break; case INT8: size = 1; break; case UINT16: size = 2; break; case INT16: size = 2; break; case UINT32: size = 4; break; case INT32: size = 4; break; case UINT64: size = 8; break; case INT64: size = 8; break; case CHAR: size = 1; break; case FLOAT: size = 4; break; case DOUBLE: size = 8; break; default: size = 0; // default statements } return size; } void _clear_circbuff(CircBuff_ts * circbuff){ int i; for(i = 0; i < circbuff->data_size; i++){ circbuff->data[i] = 0; } circbuff->data_index = 0; } void clear_log(Log_ts * log){ _clear_circbuff(&log->CircBuff); } void get_command_usb(Log_ts * log, struct usb_ts * usb_s){ uint32 command; uint8 argument; if(usb_s->usb_pub.cmd_flag != 0){ command = usb_s->usb_in.command[3] +0xFF * usb_s->usb_in.command[2] + \ 0xFFFF * usb_s->usb_in.command[1] + 0xFFFFFF * usb_s->usb_in.command[0]; switch(command){ case NOCMD: ; break; case NUMVARS: //how many variables are being logged? //reply with number of logged variables usb_s->usb_out.response[0] = log->num_vars; usb_s->usb_out.out_flag = 1; usb_s->usb_pub.cmd_flag = 0; break; case VARSIZE: //size of variable in bytes //variable number is the arg, argument is first byte after command argument = usb_s->usb_in.command[4]; if(argument <= log->num_vars){ usb_s->usb_out.response[0] = var_size(log->vars[argument].type); } usb_s->usb_out.out_flag = 1; usb_s->usb_pub.cmd_flag = 0; break; case VARNAME: //variable name? (string) //variable number is the arg, first byte after command argument = usb_s->usb_in.command[4]; if(argument <= log->num_vars){ memcpy(usb_s->usb_out.response,log->vars[argument].name,strlen(log->vars[argument].name)); } usb_s->usb_out.out_flag = 1; usb_s->usb_pub.cmd_flag = 0; break; case VARMAX: //max value for variable? //variable number is the arg, first byte after command argument = usb_s->usb_in.command[4]; if(argument <= log->num_vars){ ; } usb_s->usb_pub.cmd_flag = 0; break; case VARMIN: //min value for variable? //variable number is the arg, first byte after command argument = usb_s->usb_in.command[4]; if(argument <= log->num_vars){ ; } usb_s->usb_pub.cmd_flag = 0; break; case VARSCALE: //multiplier for variable? //variable number is the arg, first byte after command argument = usb_s->usb_in.command[4]; if(argument <= log->num_vars){ ; } usb_s->usb_pub.cmd_flag = 0; break; case VAROFFSET: //offset for variable? //variable number is the arg, first byte after command argument = usb_s->usb_in.command[4]; if(argument <= log->num_vars){ ; } usb_s->usb_pub.cmd_flag = 0; break; case START: break; case STOP: break; case RESET: break; default: ; } } } /* [] END OF FILE */
/*Solo corre en Code::Blocks, no en el online gbd :( */ /*texto sugerido a utilizar: h,ok.ao97-64(fw.789) "wo78.", [e--soa,.97648]*/ #include<stdio.h> #define TRUE 1 #define FALSE 0 int main() { char s[100]; char o[100]; int p=0; int q=0; int j=0; int i=0; scanf("%[^\n]",s); while(s[i] != '0') { switch(s[i]){ case '(': p=TRUE; o[j] = s [i]; j++; break; case ')': p=FALSE; o[j] = s [i]; j++; break; case '{': p=TRUE; o[j] = s [i]; j++; break; case '}': p=FALSE; o[j] = s [i]; j++; break; case '[': p=TRUE; o[j] = s [i]; j++; break; case ']': p=FALSE; o[j] = s [i]; j++; break; case '\"': q++; o[j] = s [i]; j++; break; case '\'': q++; o[j] = s [i]; j++; break; default: if (p==TRUE || q==TRUE){ o[j] = s[i]; j++; } else { //lines 44-47 taken from rulegamer07 if (q==2){ q=0;} if((s[i]>='A' && s[i]<='Z')||(s[i]>='a' && s[i]<='z')||(s[i] == ' ')) { o[j] = s[i]; j++; } else{ if(s[i] >=48 && s[i] <=57 ) { if(o[j-1]=='X'){ } else {o[j]='X'; j++;} } } } } i++; } printf("%s\n", o ); return 0; }
<gh_stars>10-100 #pragma once #include "gameplay/GameBoard.h" #include "gameplay/PlayScreen.h" class GameBoardUltra final: public GameBoard { public: GameBoardUltra(PlayScreen *const owner); virtual ~GameBoardUltra() override = default; virtual void lock() override; virtual float getFallPeriod() override; virtual long getLockDelay() override; virtual void renderOtherObjects(const long timePassed) override; virtual void gameOver() override; };
/* ========== LexicalScope.h ========== */ #pragma once #include "Str.h" #include <vector> #include <map> #define TEMPORARYLIMIT 255 // maximum number of temporaries permitted (ditto) #define MAXBLOCKNESTING 255 // maximum depth to which blocks (actually contexts) can be nested enum TempVarType { tvtUnaccessed=0, // Temp variable which is not accessed at all tvtStack, // Temp variable accessed only from local scope (or optimized blocks) tvtCopied, // Temp variable which is closed over, but only read after closure tvtShared, // Temp variable which is written after being closed over tvtCopy, // Temp variable decl created to represent a copied temp in the closure }; enum VarRefType { vrtUnknown = 0, vrtRead=1, vrtWrite=2, vrtReadWrite=3}; class LexicalScope; class TempVarRef; class Compiler; class TempVarDecl { Str m_strName; TEXTRANGE m_range; LexicalScope* m_pScope; TempVarType m_varType; VarRefType m_refType; TempVarDecl* m_pOuter; int m_nIndex; bool m_bInvisible; // Not visible in this scope (used for real declarations of temps in optimized blocks) bool m_bIsArgument; bool m_bIsReadOnly; public: TempVarDecl(const Str& strName, const TEXTRANGE& range) : m_strName(strName), m_pScope(NULL), m_range(range), m_varType(tvtUnaccessed), m_refType(vrtUnknown), m_pOuter(NULL), m_nIndex(-1), m_bInvisible(false), m_bIsArgument(false), m_bIsReadOnly(false) { } TempVarDecl(const TempVarDecl& s) : m_strName(s.m_strName), m_pScope(s.m_pScope), m_varType(s.m_varType), m_refType(s.m_refType), m_pOuter(const_cast<TempVarDecl*>(&s)), m_nIndex(-1), m_bInvisible(false), m_bIsArgument(false), m_bIsReadOnly(true) { } ///////////////////////// // Accessing TempVarType GetVarType() const { return m_varType; } void SetVarType(TempVarType varType) { m_varType = varType; } VarRefType GetRefType() const { return m_refType; } int GetIndex() const { return m_varType == tvtCopy || GetOuter() == NULL ? m_nIndex : GetOuter()->GetIndex(); } void SetIndex(int index) { _ASSERTE(m_varType == tvtCopy || GetOuter() == NULL); m_nIndex = index; } const Str& GetName() const { return m_strName; } void SetName(const Str& strName) { m_strName = strName; } LexicalScope* GetScope() const { return m_pScope; } void SetScope(LexicalScope* pScope) { m_pScope = pScope; } LexicalScope* GetActualScope() const { return GetActualDecl()->GetScope(); } TempVarDecl* GetOuter() const { return m_pOuter; } void SetOuter(TempVarDecl* pOuter) { m_pOuter = pOuter; } const TEXTRANGE& GetTextRange() const { return m_range; } void SetTextRange(const TEXTRANGE& range) { m_range = range; } TempVarDecl* GetActualDecl() const { TempVarDecl* pDecl = const_cast<TempVarDecl*>(this); while (pDecl->m_pOuter != NULL) pDecl = pDecl->m_pOuter; return pDecl; } void SetIsArgument(bool bIsArgument) { m_bIsArgument = bIsArgument; if (bIsArgument) BeReadOnly(); } void BeReadOnly() { m_bIsReadOnly = true; } void MarkInvisible() { m_bInvisible = true; } // Operations void MergeRef(const TempVarRef*, Compiler* pCompiler); // Testing bool IsArgument() const { return m_bIsArgument; } bool IsStack() const { switch (m_varType) { case tvtCopy: // break; case tvtStack: case tvtCopied: return true; case tvtUnaccessed: return m_bIsReadOnly; case tvtShared: default: break; } return false; } bool IsReferenced() const { return m_varType != tvtUnaccessed || m_bIsReadOnly; } bool IsVisible() const { return !m_bInvisible; } bool IsReadOnly() const { return m_bIsReadOnly; } }; class TempVarRef { LexicalScope* m_pScope; TempVarDecl* m_pDecl; VarRefType m_refType; TEXTRANGE m_range; public: TempVarRef(LexicalScope* pScope, TempVarDecl* pDecl, VarRefType refType, const TEXTRANGE& range) : m_pScope(pScope), m_pDecl(pDecl), m_refType(refType), m_range(range) { } ////////////////////////////////////////////// // Accessing int GetEstimatedDistance() const; int GetActualDistance() const; VarRefType GetRefType() const { return m_refType; } void SetRefType(VarRefType refType) { _ASSERTE(refType >= m_refType); m_refType = refType; } TempVarDecl* GetDecl() const { return m_pDecl; } void SetDecl(TempVarDecl* pDecl) { m_pDecl = pDecl; } TempVarType GetVarType() const { return m_pDecl->GetVarType(); } LexicalScope* GetScope() const { return m_pScope; } LexicalScope* GetRealScope() const; const Str& GetName() const { return GetDecl()->GetName(); } const TEXTRANGE& GetTextRange() const { return m_range; } ////////////////////////////////////////////// // Testing bool IsShared() const { return GetVarType() == tvtShared; } bool IsStack() const { return GetDecl()->IsStack(); } ///////////////////////////////////////////// // Operations void MergeRefIntoDecl(Compiler* pCompiler); }; typedef std::vector<TempVarDecl*> DECLLIST; typedef std::map<Str, TempVarDecl*> DECLMAP; typedef std::vector<TempVarRef*> REFLIST; typedef std::map<Str, REFLIST> REFLISTMAP; typedef std::vector<Oop> OOPVECTOR; class LexicalScope { LexicalScope* m_pOuter; DECLLIST m_tempVarDecls; REFLISTMAP m_tempVarRefs; DECLLIST m_copiedTemps; TEXTRANGE m_textRange; // Range of text this scope represents int m_nArgs; int m_nStackSize; int m_nSharedTemps; int m_initialIP; int m_finalIP; POTE m_oteBlockLiteral; // Flags bool m_bIsEmptyBlock; // An empty block bool m_bIsOptimizedBlock;// Set if scope is for an optimized (inlined) block, i.e. has no run-time representation bool m_bHasFarReturn; // Set if scope, or an enclosed scope, contains a FarReturn instruction bool m_bRefersToSelf; // Set if scope refers directly or indirectly to receiver bool m_bRefsOuterTemps; // Set if scope refers to shared temps from outer contexts private: LexicalScope(); LexicalScope(const LexicalScope&); public: LexicalScope(LexicalScope* pOuter, int nStart, bool bOptimized) : m_pOuter(pOuter), m_nArgs(0), m_nStackSize(0), m_nSharedTemps(0), m_initialIP(-1), m_finalIP(-2), m_bIsEmptyBlock(false), m_bIsOptimizedBlock(bOptimized), m_bHasFarReturn(false), m_bRefersToSelf(false), m_bRefsOuterTemps(false), m_textRange(nStart, -1), m_oteBlockLiteral(NULL) { } ~LexicalScope(); int GetCopiedValuesCount() const { return m_copiedTemps.size(); } int GetStackTempCount() const { return m_nStackSize - GetArgumentCount() - GetCopiedValuesCount(); } int GetTempCount() const { return m_tempVarDecls.size(); } int GetArgumentCount() const { return m_nArgs; } int GetSharedTempsCount() const { _ASSERTE(!IsOptimizedBlock() || m_nSharedTemps == 0); return m_nSharedTemps; } LexicalScope* GetOuter() const { return m_pOuter; } LexicalScope* GetRealOuter() const { return GetOuter()->GetRealScope(); } // Answer the nearest real (non-optimized) scope. If the scope // is itself unoptimized, then this will be the receiver. The // actual scope is the scope in which any variables declared in the // receiver will actually be allocated. LexicalScope* GetRealScope() const { LexicalScope* pScope = const_cast<LexicalScope*>(this); while (pScope != NULL && pScope->IsOptimizedBlock()) { pScope = pScope->GetOuter(); } return pScope; } private: void SetOuter(LexicalScope* pOuter) { m_pOuter = pOuter; } public: DECLLIST& GetCopiedTemps() { return m_copiedTemps; } int GetStackSize() const { return m_nStackSize; } void BeOptimizedBlock(); void BeEmptyBlock() { m_bIsEmptyBlock = true; } void ArgumentAdded(TempVarDecl* pArg) { pArg->SetIsArgument(true); pArg->SetIndex(m_nArgs++); } int GetDepth() const { int depth = 0; const LexicalScope* current = this; const LexicalScope* outer; while ((outer = current->GetOuter()) != NULL) { if (!current->IsOptimizedBlock()) depth++; current = outer; } return depth; } int GetLogicalDepth() const { int depth = 0; const LexicalScope* current = this; const LexicalScope* outer; while ((outer = current->GetOuter()) != NULL) { depth++; current = outer; } return depth; } int GetActualDistance(LexicalScope* pDeclScope) const { const LexicalScope* pScope = GetRealScope(); int distance = 0; while (pScope != pDeclScope) { _ASSERTE(pScope != NULL); pScope = pScope->GetOuter(); if (pScope->GetSharedTempsCount() != 0) { _ASSERTE(!pScope->IsOptimizedBlock()); distance++; _ASSERTE(distance <= MAXBLOCKNESTING); } } return distance; } const TEXTRANGE& GetTextRange() const { return m_textRange; } void SetTextStop(int stop) { m_textRange.m_stop = stop; } void MarkNeedsSelf() { m_bRefersToSelf = true; } void MarkFarReturner() { if (m_bHasFarReturn) return; m_bHasFarReturn = true; LexicalScope* outer = GetOuter(); if (outer != NULL) { outer->MarkFarReturner(); } } void SetReferencesOuterTempsIn(LexicalScope* pDeclScope) { // This flag is only applicable to block scopes, and must be propagated // up to the outermost block as each block in the chain will need a LexicalScope* pScope = this; while (pScope != pDeclScope) { pScope->m_bRefsOuterTemps = true; pScope = pScope->GetOuter(); _ASSERTE(pScope != NULL); } } void SetInitialIP(int ip) { m_initialIP = ip; } void MaybeSetInitialIP(int ip) { if (GetInitialIP() < 0) { SetInitialIP(ip); // If an optimized block, such as a repeat loop, may need to chain out // to the outer scope so that cases such as the following are handled // correctly: [[.,..] repeat] value if (IsOptimizedBlock()) { GetOuter()->MaybeSetInitialIP(ip); } } } int GetInitialIP() const { return m_initialIP; } int GetFinalIP() const { return m_finalIP; } void SetFinalIP(int ip) { if (m_finalIP < ip) { m_finalIP = ip; if (GetOuter()) { GetOuter()->SetFinalIP(ip); } } } void IncrementIPs() { if (m_initialIP >= 0) { _ASSERTE(m_finalIP >= 0); m_initialIP++; m_finalIP++; // If associated with a clean block, we need to update it's initialIP too // Note that the initialIP of the block is 1-based, whereas the m_initialIP // of this object is zero-based. //STBlockClosure* pBlock = GetBlock(); //if (pBlock != NULL) //{ // _ASSERTE(IntegerValueOf(pBlock->m_initialIP) == m_initialIP); // pBlock->m_initialIP = IntegerObjectOf(m_initialIP + 1); //} } } void SetCleanBlockLiteral(POTE block) { m_oteBlockLiteral = block; } STBlockClosure* GetBlock() { return m_oteBlockLiteral ? reinterpret_cast<STBlockClosure*>(GetObj(m_oteBlockLiteral)) : NULL; } /////////////////////////////////////////////////////////////////////////// // Testing bool HasFarReturn() const { return m_bHasFarReturn; } bool NeedsSelf() const { return m_bRefersToSelf; } bool NeedsOuter() const { return HasFarReturn() || m_bRefsOuterTemps; } bool IsOptimizedBlock() const { return m_bIsOptimizedBlock; } bool IsEmptyBlock() const { return m_bIsEmptyBlock && GetArgumentCount() == 0; } bool IsInBlock() const { return GetOuter() != NULL && (!IsOptimizedBlock() || GetOuter()->IsInBlock()); } bool IsBlock() const { return GetOuter() != NULL && !IsOptimizedBlock(); } // Clean blocks can be allocated statically as they don't close over any // of their creation time environment and don't contain a ^-return bool IsCleanBlock() const { return IsBlock() && !NeedsSelf() && !NeedsOuter() && GetSharedTempsCount() == 0 && GetCopiedValuesCount() == 0; } ///////////////////////////////////////////////////////////////// // Searching TempVarDecl* FindTempDecl(const Str&); //////////////////////////////////////////////////////////////// // Operations void RenameTemporary(int, const Str&, const TEXTRANGE&); TempVarDecl* CopyTemp(TempVarDecl* pTemp, Compiler*); TempVarRef* AddTempRef(TempVarDecl*, VarRefType, const TEXTRANGE&); void CopyTemps(Compiler*); void AllocTempIndices(Compiler*); void PropagateOuterRequirements(); void AddTempDecl(TempVarDecl* pDecl, Compiler*); void PatchOptimized(Compiler*); void PatchBlockLiteral(IDolphin*, POTE oteMethod); POTE BuildTempMapEntry(IDolphin*) const; private: void PropagateNeedsSelf(); void PropagateFarReturn(); void AddVisibleDeclsTo(DECLMAP&) const; void AddSharedDeclsTo(DECLMAP& allSharedDecls) const; void CopyDownOptimizedDecls(Compiler*); }; inline int TempVarRef::GetEstimatedDistance() const { // Note that this will be an overestimate until the optimized scopes have been // unlinked. return GetRealScope()->GetDepth() - GetDecl()->GetScope()->GetDepth(); }
#include <stdio.h> #include <stdint.h> #include <string.h> #include "queue.h" #include "iot_import.h" #include "lite-utils.h" typedef struct { void *data; } node_t; struct queue_s { int rdx; int wdx; int max_nodes; node_t *nodes; void *lock; void *sem; }; queue_t *queue_new(int max_nodes) { queue_t *q = LITE_malloc(sizeof(queue_t)); if (!q) return NULL; memset(q, 0, sizeof(queue_t)); q->nodes = LITE_calloc(max_nodes, sizeof(node_t)); if (!q->nodes) { LITE_free(q); return NULL; } q->max_nodes = max_nodes; q->lock = HAL_MutexCreate(); if (!q->lock) { LITE_free(q->nodes); LITE_free(q); return NULL; } q->sem = HAL_SemaphoreCreate(); if (!q->sem) { HAL_MutexDestroy(q->lock); LITE_free(q->nodes); LITE_free(q); return NULL; } return q; } int queue_free(queue_t *q) { if (q->nodes) LITE_free(q->nodes); if (q->lock) HAL_MutexDestroy(q->lock); if (q->sem) HAL_SemaphoreDestroy(q->sem); LITE_free(q); return 0; } inline static int queue_lenght(queue_t *q) { return (unsigned int)(q->wdx - q->rdx); } inline static int queue_empty(queue_t *q) { return (queue_lenght(q) == 0); } inline static int queue_full(queue_t *q) { return (queue_lenght(q) == q->max_nodes); } void *queue_get(queue_t *q, uint32_t timeout_ms) { if (HAL_SemaphoreWait(q->sem, timeout_ms) < 0) return NULL; HAL_MutexLock(q->lock); if (queue_empty(q)) { HAL_MutexUnlock(q->lock); return NULL; } void *data = q->nodes[q->rdx % q->max_nodes].data; q->rdx++; HAL_MutexUnlock(q->lock); return data; } int queue_put(queue_t *q, void *data) { HAL_MutexLock(q->lock); if (queue_full(q)) { HAL_MutexUnlock(q->lock); return -1; } q->nodes[q->wdx % q->max_nodes].data = data; q->wdx++; HAL_MutexUnlock(q->lock); HAL_SemaphorePost(q->sem); return 0; }
/** ****************************************************************************** * @file navipack_session_layer.h * @author Jalon * @date 2016.06.16 * @brief 通讯协议会话层解析相关声明 * @attention Copyright (C) 2016 Inmotion Corporation ****************************************************************************** */ #ifndef __NAVIPACK_SESSION_LAYER_H__ #define __NAVIPACK_SESSION_LAYER_H__ /** @addtogroup Session_Layer * @{ */ #include "navipack_type.h" #include "navipack_transport_layer.h" #define CHASSIS_PLATFORM #include "navipack_protocol.h" #define REG_ID_STATUS 1 #define REG_ID_COTROL 2 #define REG_ID_CONFIG 3 #define REG_ID_USER 4 #define REG_ID_UID 5 typedef struct { // 需要初始化 u8 *rxBuffer; ///< 接收 Buffer 指针 u8 *txBuffer; ///< 发送 Buffer 指针 u16 rxSize; ///< 接收 Buffer 尺寸 u16 txSize; ///< 发送 Buffer 尺寸 u16 rxDataLen; u16 txDataLen; TransportFrame_Type rxFrame; TransportFrame_Type txFrame; NaviPack_CtrlType control; ///< 控制寄存器 NaviPack_StatusType status; ///< 状态寄存器 NaviPack_ConfigType config; ///< 参数寄存器 u32 FirmwareRespond; }NavipackComm_Type; bool NaviPack_SessionRxProcessor(NavipackComm_Type *comm, u8 data); bool RegisterWrite(NaviPack_HeadType *head, u8 *reg, u32 size, u8 reg_id); bool RegisterRead(NavipackComm_Type *comm, NaviPack_HeadType *head, u8 err_id, u8 *reg, u32 reg_size, u8 reg_id); bool Navipack_TransportUnpacking(NavipackComm_Type *comm, u8 data); bool Navipack_TransportPacking(NavipackComm_Type *comm, u8 *in_buf, u16 len, u8 pack_flag); bool Navipack_TxCallback(u8* pbuf, u16 len); bool Navipack_RxCallback(NavipackComm_Type *comm, NaviPack_HeadType *head); /** * @} */ #endif
void printf(const char* fmt, ...); struct strWithLen sprintf(const char* fmt, ...);
#ifndef IRIS_BUFFERED_WRITER_H_ #define IRIS_BUFFERED_WRITER_H_ #include <string.h> #include <memory> #include "writer.h" namespace iris { struct buffered_writer { private: buffered_writer(const buffered_writer & rhs)=delete; struct buffered_writer & operator=(const buffered_writer &rhs)=delete; writer &m_w; char *m_buf; int m_pos; int m_capacity; public: buffered_writer(writer & w, size_t cap = 0); ~buffered_writer(); void expand(size_t n); inline void reset() { m_pos = 0; } inline char * reserve(size_t s) { if (freespace() < s) { flush(); if (freespace() < s) throw std::bad_alloc(); } return write_pointer(); } inline size_t freespace() { return m_capacity - m_pos; } inline void inc_write_pointer(size_t s) { m_pos += s; } inline char * write_pointer() { return m_buf + m_pos; } inline size_t size() { return m_pos; } inline operator char*() { return m_buf; } inline void flush() { m_w.write(m_buf, m_pos); reset(); } }; } #endif
/****************************************************************************** * Copyright (c) 2012-2013, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the MSS PROJECT nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 MSS PROJECT OR ITS * 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 mss_sema.c * * @brief mcu simple scheduler semaphore module * * @version 0.2.1 * * @author <NAME> * * @remark this will be included in compilation only if MSS_TASK_USE_SEMA * defined as TRUE * ******************************************************************************/ //***************************************************************************** // Include section //***************************************************************************** #include "mss.h" #include "mss_int.h" #if (MSS_TASK_USE_SEMA == TRUE) //***************************************************************************** // Global variables //***************************************************************************** //***************************************************************************** // Macros (defines), data types, static variables //***************************************************************************** /** mss_sema_t * mss semaphore table data type */ struct mss_sema_tbl_t{ uint16_t value; mss_task_bits_t waiting_tasks; mss_task_bits_t signaling_tasks; }; // number of created semaphores static uint8_t num_of_sema = 0; // semaphore table static struct mss_sema_tbl_t sema_tbl[MSS_MAX_NUM_OF_SEMA]; //***************************************************************************** // Internal function declarations //***************************************************************************** //***************************************************************************** // External functions //***************************************************************************** /**************************************************************************//** * * mss_sema_create * * @brief create a new semaphore * * @param[in] init_val initial semaphore value * * @return handle to created semaphore, MSS_SEMA_INVALID_HDL if failure * ******************************************************************************/ mss_sema_t mss_sema_create(uint16_t init_val) { mss_sema_t ret_hdl = MSS_SEMA_INVALID_HDL; // check if there is a free semaphore block if(num_of_sema < MSS_MAX_NUM_OF_SEMA) { // set initialization value of semaphore block sema_tbl[num_of_sema].value = init_val; sema_tbl[num_of_sema].waiting_tasks = 0; sema_tbl[num_of_sema].signaling_tasks = 0; // return handle and increment number of mque block ret_hdl = &sema_tbl[num_of_sema++]; } return ret_hdl; } /**************************************************************************//** * * mss_sema_wait * * @brief decrement (lock/down) a semaphore. A task can only lock a * semaphore once. When semaphore is not available, the task * will be put into waiting task list. * * @param[in] hdl semaphore handle * * @return if true semaphore is successfully decremented, if false semaphore * is not available * ******************************************************************************/ bool mss_sema_wait(mss_sema_t hdl) { bool ret = false; uint16_t task_bit; mss_int_flag_t int_flag; // check task id MSS_DEBUG_CHECK(hdl != MSS_SEMA_INVALID_HDL); // turn running task id into bit position task_bit = mss_bitpos_to_bit[mss_running_task_id]; MSS_ENTER_CRITICAL_SECTION(int_flag); // check if semaphore is available if(hdl->value > 0) { // check if calling task hasn't locked the semaphore before if(!(hdl->signaling_tasks & task_bit)) { // decrement semaphore value hdl->value--; // set the corresponding task bit in the signaling task list hdl->signaling_tasks |= task_bit; // return TRUE as locking semaphore succeeds ret = true; } } else { // semaphore is not available, put task into waiting list if necessary hdl->waiting_tasks |= task_bit; } MSS_LEAVE_CRITICAL_SECTION(int_flag); return ret; } /**************************************************************************//** * * mss_sema_post * * @brief increment (unlock/up) a semaphore. The waiting task with the * highest priority will be activated upon incrementing the * semaphore value * * @param[in] hdl semaphore handle * * @return - * ******************************************************************************/ void mss_sema_post(mss_sema_t hdl) { uint16_t task_bit; uint8_t waiting_task_id; mss_int_flag_t int_flag; // check task id MSS_DEBUG_CHECK(hdl != MSS_SEMA_INVALID_HDL); MSS_ENTER_CRITICAL_SECTION(int_flag); // turn running task id into bit position task_bit = mss_bitpos_to_bit[mss_running_task_id]; // check if task has locked the semaphore before if(hdl->signaling_tasks & task_bit) { // increment the semaphore value hdl->value++; // remove task from the signaling list hdl->signaling_tasks &= ~task_bit; // check if there is waiting task(s) if(hdl->waiting_tasks) { // search the task with highest priority in the waiting task list waiting_task_id = mss_get_highest_prio_task(hdl->waiting_tasks); // activate the waiting task with highest priority mss_activate_task_int(waiting_task_id); // remove task from waiting task list hdl->waiting_tasks &= ~mss_bitpos_to_bit[waiting_task_id]; } } MSS_LEAVE_CRITICAL_SECTION(int_flag); } //***************************************************************************** // Internal functions //***************************************************************************** #endif /* (MSS_TASK_USE_SEMA == TRUE) */
// // OdinUICollectionViewLayout.h // OdinShareSDKUI // // Created by nathan on 2019/4/22. // Copyright © 2019 Odin. All rights reserved. // #import <UIKit/UIKit.h> #import "OdinUIShareSheetConfiguration.h" NS_ASSUME_NONNULL_BEGIN @interface OdinUICollectionViewLayout : UICollectionViewLayout @property (assign, nonatomic) OdinUIItemAlignment alignment; @property (assign, nonatomic) NSInteger rowCount; @property (assign, nonatomic) NSInteger columnCount; @property (assign, nonatomic) CGFloat horizontalSpacing; @property (assign, nonatomic) CGFloat verticalSpacing; @property (assign, nonatomic) CGFloat itemWidth; @property (assign, nonatomic) CGFloat itemHeight; @end NS_ASSUME_NONNULL_END
<reponame>leleonardzhang/uDNN-tf2msp #include "layers.h" #pragma PERSISTENT(PADDING_BUFFER) static dtype PADDING_BUFFER[PADDING_BUFFER_LENGTH] = {0}; #pragma PERSISTENT(FILTER_BUFFER) static dtype FILTER_BUFFER[FILTER_BUFFER_LENGTH] = {0}; matrix *dense(matrix *result, matrix *input, matrix *W, matrix *b, int16_t (*activation)(int16_t, uint16_t), uint16_t precision) { /** * Implementation of a dense feed-forward layer using matrix operations. */ result = matrix_multiply(result, W, input, precision); // Only add bias if given if (b != NULL_PTR) { result = matrix_add(result, result, b); } result = apply_elementwise(result, result, activation, precision); return result; } matrix *maxpooling(matrix* result, matrix *input, uint16_t pool_numRows, uint16_t pool_numCols){ /** * Implementation of maxpooling layer */ uint16_t result_numRows = input->numRows / pool_numRows; uint16_t result_numCols = input->numCols / pool_numCols; uint16_t i, j, x, y, kx, ky, input_offset, result_offset; int16_t max; for (i = 0; i < result_numRows; i ++){ for (j = 0; j < result_numCols; j ++){ // (i, j) is the coordinate of each element after maxpooling // (x, y) is the coordinate of top-left element among all corresponding points in the original input matrix x = i * pool_numRows; y = j * pool_numCols; max = -32768; for (kx = 0; kx < pool_numRows; kx ++){ for (ky = 0; ky < pool_numCols; ky ++){ // traverse the entire sub-block that are related to this pooling input_offset = (x + kx) * input->numCols + (y + ky); if (max < input->data[input_offset]){ max = input->data[input_offset]; // if a bigger number found, update max } } } result_offset = i * result_numCols + j; result->data[result_offset] = max; } } return result; } matrix *maxpooling_filters(matrix *result, matrix *input, uint16_t numFilters, uint16_t pool_numRows, uint16_t pool_numCols){ /** * Iteration for each filter * one conv2d layer usually has multiple filters, we do maxpooling one by one */ uint16_t i, filter_offset, result_offset, filter_length = input->numRows * input->numCols, result_length = result->numRows * result->numCols; int16_t *filterData = input->data, *resultData = result->data; for (i = numFilters; i > 0; i --){ filter_offset = (i - 1) * filter_length; result_offset = (i - 1) * result_length; input->data = filterData + filter_offset; result->data = resultData + result_offset; /* process one filter at a time */ maxpooling(result, input, pool_numRows, pool_numCols); } return result; } matrix *flatten(matrix* result, matrix *input, uint16_t num_filter){ /** * Implementation of flatten layer for CNN * the result of conv2d_maxpooling or conv2d_filter is saved in the order of filter by filter * however, the flatten result should be in this following way according to Tensorflow * f0[0], f1[0], ..., fn[0], f0[1], f1[1], ..., fn[1], ..., f0[n], f1[n], fn[n] */ uint16_t i, j, input_offset, result_offset = 0; uint16_t filter_length; filter_length = input->numCols * input->numRows; for (i = 0; i < filter_length; i ++ ){ for (j = 0; j < num_filter; j ++){ input_offset = i + j * filter_length; // get the ith element of the jth filter result->data[result_offset++] = input->data[input_offset]; // append it to result result->data[result_offset++] = 0; // for LEA, we have to append 0 to each number } } return result; } matrix *padding_same(matrix *result, matrix *input, matrix *filter, uint16_t stride_numRows, uint16_t stride_numCols) { uint16_t input_numRows = input->numRows, input_numCols = input->numCols, filter_numRows = filter->numRows, filter_numCols = filter->numCols; uint16_t pad_along_numRows, pad_along_numCols, i, input_offset, padding_offset; if (input_numRows % stride_numRows) { pad_along_numRows = filter_numRows - input_numRows % stride_numRows; } else { pad_along_numRows = filter_numRows - stride_numRows; } if (input_numCols % stride_numCols) { pad_along_numCols = filter_numCols - input_numCols % stride_numCols; } else { pad_along_numCols = filter_numCols - stride_numCols; } result->numRows = input->numRows + pad_along_numRows; result->numCols = input->numCols + pad_along_numCols; memset(PADDING_BUFFER, 0, result->numRows * result->numCols * sizeof(dtype)); for (i = 0; i < input_numRows; i ++) { input_offset = i * input_numCols; padding_offset = ((pad_along_numRows >> 1) + i) * result->numCols + (pad_along_numCols >> 1); memcpy(PADDING_BUFFER + padding_offset, input->data + input_offset, sizeof(dtype) * input_numCols); } // memcpy(result->data = PADDING_BUFFER, result->numRows * result->numCols * sizeof(dtype)); result->data = PADDING_BUFFER; return result; } matrix *filter_simple(matrix *result, matrix *input, matrix *filter, uint16_t precision, uint16_t stride_numRows, uint16_t stride_numCols){ /** * Implementation of one filter of a conv2d layer */ uint16_t input_numRows = input->numRows; uint16_t input_numCols = input->numCols; uint16_t filter_numRows = filter->numRows; uint16_t filter_numCols = filter->numCols; uint16_t i, j, m, n, input_offset, filter_offset, result_offset = 0; int16_t mult_result, sum = 0, mult1, mult2; for (i = 0; i <= input_numRows - filter_numRows; i += stride_numRows){ for (j = 0; j <= input_numCols - filter_numCols; j += stride_numCols){ // (i,j) is the coordinate of the top-left element of the moving filter sum = 0; for (m = i; m < i + filter_numRows; m ++){ for (n = j; n < j + filter_numCols; n ++){ // calculate element-wise matrix product between the filter and corresponding section in the input image input_offset = m * input_numRows + n; filter_offset = (m - i) * filter_numCols + (n - j); mult1 = input->data[input_offset]; mult2 = filter->data[filter_offset]; mult_result = fp_mul(mult1, mult2, precision); sum += mult_result; // ATTENTION *** potential overflow issue *** } } result->data[result_offset ++] = sum; // add bias } } return result; } matrix *filters_sum(matrix *result, matrix *input, matrix *filter, uint16_t numChannels, int16_t b, int16_t (*activation)(int16_t, uint16_t), uint16_t precision, uint16_t stride_numRows, uint16_t stride_numCols, uint16_t padding){ int16_t *filter_head = filter->data; int16_t *input_head = input->data; uint16_t i, result_length = result->numRows * result->numCols, input_length = input->numRows * input->numCols, filter_length = filter->numRows * filter->numCols, input_numRows = input->numRows, input_numCols = input->numCols; matrix temp = {FILTER_BUFFER, result->numRows, result->numCols}; memset(result->data, 0, result_length * sizeof(dtype)); for (i = numChannels; i > 0; i --){ input->data = input_head + input_length * (i - 1); filter->data = filter_head + filter_length * (i - 1); if (padding == 1) { padding_same(input, input, filter, stride_numRows, stride_numCols); } #ifdef IS_MSP filter_LEA(&temp, input, filter, precision, stride_numRows, stride_numCols); #else filter_simple(&temp, input, filter, precision, stride_numRows, stride_numCols); #endif matrix_add(result, result, &temp); input->numRows = input_numRows; input->numCols = input_numCols; input->data = input_head; } for (i = result_length; i > 0; i --){ result->data[i - 1] = result->data[i - 1] + b; } result = apply_elementwise(result, result, activation, precision); return result; } matrix *conv2d(matrix *result, matrix *input, matrix *filter, uint16_t numFilters, uint16_t numChannels, int16_t *b, int16_t (*activation)(int16_t, uint16_t), uint16_t precision, uint16_t stride_numRows, uint16_t stride_numCols, uint16_t padding){ uint16_t i, result_length = result->numRows * result->numCols, filter_length = filter->numRows * filter->numCols * numChannels; int16_t *filter_head = filter->data, *result_head = result->data; for (i = numFilters; i > 0; i --){ filter->data = filter_head + (i - 1) * filter_length; result->data = result_head + (i - 1) * result_length; filters_sum(result, input, filter, numChannels, b[i - 1], activation, precision, stride_numRows, stride_numCols, padding); } return result; } matrix *apply_leakyrelu(matrix *result, matrix *input, uint16_t precision){ result = apply_elementwise(result, input, &fp_leaky_relu, precision); return result; }
#include "zai_sapi_extension.h" // clang-format off static const zend_module_entry zai_sapi_extension_orig = { STANDARD_MODULE_HEADER, "ZAI SAPI extension", NULL, // Functions NULL, // MINIT NULL, // MSHUTDOWN NULL, // RINIT NULL, // RSHUTDOWN NULL, // Info function PHP_VERSION, STANDARD_MODULE_PROPERTIES }; // clang-format on zend_module_entry zai_sapi_extension; void zai_sapi_reset_extension_global(void) { zai_sapi_extension = zai_sapi_extension_orig; }
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <omp.h> int main(void) { int a = 2, b = 3, c = 4; /* Aici variabilele a = 2, b = 3 si c = 4 au aceste valori pe thread-ul MASTER. De ce, avand in vedere ca in portiunea paralela intra si thread-ul 0 (MASTER), la final cand afisez variabilele a si b raman valorile 2 si 3 de la inceput? Inteleg ca valoarea c din 4 devine 3 pentru ca este partajata, dar daca a = 1 si b = 2 pentru fiecare thread in parte, la final la printf cand afisez valorile a si b ale thread-ului MASTER, de ce nu se afiseaza 1 si 2? */ printf("Master thread id: %d\n", omp_get_thread_num()); #pragma omp parallel private(a, b) shared(c) { printf("Thread id: %d\n", omp_get_thread_num()); a = 1; b = 2; c = a + b; } printf("[%d] %d %d %d\n", omp_get_thread_num(), a, b, c); return 0; }
#ifndef GAMEASSETMANAGER_H #define GAMEASSETMANAGER_H #include <memory> #include <vector> #include <string> #include <utility> #include <fstream> #include <iostream> #include <GL/gl.h> #include "common.h" #include "GameAsset.h" /** * GameAssetManager is a container for GameAssets. It also provides utility * functions to to create a simple OpenGL program that can be used to draw a * simple GameAsset. */ class GameAssetManager { public: explicit GameAssetManager(ApplicationMode); // constructor virtual ~GameAssetManager(); GameAssetManager(GameAssetManager const&); // copy constructor GameAssetManager(GameAssetManager const&&); // move constructor void operator=(GameAssetManager const&); // assignment void AddAsset(std::shared_ptr<GameAsset>); void Draw(); private: GLuint CreateGLProgram(std::string &, std::string &); GLuint CreateGLESShader(GLenum, std::string &); // As this is private and we're writing to the GPU, we will use raw pointers. std::pair<GLchar *, GLint> ReadShader(std::string &); // The internal scene graph is a simple list. std::vector<std::shared_ptr<GameAsset>> draw_list; GLuint program_token; }; #endif // GAMEASSETMANAGER_H
<filename>bePhysics/header/bePhysics/beRigidShape.h /*****************************************************/ /* breeze Engine Physics Module (c) <NAME> 2011 */ /*****************************************************/ #pragma once #ifndef BE_PHYSICS_RIGIDSHAPE #define BE_PHYSICS_RIGIDSHAPE #include "bePhysics.h" #include "beAssembledShape.h" #include "beMaterial.h" #include <beCore/beShared.h> #include <beCore/beManagedResource.h> #include <beCore/beComponent.h> #include <beCore/beReflectedComponent.h> #include <beCore/beMany.h> namespace bePhysics { class Material; class AssembledShape; class RigidShapeCache; using beCore::PropertyDesc; /// Mesh compound. class RigidShape : public beCore::Resource, public beCore::OptionalPropertyProvider<beCore::ReflectedComponent>, public beCore::ManagedResource<RigidShapeCache>, public beCore::HotResource<RigidShape>, public Implementation { LEAN_SHARED_INTERFACE_BEHAVIOR(RigidShape) public: /// Subset. struct Subset { utf8_string Name; ///< Subset name. beCore::Range<uint4> Shapes; ///< Subset shape range. lean::resource_ptr<Material> Material; ///< Subset material. }; typedef beCore::Range<ShapeHandle const*> ShapeRange; typedef beCore::Range<Subset const*> SubsetRange; /// Gets all shapes. virtual ShapeRange GetShapes() const = 0; /// Gets all subsets. virtual SubsetRange GetSubsets() const = 0; /// Adds the given subset. virtual uint4 AddSubset(const lean::utf8_ntri &name, Material *pMaterial = nullptr) = 0; /// Sets the material for the given subset. virtual void SetMaterial(uint4 subsetIdx, Material *pMaterial) = 0; /// Removes the given subset. virtual void RemoveSubset(uint4 subsetIdx) = 0; /// Adds the given shape. virtual uint4 AddShape(uint4 subsetIdx, ShapeHandle shape) = 0; /// Removes the n-th shape. virtual void RemoveShape(uint4 shapeIdx) = 0; /// Sets the source shape. virtual void SetSource(const AssembledShape *pSource) = 0; /// Gets the source shape. virtual const AssembledShape* GetSource() const = 0; /// Gets the type. BE_PHYSICS_API static const beCore::ComponentType* GetComponentType(); /// Gets the type. BE_PHYSICS_API const beCore::ComponentType* GetType() const; }; /// Creates a rigid shape. BE_PHYSICS_API lean::resource_ptr<RigidShape, lean::critical_ref> CreateRigidShape(); /// Adds all shapes in the given assembled shape to the given rigid shape using the given material. BE_PHYSICS_API lean::resource_ptr<RigidShape, lean::critical_ref> ToRigidShape( const AssembledShape &src, Material *pMaterial, bool bStoreSource); /// Adds all shapes in the given assembled shape to the given rigid shape using the given material. BE_PHYSICS_API void ToRigidShape(RigidShape &dest, const AssembledShape &src, Material *pMaterial, bool bStoreSource); /// Fills in missing materials using the given material. BE_PHYSICS_API void FillRigidShape(RigidShape &shape, Material *material); /// Transfers materials from one rigid shape to another, matching subset names. BE_PHYSICS_API bool TransferMaterials(const RigidShape &source, RigidShape &dest); } // namespace #endif
<filename>src/rotate_basis.c #include "rotate_basis.h" void get_sym_op_reciprocalspace(dcomplex * sym_op, double lattice[3][3], wannorb * orb_info, int norb, int isym_in_doublegp, double rotation[3][3],double translation[3], int TR, double rot_kd[3][3], vector kpt, int flag_soc) { // // trans from ccao's fortran code // // This function defines the rotation in the Hilbert space // <W'|R|W> // For each Wannier orbital, we indeed have 4 labels: // |W> = | Rv, tau, l, m> // where Rv is the lattice vector // tau is the atomic position // l is the angular momentum // m indexes the actual orbital (mostly cubic harmonics) // Therefore // <Rv', tau', l, m' | R | Rv, tau, l, m> is the matrix element // lm part rotation matrix is exacly what we had for Ylm or cubic harmonics // <Rv', tau' | R | Rv, tau> is a delta function // For real-space rotation, above is just fine // However, here we rotate |kv, tau, l, m> = \sum(Rv) exp(-i (kv*Rv)) | Rv, tau, l, m> // under rotation, kv -> kv', Rv+tau -> Rv'+tau' // notice that Rv' and R*Rv can differ by a lattice vector Rv", Rv'=R*Rv+R" // thus under rotation, exp(-i (kv*Rv))=exp(-i (kv'*R*Rv))=exp(-i (kv'*Rv'))*exp(i(kv'*Rv")) // Therefore // \sum(Rv') exp(-i (kv'*Rv')) | Rv', tau', l, m> // =\sum(Rv") exp(-i (kv'*Rv")) *exp(-i (kv'* R*Rv)) |Rv', tau', l, m> // // isym_in_doublegp : index of symm in double group, range [-nsymm, nsymm-1], nsymm is num of symm in single-valued group // if( fabs(translation[0]) > 1E-3 || fabs(translation[1]) > 1E-3 || fabs(translation[2]) > 1E-3){ // fprintf(stderr, "Warning, non symmorphic symmetry detected\n"); // } int i,j,k; int ii,jj,kk; int io,jo; dcomplex * orb_rot[MAX_L+1]; dcomplex * s_rot; double rot_axis[3]; double rot_angle; int inv_flag; double inv_rot[3][3]; vector kpt_roted; vector rvec_supp; // tau' = rot*tau - rvec_supp vector tau1,tau2,tau2_roted, tau2_symed; vector translation_v; vector inv_trans; //vector translation_kd_v; int l, N; int mr1,mr2; int ms1,ms2; init_vector(&translation_v, translation[0], translation[1], translation[2]); //init_vector(&translation_kd_v, translation_kd[0], translation_kd[1], translation_kd[2]); matrix3x3_inverse(inv_rot, rotation); inv_trans = vector_rotate(translation_v, inv_rot); inv_trans.x *= -1; inv_trans.y *= -1; inv_trans.z *= -1; get_axis_angle_of_rotation(rot_axis, &rot_angle, &inv_flag, rotation, lattice); if(flag_soc == 1) { if(isym_in_doublegp < 0) { rot_angle += 2*PI; // element introduced by double group } } //rot_angle *= -1; // proper rotation or inverse rotation //get s_rot with input (axis,angle,inv) s_rot = (dcomplex *)malloc(sizeof(dcomplex)*2*2); rotate_spinor(s_rot, rot_axis, rot_angle, inv_flag); if(flag_soc == 0){ s_rot[0] = s_rot[3] = 1; s_rot[1] = s_rot[2] = 0; } //get orb_rot with input (l,axis,angle,inv) for (l=0;l<=3;l++){ N = 2*l + 1; orb_rot[l] = (dcomplex *)malloc(sizeof(dcomplex)*N*N); rotate_cubic( orb_rot[l], l, rot_axis, rot_angle, inv_flag); } kpt_roted = vector_rotate(kpt, rot_kd); if(TR==1){ kpt_roted = vector_scale(-1.0, kpt_roted); } for(io=0;io<norb;io++){ for(jo=0;jo<norb;jo++){ //if( ! kpt_equivalent(kpt_roted, kpt) ){ // sym_op[io*norb+jo] = 0; // continue; //} if( (orb_info+io)->l != (orb_info+jo)->l ){ sym_op[io*norb+jo] = 0; continue; } tau1 = (orb_info+io)->site; tau2 = (orb_info+jo)->site; tau2_roted = vector_rotate(tau2, rotation); tau2_roted = vector_add( tau2_roted, translation_v); //tau2_roted = vector_rotate(tau2, inv_rot); //tau2_roted = vector_add( tau2_roted, inv_trans); getrvec_and_site(&rvec_supp, &tau2_symed, tau2_roted, orb_info, norb, lattice); if( ! equale(tau1, tau2_symed, 1E-5)){ sym_op[io*norb+jo] = 0; continue; } l = (orb_info+jo)->l; mr1 = (orb_info+io)->mr; mr2 = (orb_info+jo)->mr; ms1 = (orb_info+io)->ms; ms2 = (orb_info+jo)->ms; //sym_op[io*norb+jo] =cexp(2*PI*cmplx_i * (dot_product(kpt_roted, vector_sub(rvec_supp,translation_v))))* //sym_op[io*norb+jo] =cexp(-2*PI*cmplx_i * (dot_product(kpt_roted, rvec_supp)))* //sym_op[io*norb+jo] =cexp(-2*PI*cmplx_i * (dot_product(kpt_roted, vector_add(rvec_supp,translation_v))))* sym_op[io*norb+jo] =cexp(-2*PI*cmplx_i * (dot_product(kpt_roted, vector_sub(rvec_supp,translation_v))))* (orb_rot[l][(2*l+1)*(mr1-1) + mr2-1]) * (s_rot[2*ms1 + ms2]); sym_op[io*norb+jo] = conj(sym_op[io*norb+jo]); } } }
<gh_stars>100-1000 /* * Copyright © 2009 CNRS * Copyright © 2009-2010 inria. All rights reserved. * Copyright © 2009 <NAME> * Copyright © 2009-2011 Cisco Systems, Inc. All rights reserved. * See COPYING in top-level directory. */ #include "hwloc.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> /* check hwloc_bitmap_singlify() */ int main(void) { hwloc_bitmap_t orig, expected; orig = hwloc_bitmap_alloc(); expected = hwloc_bitmap_alloc(); /* empty set gives empty set */ hwloc_bitmap_singlify(orig); assert(hwloc_bitmap_iszero(orig)); /* full set gives first bit only */ hwloc_bitmap_fill(orig); hwloc_bitmap_singlify(orig); hwloc_bitmap_zero(expected); hwloc_bitmap_set(expected, 0); assert(hwloc_bitmap_isequal(orig, expected)); assert(!hwloc_bitmap_compare(orig, expected)); /* actual non-trivial set */ hwloc_bitmap_zero(orig); hwloc_bitmap_set(orig, 45); hwloc_bitmap_set(orig, 46); hwloc_bitmap_set(orig, 517); hwloc_bitmap_singlify(orig); hwloc_bitmap_zero(expected); hwloc_bitmap_set(expected, 45); assert(hwloc_bitmap_isequal(orig, expected)); assert(!hwloc_bitmap_compare(orig, expected)); hwloc_bitmap_free(orig); hwloc_bitmap_free(expected); return 0; }
<reponame>t7saeki/ndmansfield #ifndef _RANDOM_GEN_H #define _RANDOM_GEN_H #include <cassert> // defines assert(), optional debugging utility. #include <cstdlib> // needed for random-number generation // (specifically getenv() and seed48()) #include <ctime> // required for "struct timezone" and // "gettimeofday()" used to set the randomseed #include <cmath> // defines exp(), log(), sqrt(), cos(), sin() #include <iostream> #ifndef M_PI #define M_PI (2.0*asin(1.0)) // A work around for MinGW or Cygwin #endif using namespace std; //RANDOM_INT(n) returns uniformly distributed integers ranging from 0 to n-1. //The maximum allowed value of "n" is 2^31 inline long RANDOM_INT(unsigned long n) { //assert(n < 2147483648-1); // Unnecessary? Probably...Check that n < 2^31-1 //return lrand48() % n; //Note: lrand48 returns a number between 0 and 2^31 return rand() % n; // A work around for MinGW or Cygwin } //RANDOM_REAL_0_1() returns uniformly distributed "Real" numbers over [0, 1) inline double RANDOM_REAL_0_1() { //return drand48(); //for some reason this is better than lrand48() / RAND_MAX return rand() / RAND_MAX; // A work around for MinGW or Cygwin } //RANDOM_GAUSSIAN() returns a random number in the range // (-infinity, +infinity) //with distrubition of P(x) proportional to exp( - x^2 / 2 ) // (the "standard normal distribution".) //The number should be Gaussian distributed, and have a variance, <x^2> = 1. inline double RANDOM_GAUSSIAN() { double u = RANDOM_REAL_0_1(); // generates a random number in the range [0,1) u = 1.0 - u; // After this command, u is in the range (0,1] // We want u>0 because log(u) not defined at 0 // The following line should generate r with a probability density of // P(r) proportional to r * exp(- r^2/2) double r = sqrt( - log (u) * 2.0 ); //cerr << "u=" << u << ", log(u)=" << log(u) << ", sqrt(-log(u))=" // << sqrt(-log(u)) << endl; // Now generate another random number between 0 and 2*pi double theta = (2.0*M_PI) * RANDOM_REAL_0_1(); // Convert from polar (r,theta) to cartesian coordinates (x,y) // The "x" and "y" values should both be Gaussian distributed. // (Probability density P(x) should be proportional to exp(-lambda x^2)) //double return_val = r*cos(theta); //cerr << " theta=" << theta << ", cos(theta)=" << cos(theta) // << ", r=" << r << ", r*cos(theta)=" << return_val << endl; return r * cos( theta ); } //RANDOM_GAUSSIAN() // RANDOM_EXPONENTIAL() returns a number in the range [0,infinity) // with an exponential probability distribution P(x) = exp(-x) // (Scale the final answer to get different decay rates. // P(x) = (1/K) exp(-K x)) inline double RANDOM_EXPONENTIAL() { double u = RANDOM_REAL_0_1(); // generates a random number in the range [0,1) u = 1.0 - u; // After this command, u is in the range (0,1] // We want u>0 because log(u) not defined at 0 return -log(u); } // RANDOM_INIT() // Invoke this function before calling anything else: // This function chooses the random-seed for the random // number generator based on the time. // This insures that the program will never reproduce exactly the same // results when run twice (unless run within 1 second of eachother). inline void RANDOM_INIT(long seed=-1) { time_t timer; struct tm y2k; double seconds; y2k.tm_hour = 0; y2k.tm_min = 0; y2k.tm_sec = 0; y2k.tm_year = 100; y2k.tm_mon = 0; y2k.tm_mday = 1; time(&timer); /* get current time; same as: timer = time(NULL) */ seconds = difftime(timer,mktime(&y2k)); if (seed < 0) { seed = static_cast<long>(floor(seconds)); } //srand48( seed ); srand(seed);// A work around for MinGW or Cygwin. } #endif //#ifndef _RANDOM_GEN_H
<filename>YeetLike/Include/libtcod/libtcod/console/printing.h /* libtcod * Copyright © 2008-2018 Jice and the libtcod contributers. * All rights reserved. * * libtcod 'The Doryen library' is a cross-platform C/C++ library for roguelike * developers. * Its source code is available from: * https://github.com/libtcod/libtcod * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * The name of copyright holder nor the names of its contributors may not * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef TCOD_CONSOLE_PRINTING_H_ #define TCOD_CONSOLE_PRINTING_H_ #include "../portability.h" #include "../console.h" #ifdef __cplusplus extern "C" { #endif TCOD_DEPRECATED("Use TCOD_console_printf instead.") TCODLIB_API void TCOD_console_print(TCOD_Console* con,int x, int y, const char *fmt, ...); TCOD_DEPRECATED("Use TCOD_console_printf_ex instead.") TCODLIB_API void TCOD_console_print_ex(TCOD_Console* con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); TCOD_DEPRECATED("Use TCOD_console_printf_rect instead.") TCODLIB_API int TCOD_console_print_rect(TCOD_Console* con,int x, int y, int w, int h, const char *fmt, ...); TCOD_DEPRECATED("Use TCOD_console_printf_rect_ex instead.") TCODLIB_API int TCOD_console_print_rect_ex(TCOD_Console* con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); TCODLIB_API int TCOD_console_get_height_rect(TCOD_Console* con,int x, int y, int w, int h, const char *fmt, ...); #ifndef NO_UNICODE TCOD_DEPRECATED("Use TCOD_console_printf instead.") TCODLIB_API void TCOD_console_print_utf(TCOD_Console* con,int x, int y, const wchar_t *fmt, ...); TCOD_DEPRECATED("Use TCOD_console_printf_ex instead.") TCODLIB_API void TCOD_console_print_ex_utf(TCOD_Console* con,int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...); TCOD_DEPRECATED("Use TCOD_console_printf_rect instead.") TCODLIB_API int TCOD_console_print_rect_utf(TCOD_Console* con,int x, int y, int w, int h, const wchar_t *fmt, ...); TCOD_DEPRECATED("Use TCOD_console_printf_rect_ex instead.") TCODLIB_API int TCOD_console_print_rect_ex_utf(TCOD_Console* con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const wchar_t *fmt, ...); TCODLIB_API int TCOD_console_get_height_rect_utf(TCOD_Console* con,int x, int y, int w, int h, const wchar_t *fmt, ...); #endif /* UTF-8 functions */ TCODLIB_API void TCOD_console_printf(TCOD_Console* con, int x, int y, const char *fmt, ...); TCODLIB_API void TCOD_console_printf_ex( TCOD_Console* con, int x, int y, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); TCODLIB_API int TCOD_console_printf_rect( TCOD_Console* con, int x, int y, int w, int h, const char *fmt, ...); TCODLIB_API int TCOD_console_printf_rect_ex( TCOD_Console* con,int x, int y, int w, int h, TCOD_bkgnd_flag_t flag, TCOD_alignment_t alignment, const char *fmt, ...); TCODLIB_API void TCOD_console_printf_frame(struct TCOD_Console *con, int x, int y, int w, int h, int empty, TCOD_bkgnd_flag_t flag, const char *fmt, ...); TCODLIB_API int TCOD_console_get_height_rect_fmt(struct TCOD_Console *con, int x, int y, int w, int h, const char *fmt, ...); /* Private internal functions. */ int TCOD_console_print_internal_utf8_( TCOD_Console* con, int x, int y, int max_width, int max_height, TCOD_bkgnd_flag_t flag, TCOD_alignment_t align, const unsigned char *string, int can_split, int count_only); #ifdef __cplusplus } #endif #endif /* TCOD_CONSOLE_PRINTING_H_ */
<gh_stars>1-10 // // YKAddressDetailCell.h // YK // // Created by LXL on 2017/11/16. // Copyright © 2017年 YK. All rights reserved. // #import <UIKit/UIKit.h> #import "YKAddress.h" @interface YKAddressDetailCell : UITableViewCell @property (nonatomic,strong)YKAddress *address; @property (nonatomic,copy)void (^selectDefaultBlock)(void); @property (nonatomic,copy)void (^editBlock)(YKAddress *address); @property (nonatomic,copy)void (^deleteBlock)(void); @end
#include <math.h> #include <stdio.h> const double K = 7.8e9; const int n0 = 27; const double actual[] = { 27, 27, 27, 44, 44, 59, 59, 59, 59, 59, 59, 59, 59, 60, 60, 61, 61, 66, 83, 219, 239, 392, 534, 631, 897, 1350, 2023, 2820, 4587, 6067, 7823, 9826, 11946, 14554, 17372, 20615, 24522, 28273, 31491, 34933, 37552, 40540, 43105, 45177, 60328, 64543, 67103, 69265, 71332, 73327, 75191, 75723, 76719, 77804, 78812, 79339, 80132, 80995, 82101, 83365, 85203, 87024, 89068, 90664, 93077, 95316, 98172, 102133, 105824, 109695, 114232, 118610, 125497, 133852, 143227, 151367, 167418, 180096, 194836, 213150, 242364, 271106, 305117, 338133, 377918, 416845, 468049, 527767, 591704, 656866, 715353, 777796, 851308, 928436, 1000249, 1082054, 1174652 }; const size_t actual_size = sizeof(actual) / sizeof(double); double f(double r) { double sq = 0; size_t i; for (i = 0; i < actual_size; ++i) { double eri = exp(r * i); double guess = (n0 * eri) / (1 + n0 * (eri - 1) / K); double diff = guess - actual[i]; sq += diff * diff; } return sq; } double solve(double (*fn)(double), double guess, double epsilon) { double delta, f0, factor; for (delta = guess ? guess : 1, f0 = fn(guess), factor = 2; delta > epsilon && guess != guess - delta; delta *= factor) { double nf = (*fn)(guess - delta); if (nf < f0) { f0 = nf; guess -= delta; } else { nf = fn(guess + delta); if (nf < f0) { f0 = nf; guess += delta; } else { factor = 0.5; } } } return guess; } double solve_default(double (*fn)(double)) { return solve(fn, 0.5, 0); } int main() { double r = solve_default(f); double R0 = exp(12 * r); printf("r = %f, R0 = %f\n", r, R0); return 0; }
/***************************************************************************//** * \file cy_syspm.c * \version 2.10 * * This driver provides the source code for API power management. * ******************************************************************************** * \copyright * Copyright 2016-2018, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #include "cy_syspm.h" /******************************************************************************* * Internal Variables *******************************************************************************/ static cy_stc_syspm_callback_t* callbackRoot = NULL; static uint32_t curRegisteredCallbacks = 0U; #if(0u != CY_CPU_CORTEX_M4) static bool wasEventSent = false; #endif /* (0u != CY_CPU_CORTEX_M4) */ /******************************************************************************* * Internal Functions *******************************************************************************/ #ifdef CY_IP_MXUDB static void SaveRegisters(cy_stc_syspm_backup_regs_t *regs); static void RestoreRegisters(cy_stc_syspm_backup_regs_t const *regs); #endif /* CY_IP_MXUDB */ static void EnterDeepSleep(cy_en_syspm_waitfor_t waitFor); static void SetReadMarginTrimUlp(void); static void SetReadMarginTrimLp(void); static void SetWriteAssistTrimUlp(void); static void SetWriteAssistTrimLp(void); static void SetVoltageBitForFlash(void); static void ClearVoltageBitForFlash(void); #if defined(CY_DEVICE_PSOC6ABLE2) && !defined(CY_PSOC6ABLE2_REV_0A_SUPPORT_DISABLE) static void Cy_EnterDeepSleep(cy_en_syspm_waitfor_t waitFor); #endif /* defined(CY_DEVICE_PSOC6ABLE2) && !defined(CY_PSOC6ABLE2_REV_0A_SUPPORT_DISABLE) */ /******************************************************************************* * Internal Defines *******************************************************************************/ #if defined(CY_DEVICE_PSOC6ABLE2) && !defined(CY_PSOC6ABLE2_REV_0A_SUPPORT_DISABLE) /** The internal define for clock divider */ #define SYSPM_CLK_DIVIDER (9U) /* Mask for the fast clock divider value */ #define SYSPM_FAST_CLK_DIV_Msk (0xFF000000UL) /* Position for the fast clock divider value */ #define SYSPM_FAST_CLK_DIV_Pos (24UL) /* Mask for the slow clock divider value */ #define SYSPM_SLOW_CLK_DIV_Msk (0x00FF0000UL) /* Position for the slow clock divider value */ #define SYSPM_SLOW_CLK_DIV_Pos (16UL) #if(0u != CY_CPU_CORTEX_M4) #define CUR_CORE_DP_MASK (0x01UL) #define OTHER_CORE_DP_MASK (0x02UL) #else #define CUR_CORE_DP_MASK (0x02UL) #define OTHER_CORE_DP_MASK (0x01UL) #endif #endif /* defined(CY_DEVICE_PSOC6ABLE2) && !defined(CY_PSOC6ABLE2_REV_0A_SUPPORT_DISABLE) */ /* Redefine for sflash region */ #define DELAY_DONE_FLAG FLASHC /* Slow control register */ #define TST_DDFT_SLOW_CTL_REG (*(volatile uint32_t *) 0x40260108U) /* Slow output register */ #define CLK_OUTPUT_SLOW_REG (*(volatile uint32_t *) 0x40260518U) /* Fast control register */ #define TST_DDFT_FAST_CTL_REG (*(volatile uint32_t *) 0x40260104U) /* Counter register */ #define CLK_CAL_CNT1_REG (*(volatile uint32_t *) 0x4026051CU) #ifdef CY_IP_MXUDB /* The UDB placement on MMIO slave level */ #define PERI_UDB_SLAVE_ENABLED ((uint32_t) (1UL << CY_MMIO_UDB_SLAVE_NR)) #endif /* CY_IP_MXUDB */ /** The definition for the delay of the LDO after its output * voltage is changed */ #define LDO_STABILIZATION_DELAY_US (9U) /* Define for the IPC structure used by syspm driver */ #define SYSPM_IPC_STC IPC_STRUCT7 /** Define to indicate that a 10 us delay is needed */ #define NEED_DELAY (0x0U) /** Define to set the IMO to count a 10 us delay after exiting Deep Sleep */ #define TST_DDFT_SLOW_CTL_MASK (0x00001F1EU) /** Slow output register */ #define CLK_OUTPUT_SLOW_MASK (0x06U) /** Slow control register */ #define TST_DDFT_FAST_CTL_MASK (62U) /** Load value for the timer to count delay after exiting Deep Sleep */ #define IMO_10US_DELAY (68U) /** Define to indicate that the clock is finished counting */ #define CLK_CAL_CNT1_DONE ((uint32_t) ((uint32_t) 1U << CLK_CAL_CNT1_DONE_POS)) /** Define to indicate that the clock is finished counting */ #define CLK_CAL_CNT1_DONE_POS (31U) /** Define to indicate that a 10 us delay was done after exiting Deep Sleep */ #define DELAY_DONE (0xAAAAAAAAU) /** Define for transitional 0.95 V for the LDO regulator */ #define LDO_OUT_VOLTAGE_0_95V (0x0BU) /** Define for transitional 1.1 V for the LDO regulator */ #define LDO_OUT_VOLTAGE_1_1V (0x17U) /** Define for transitional 1.15 V for the LDO regulator */ #define LDO_OUT_VOLTAGE_1_15V (0x1BU) #if(0u != SRSS_BUCKCTL_PRESENT) /** Define for transitional 0.95 V for buck regulator */ #define BUCK_OUT1_VOLTAGE_0_95V (3U) #endif /* (0u != SRSS_BUCKCTL_PRESENT) */ /* These defines will be removed and SFLASH registers used instead */ /** Trim define for ROM in LP mode */ #define CPUSS_TRIM_ROM_LP (0x00000013U) /** Trim define for RAM in LP mode */ #define CPUSS_TRIM_RAM_LP (0x00004013U) /** Trim define for ROM in ULP mode */ #define CPUSS_TRIM_ROM_ULP (0x00000012U) /** Trim define for RAM in ULP mode */ #define CPUSS_TRIM_RAM_ULP (0x00006012U) /******************************************************************************* * Function Name: Cy_SysPm_ReadStatus ****************************************************************************//** * * Reads the status of the core(s). * * \return The current power mode. See \ref group_syspm_return_status. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_ReadStatus * *******************************************************************************/ uint32_t Cy_SysPm_ReadStatus(void) { uint32_t interruptState; uint32_t pmStatus = 0U; interruptState = Cy_SysLib_EnterCriticalSection(); #if(0u != CY_IP_M4CPUSS) /* Check whether CM4 is in Deep Sleep mode*/ if((0U != _FLD2VAL(CPUSS_CM4_STATUS_SLEEPING, CPUSS->CM4_STATUS)) && (0U != _FLD2VAL(CPUSS_CM4_STATUS_SLEEPDEEP, CPUSS->CM4_STATUS))) { pmStatus |= CY_SYSPM_STATUS_CM4_DEEPSLEEP; } /* Check whether CM4 is in Sleep mode*/ else if(0U != _FLD2VAL(CPUSS_CM4_STATUS_SLEEPING, CPUSS->CM4_STATUS)) { pmStatus |= CY_SYSPM_STATUS_CM4_SLEEP; } else { pmStatus |= CY_SYSPM_STATUS_CM4_ACTIVE; } #endif /* (0u != CY_IP_M4CPUSS) */ /* Check whether CM0p is in Deep Sleep mode*/ if((0U != _FLD2VAL(CPUSS_CM0_STATUS_SLEEPING, CPUSS->CM0_STATUS)) && (0U != _FLD2VAL(CPUSS_CM0_STATUS_SLEEPDEEP, CPUSS->CM0_STATUS))) { pmStatus |= (uint32_t) CY_SYSPM_STATUS_CM0_DEEPSLEEP; } /* Check whether CM0p is in Sleep mode*/ else if (0U != _FLD2VAL(CPUSS_CM0_STATUS_SLEEPING, CPUSS->CM0_STATUS)) { pmStatus |= CY_SYSPM_STATUS_CM0_SLEEP; } else { pmStatus |= CY_SYSPM_STATUS_CM0_ACTIVE; } /* Check whether the device is in Low Power mode by reading * the Active Reference status */ if(0U != (_FLD2VAL(SRSS_PWR_CTL_ACT_REF_DIS, SRSS->PWR_CTL))) { pmStatus |= CY_SYSPM_STATUS_SYSTEM_LOWPOWER; } Cy_SysLib_ExitCriticalSection(interruptState); return(pmStatus); } /******************************************************************************* * Function Name: Cy_SysPm_Sleep ****************************************************************************//** * * Sets a CPU core to Sleep mode. * * Puts the core into Sleep power mode, if none of callback functions were * registered. * * For more details about switching into Sleep power mode and debug, * refer to the device TRM. * * If at least one callback function with the CY_SYSPM_SLEEP type was registered, * the next algorithm is executed: * Prior to entering Sleep mode, all callback functions of the CY_SYSPM_SLEEP * type with the CY_SYSPM_CHECK_READY parameter are called. This allows the driver * to signal whether it is ready to enter the Low Power mode. If any of the * callbacks of the CY_SYSPM_SLEEP type with the CY_SYSPM_CHECK_READY parameter * returns CY_SYSPM_FAIL, the remaining callback of the CY_SYSPM_SLEEP type with * the CY_SYSPM_CHECK_READY parameter calls are skipped. * After CY_SYSPM_FAIL, all the CY_SYSPM_SLEEP callbacks with * the CY_SYSPM_CHECK_FAIL parameter are executed. These are the callbacks * of the CY_SYSPM_SLEEP type with the CY_SYSPM_CHECK_READY * parameter that were previously executed before getting CY_SYSPM_FAIL. * The Sleep mode is not entered and the Cy_SysPm_Sleep() function returns * CY_SYSPM_FAIL. * * If all of the callbacks of the CY_SYSPM_SLEEP type with the * CY_SYSPM_CHECK_READY parameter calls return CY_SYSPM_SUCCESS, then all * callbacks of the CY_SYSPM_SLEEP type with the CY_SYSPM_CHECK_FAIL parameters * calls are skipped. Also, all callbacks of the CY_SYSPM_SLEEP type and * CY_SYSPM_BEFORE_TRANSITION parameter calls are executed, allowing the * peripherals to prepare for Sleep. The CPU then enters Sleep mode. * This is a CPU-centric power mode. This means that the CPU has entered Sleep * mode and its main clock is removed. It is identical to Active from a * peripheral point of view. Any enabled interrupt can cause a wakeup from * Sleep mode. * * After a wakeup from Sleep, all of the registered callbacks of the * CY_SYSPM_SLEEP type and with the CY_SYSPM_AFTER_TRANSITION parameter are * executed to return the peripherals to Active operation. The Cy_SysPm_Sleep() * function returns CY_SYSPM_SUCCESS. * No callbacks of the CY_SYSPM_SLEEP type with the CY_SYSPM_BEFORE_TRANSITION * parameter or callbacks of the CY_SYSPM_SLEEP type and * CY_SYSPM_AFTER_TRANSITION parameter callbacks are executed if Sleep mode * is not entered. * * \note The last callback that returned CY_SYSPM_FAIL is not executed with the * CY_SYSPM_CHECK_FAIL parameter because of the FAIL. * * The return values from executed callback functions with the * CY_SYSPM_CHECK_FAIL, CY_SYSPM_BEFORE_TRANSITION, and CY_SYSPM_AFTER_TRANSITION * modes are ignored. * * \ref cy_en_syspm_callback_mode_t, except the CY_SYSPM_CHECK_READY, are ignored * * \param waitFor Selects wait for action. See \ref cy_en_syspm_waitfor_t. * * \return * Entered status, see \ref cy_en_syspm_status_t. * * \sideeffect * This function clears the Event Register of CM4 core after wakeup from WFE. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_Sleep * *******************************************************************************/ cy_en_syspm_status_t Cy_SysPm_Sleep(cy_en_syspm_waitfor_t waitFor) { uint32_t interruptState; cy_en_syspm_status_t retVal = CY_SYSPM_SUCCESS; CY_ASSERT_L3(CY_SYSPM_IS_WAIT_FOR_VALID(waitFor)); /* Call registered callback functions with CY_SYSPM_CHECK_READY parameter */ if(0U != curRegisteredCallbacks) { retVal = Cy_SysPm_ExecuteCallback(CY_SYSPM_SLEEP, CY_SYSPM_CHECK_READY); } /* The device (core) can switch into the sleep power mode only when * all executed registered callback functions with the CY_SYSPM_CHECK_READY * parameter returned CY_SYSPM_SUCCESS. */ if(retVal == CY_SYSPM_SUCCESS) { /* Call the registered callback functions with * CY_SYSPM_BEFORE_TRANSITION parameter. The return value should be * CY_SYSPM_SUCCESS. */ interruptState = Cy_SysLib_EnterCriticalSection(); if(0U != curRegisteredCallbacks) { (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_SLEEP, CY_SYSPM_BEFORE_TRANSITION); } /* The CPU enters the Sleep power mode upon execution of WFI/WFE */ SCB->SCR = _CLR_SET_FLD32U((SCB->SCR), SCB_SCR_SLEEPDEEP, 0U); if(waitFor != CY_SYSPM_WAIT_FOR_EVENT) { __WFI(); } else { __WFE(); #if(0u != CY_CPU_CORTEX_M4) /* For the CM4 core, the WFE instructions are called twice. * The second WFE call clears the Event register of CM4 core. * Cypress ID #279077. */ if(wasEventSent) { __WFE(); } wasEventSent = true; #endif /* (0u != CY_CPU_CORTEX_M4) */ } Cy_SysLib_ExitCriticalSection(interruptState); /* Call the registered callback functions with the * CY_SYSPM_AFTER_TRANSITION parameter. The return value should be * CY_SYSPM_SUCCESS. */ if(0U != curRegisteredCallbacks) { (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_SLEEP, CY_SYSPM_AFTER_TRANSITION); } } else { /* Execute callback functions with the CY_SYSPM_CHECK_FAIL parameter to * undo everything done in the callback with the CY_SYSPM_CHECK_READY * parameter. The return value should be CY_SYSPM_SUCCESS. */ (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_SLEEP, CY_SYSPM_CHECK_FAIL); retVal = CY_SYSPM_FAIL; } return retVal; } /******************************************************************************* * Function Name: Cy_SysPm_DeepSleep ****************************************************************************//** * * Sets a CPU core to the Deep Sleep mode. * * Puts the core into the Deep Sleep power mode. Prior to entering the Deep Sleep * mode, all callbacks of the CY_SYSPM_DEEPSLEEP type with the * CY_SYSPM_CHECK_READY parameter registered callbacks are called, allowing the * driver to signal whether it is ready to enter the power mode. If any * CY_SYSPM_DEEPSLEEP type with the CY_SYSPM_CHECK_READY parameter call returns * CY_SYSPM_FAIL, the remaining callback CY_SYSPM_DEEPSLEEP type with the * CY_SYSPM_CHECK_READY parameter calls are skipped. After a CY_SYSPM_FAIL, all * of the callbacks of the CY_SYSPM_DEEPSLEEP type with the CY_SYSPM_CHECK_FAIL * parameter are executed that correspond to the callbacks with * CY_SYSPM_DEEPSLEEP type with CY_SYSPM_CHECK_READY parameter calls that * occurred up to the point of failure. * The Deep Sleep mode is not entered and the Cy_SysPm_DeepSleep() function * returns CY_SYSPM_FAIL. * * If all callbacks of the CY_SYSPM_DEEPSLEEP type with the CY_SYSPM_CHECK_READY * parameter calls return CY_SYSPM_SUCCESS, then all callbacks of the * CY_SYSPM_DEEPSLEEP type with the CY_SYSPM_CHECK_FAIL parameter calls are * skipped and all callbacks of the CY_SYSPM_DEEPSLEEP type with the * CY_SYSPM_BEFORE_TRANSITION parameter calls are executed, allowing the * peripherals to prepare for Deep Sleep. * The Deep Sleep mode is then entered. Any enabled interrupt can cause a wakeup * from the Deep Sleep mode. * * \note The last callback which returned CY_SYSPM_FAIL is not executed with the * CY_SYSPM_CHECK_FAIL parameter because of the FAIL. * * The return values from executed callback functions with the * CY_SYSPM_CHECK_FAIL, CY_SYSPM_BEFORE_TRANSITION, and CY_SYSPM_AFTER_TRANSITION * modes are ignored. * * If the firmware attempts to enter this mode before the system is ready (that * is, when PWR_CONTROL.LPM_READY = 0), then the device will go into the (LP) * Sleep mode instead and automatically enter Deep Sleep mode when the * system is ready. * * The system puts the whole device into Deep Sleep mode when all the * processor(s) is (are) in Deep Sleep, there are no busy peripherals, the * debugger is not active, and the Deep Sleep circuits are * ready (PWR_CONTROL.LPM_READY=1). * * The peripherals that do not need a clock or that receive a clock from their * external interface (e.g. I2C/SPI) continue operating. All circuits using the * current from Vccdpslp supply are under the current limitation, which is * controlled by the Deep Sleep regulator. * * Wakeup occurs when an interrupt asserts from a Deep Sleep active peripheral. * For more details, see the corresponding peripheral's datasheet. * * \note * For multi-core devices, the second core, which did not participate in * device wakeup, continues to execute the Deep Sleep instructions. Any Deep Sleep * capable interrupt routed to this core can wake it. * * For more details about switching into the Deep Sleep power mode and debug, * refer to the device TRM. * * A normal wakeup from the Deep Sleep power mode returns to either LPActive or * Active, depending on the previous state and programmed behavior for the * particular wakeup interrupt. * * After wakeup from Deep Sleep, all of the registered callbacks with * CY_SYSPM_DEEPSLEEP type with CY_SYSPM_AFTER_TRANSITION are executed to return * peripherals to Active operation. The Cy_SysPm_DeepSleep() function returns * CY_SYSPM_SUCCESS. No callbacks are executed with CY_SYSPM_DEEPSLEEP type with * CY_SYSPM_BEFORE_TRANSITION or CY_SYSPM_AFTER_TRANSITION parameter, if * Deep Sleep mode was not entered. * * \param waitFor Selects wait for action. See \ref cy_en_syspm_waitfor_t. * * \sideeffect * This side effect is applicable only for devices with UDB IP block available. * You can obtain unpredictable behavior of the UDB block after the device wakeup * from Deep Sleep. * Unpredictable behavior scenario: * * The first core saves non-retained UDB configuration registers and goes into * the Deep Sleep (Cy_SysPm_DeepSleep() function). * * These non-retained UDB configuration registers are modified in runtime by * another (second) active core. * * The second core saves non-retained UDB configuration registers and goes into * the Deep Sleep (Cy_SysPm_DeepSleep() function). * These conditions save different values of the non-retained UDB configuration * registers. The prevented scenario: on the first core wakeup, these registers * are restored by the values saved on the first core. After the second core * wakeup, these registers are "reconfigured" by the values saved on the second * core. * Be aware of this situation. * * \sideeffect * This function clears the Event Register of CM4 core after wakeup from WFE. * * \sideeffect * This side effect is applicable only for rev-08 of the CY8CKIT-062. * The function changes the slow and fast clock dividers to * SYSPM_CLK_DIVIDER right before entering into Deep Sleep and restores * these dividers after wakeup. * * \return * Entered status, see \ref cy_en_syspm_status_t. * * \note * The FLL/PLL are not restored right before the CPU starts executing the * instructions after Deep Sleep. This can affect the peripheral which is * driven by PLL/FLL. Ensure that the PLL/FLL were properly restored (locked) * after the wakeup from Deep Sleep. Refer to the * \ref group_sysclk driver documentation driver for the information how to * read the PLL/FLL lock statuses. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_DeepSleep * *******************************************************************************/ cy_en_syspm_status_t Cy_SysPm_DeepSleep(cy_en_syspm_waitfor_t waitFor) { uint32_t interruptState; cy_en_syspm_status_t retVal = CY_SYSPM_SUCCESS; CY_ASSERT_L3(CY_SYSPM_IS_WAIT_FOR_VALID(waitFor)); /* Call the registered callback functions with * the CY_SYSPM_CHECK_READY parameter. */ if(0U != curRegisteredCallbacks) { retVal = Cy_SysPm_ExecuteCallback(CY_SYSPM_DEEPSLEEP, CY_SYSPM_CHECK_READY); } /* The device (core) can switch into the Deep Sleep power mode only when * all executed registered callback functions with the CY_SYSPM_CHECK_READY * parameter returned CY_SYSPM_SUCCESS. */ if(retVal == CY_SYSPM_SUCCESS) { /* Call the registered callback functions with the * CY_SYSPM_BEFORE_TRANSITION parameter. The return value should be * CY_SYSPM_SUCCESS. */ interruptState = Cy_SysLib_EnterCriticalSection(); if(0U != curRegisteredCallbacks) { (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_DEEPSLEEP, CY_SYSPM_BEFORE_TRANSITION); } #ifdef CY_IP_MXUDB static cy_stc_syspm_backup_regs_t regs; /* Check whether the UDB disabled on MMIO level */ if (0UL != (PERI->GR[CY_MMIO_UDB_GROUP_NR].SL_CTL & PERI_UDB_SLAVE_ENABLED)) { /* Save non-retained registers */ SaveRegisters(&regs); } #endif /* CY_IP_MXUDB */ #if defined(CY_DEVICE_PSOC6ABLE2) && !defined(CY_PSOC6ABLE2_REV_0A_SUPPORT_DISABLE) if (CY_SYSLIB_DEVICE_REV_0A == (uint32_t) Cy_SysLib_GetDeviceRevision()) { Cy_EnterDeepSleep(waitFor); } else #endif /* defined(CY_DEVICE_PSOC6ABLE2) && !defined(CY_PSOC6ABLE2_REV_0A_SUPPORT_DISABLE) */ { cy_en_syspm_ldo_voltage_t curLdoVoltage; curLdoVoltage = Cy_SysPm_LdoGetVoltage(); /* Configure additional wakeup delay from Deep Sleep * for 1.1 V LDO. Cypress ID #290172. */ if ((Cy_SysPm_LdoIsEnabled()) && (CY_SYSPM_LDO_VOLTAGE_1_1V == curLdoVoltage)) { SRSS->PWR_TRIM_WAKE_CTL = CY_SYSPM_SFLASH->PWR_TRIM_WAKE_CTL; } else { SRSS->PWR_TRIM_WAKE_CTL = 0UL; } /* Set the core into Deep Sleep */ EnterDeepSleep(waitFor); } #ifdef CY_IP_MXUDB /* Do not restore the UDB if it is disabled on MMIO level */ if (0UL != (PERI->GR[CY_MMIO_UDB_GROUP_NR].SL_CTL & PERI_UDB_SLAVE_ENABLED)) { /* Restore non-retained registers */ RestoreRegisters(&regs); } #endif /* CY_IP_MXUDB */ Cy_SysLib_ExitCriticalSection(interruptState); /* Call the registered callback functions with the CY_SYSPM_AFTER_TRANSITION * parameter. The return value should be CY_SYSPM_SUCCESS. */ if(0U != curRegisteredCallbacks) { (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_DEEPSLEEP, CY_SYSPM_AFTER_TRANSITION); } } else { /* Execute callback functions with the CY_SYSPM_CHECK_FAIL parameter to * undo everything done in the callback with the CY_SYSPM_CHECK_READY * parameter. The return value should be CY_SYSPM_SUCCESS. */ (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_DEEPSLEEP, CY_SYSPM_CHECK_FAIL); retVal = CY_SYSPM_FAIL; } return retVal; } /******************************************************************************* * Function Name: Cy_SysPm_Hibernate ****************************************************************************//** * * Sets the device into Hibernate mode. * * Puts the core into the Hibernate power mode. Prior to entering Hibernate * mode, all callbacks of the CY_SYSPM_HIBERNATE type are executed. * First, callbacks of the CY_SYSPM_HIBERNATE type and with * CY_SYSPM_CHECK_READY parameter are called, allowing the driver to signal if it * is not ready to enter the power mode. If any of the callbacks of the * CY_SYSPM_HIBERNATE type with the CY_SYSPM_CHECK_READY parameter call returns * CY_SYSPM_FAIL, the remaining CY_SYSPM_HIBERNATE callbacks with the * CY_SYSPM_CHECK_READY parameter calls are skipped. After CY_SYSPM_FAIL, all * of the CY_SYSPM_HIBERNATE callbacks with CY_SYSPM_CHECK_FAIL parameter are * executed that correspond to the CY_SYSPM_HIBERNATE callbacks with * CY_SYSPM_CHECK_READY parameter calls that occurred up to the point of failure. * Hibernate mode is not entered and the Cy_SysPm_Hibernate() function * returns CY_SYSPM_FAIL. * * If all CY_SYSPM_HIBERNATE callbacks with the CY_SYSPM_CHECK_READY parameter * calls return CY_SYSPM_SUCCESS, then all CY_SYSPM_HIBERNATE callbacks with * CY_SYSPM_CHECK_FAIL calls are skipped and all CY_SYSPM_HIBERNATE callbacks * CY_SYSPM_BEFORE_TRANSITION parameter calls are executed allowing the * peripherals to prepare for Hibernate. The I/O output state is frozen and * Hibernate mode is then entered. In Hibernate mode, all internal supplies * are off and no internal state is retained. There is no handshake with the * CPUs and the chip will enter Hibernate immediately. * * The I/O output state is frozen and Hibernate mode is then * entered. In Hibernate mode, all internal supplies are off and no * internal state is retained. * For multi-core devices there is no handshake with the CPUs and the chip * will enter Hibernate power mode immediately. * * \note The last callback that returned CY_SYSPM_FAIL is not executed with the * CY_SYSPM_CHECK_FAIL parameter because of the FAIL. * * The return values from executed callback functions with the * CY_SYSPM_CHECK_FAIL, CY_SYSPM_BEFORE_TRANSITION, and CY_SYSPM_AFTER_TRANSITION * modes are ignored. * * A wakeup from Hibernate is triggered by toggling the wakeup pin(s), a WDT * match, or back-up domain alarm expiration, depending on how the they were * configured. A wakeup causes a normal boot procedure. * To configure the wakeup pin(s), a Digital Input Pin must be configured, and * resistively pulled up or down to the inverse state of the wakeup polarity. To * distinguish a wakeup from Hibernate mode and a general reset event, the * Cy_SysLib_GetResetReason() function can be used. The wakeup pin and low-power * comparators are active-low by default. The wakeup pin or the LPComparators * polarity can be changed with the \ref Cy_SysPm_SetHibernateWakeupSource() function. * This function call will not return if Hibernate mode is entered. * The CY_SYSPM_HIBERNATE callbacks with the CY_SYSPM_AFTER_TRANSITION parameter * are never executed. * * This function freezes the I/O cells implicitly. Entering * Hibernate mode before freezing the I/O cells is not possible. The I/O cells remain frozen * after waking from Hibernate mode until the firmware unfreezes them * with a \ref Cy_SysPm_IoUnfreeze() function call. * * \return * Entered status, see \ref cy_en_syspm_status_t. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_Hibernate * *******************************************************************************/ cy_en_syspm_status_t Cy_SysPm_Hibernate(void) { cy_en_syspm_status_t retVal = CY_SYSPM_SUCCESS; /* Call the registered callback functions with the * CY_SYSPM_CHECK_READY parameter */ if(0U != curRegisteredCallbacks) { retVal = Cy_SysPm_ExecuteCallback(CY_SYSPM_HIBERNATE, CY_SYSPM_CHECK_READY); } /* The device (core) can switch into Hibernate power mode only when * all executed registered callback functions with CY_SYSPM_CHECK_READY * parameter returned CY_SYSPM_SUCCESS. */ if(retVal == CY_SYSPM_SUCCESS) { /* Call registered callback functions with CY_SYSPM_BEFORE_TRANSITION * parameter. Return value should be CY_SYSPM_SUCCESS. */ (void) Cy_SysLib_EnterCriticalSection(); if(0U != curRegisteredCallbacks) { (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_HIBERNATE, CY_SYSPM_BEFORE_TRANSITION); } /* Preserve the token that will retain through a wakeup sequence * thus could be used by Cy_SysLib_GetResetReason() to differentiate * Wakeup from a general reset event. * Preserve the wakeup source(s) configuration. */ SRSS->PWR_HIBERNATE = (SRSS->PWR_HIBERNATE & CY_SYSPM_PWR_WAKEUP_HIB_MASK) | CY_SYSPM_PWR_TOKEN_HIBERNATE; /* Freeze I/O-Cells to save I/O-Cell state */ Cy_SysPm_IoFreeze(); SRSS->PWR_HIBERNATE |= CY_SYSPM_PWR_SET_HIBERNATE; /* Read register to make sure it is settled */ (void) SRSS->PWR_HIBERNATE; /* Wait for transition */ __WFI(); /* The callback functions calls with the CY_SYSPM_AFTER_TRANSITION * parameter in the Hibernate power mode are not applicable as device * wake-up was made on device reboot. */ /* A wakeup from Hibernate is performed by toggling of the wakeup * pins, or WDT matches, or Backup domain alarm expires. This depends on what * item is configured in the hibernate register. After a wakeup event, a * normal Boot procedure occurs. * There is no need to exit from the critical section. */ } else { /* Execute callback functions with the CY_SYSPM_CHECK_FAIL parameter to * undo everything done in the callback with the CY_SYSPM_CHECK_READY * parameter. The return value should be CY_SYSPM_SUCCESS. */ (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_HIBERNATE, CY_SYSPM_CHECK_FAIL); retVal = CY_SYSPM_FAIL; } return retVal; } /******************************************************************************* * Function Name: Cy_SysPm_EnterLowPowerMode ****************************************************************************//** * * This function switches only the supply regulators into Low Power mode. * You must configure * clocks and/or peripherals to meet current load limitations in LP Active. * For more details about power modes and current load limitations refer to * the device technical reference manual (TRM). * * The LPActive mode is similar to the Active mode. * The difference is that the current is limited and some functions have limited * features/performance. * * The key feature of the Low Power mode is the limited current. Restrictions are * placed on the clock frequencies and allow the peripherals to achieve * a current limit. * * Before entering Low Power mode, you must configure the system so * the total current drawn from Vccd is less that the value presented in the * technical reference manual (TRM). Refer to the TRM for the maximum load for * low power operation and clock limitations in Low Power mode with different * core supply regulator voltages. * * * Peripherals can use the knowledge of the LPActive mode to make * trade-offs that consume less current. For more details, see the corresponding * peripherals' datasheet. * * High-speed clock sources are available with the appropriate pre-divider * settings to limit the system current. * Refer to the TRM for the maximum frequency values for low power operation * using different Core Regulators' output voltages. * * This function puts the device into Low Power mode. Prior to entering Low Power mode, * all the registered CY_SYSPM_ENTER_LOWPOWER_MODE callbacks with CY_SYSPM_CHECK_READY * parameter are called. This allows the driver to signal if it is not ready to * enter Low Power mode. If any CY_SYSPM_ENTER_LOWPOWER_MODE callbacks with the * CY_SYSPM_CHECK_READY parameter call returns CY_SYSPM_FAIL, the remaining * CY_SYSPM_ENTER_LOWPOWER_MODE callbacks with the CY_SYSPM_CHECK_READY parameter * calls are skipped. * * After a CY_SYSPM_FAIL, all of the CY_SYSPM_ENTER_LOWPOWER_MODE callbacks with * CY_SYSPM_CHECK_FAIL parameter are executed that correspond to the * CY_SYSPM_ENTER_LOWPOWER_MODE callbacks with CY_SYSPM_CHECK_READY parameter calls * that occurred up to the point of failure. Low Power mode is not entered and * the Cy_SysPm_EnterLowPowerMode() function returns CY_SYSPM_FAIL. * * If all CY_SYSPM_ENTER_LOWPOWER_MODE callbacks with the CY_SYSPM_CHECK_READY * parameter calls return CY_SYSPM_SUCCESS, then all CY_SYSPM_ENTER_LOWPOWER_MODE * callbacks with CY_SYSPM_CHECK_FAIL calls are skipped and all * CY_SYSPM_ENTER_LOWPOWER_MODE callbacks with the CY_SYSPM_BEFORE_TRANSITION parameter * calls are executed. This allows the peripherals to prepare for low power. * Low Power mode is then entered. * * After entering Low Power mode, all of the registered * CY_SYSPM_ENTER_LOWPOWER_MODE callbacks with the CY_SYSPM_AFTER_TRANSITION parameter * are executed to complete preparing the peripherals for low power operation. * The Cy_SysPm_EnterLowPowerMode() function returns CY_SYSPM_SUCCESS. * No CY_SYSPM_ENTER_LOWPOWER_MODE callbacks with the CY_SYSPM_BEFORE_TRANSITION or * CY_SYSPM_AFTER_TRANSITION parameter are executed, if Low Power mode is not * entered. * * \note The last callback that returned CY_SYSPM_FAIL is not executed with * the CY_SYSPM_CHECK_FAIL parameter because of the FAIL. * * The return values from executed callback functions with the * CY_SYSPM_CHECK_FAIL, CY_SYSPM_BEFORE_TRANSITION, and CY_SYSPM_AFTER_TRANSITION * modes are ignored. * * \note The callbacks are not executed if the device is already not in * Low Power mode. * * \return * See \ref cy_en_syspm_status_t. <br> * CY_SYSPM_SUCCESS - Entered the LPActive mode or the device is already * in LPActive.<br> * CY_SYSPM_FAIL - The LPActive mode is not entered or low power circuits * are not ready to enter Low Power mode. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_EnterLowPowerMode * *******************************************************************************/ cy_en_syspm_status_t Cy_SysPm_EnterLowPowerMode(void) { uint32_t interruptState; cy_en_syspm_status_t retVal = CY_SYSPM_SUCCESS; /* Check whether device is in the low power mode. */ if(0U == (_FLD2VAL(SRSS_PWR_CTL_ACT_REF_DIS, SRSS->PWR_CTL))) { /* The entering into the low power mode is permitted when low * power circuits are ready to enter into the low power mode. */ if(0U != _FLD2VAL(SRSS_PWR_CTL_LPM_READY, SRSS->PWR_CTL)) { /* Call the registered callback functions with the * CY_SYSPM_CHECK_READY parameter. */ if(0U != curRegisteredCallbacks) { retVal = Cy_SysPm_ExecuteCallback(CY_SYSPM_ENTER_LOWPOWER_MODE, CY_SYSPM_CHECK_READY); } /* The device (core) can switch into the low power mode only when * all executed registered callback functions with the * CY_SYSPM_CHECK_READY parameter returned CY_SYSPM_SUCCESS. */ if(retVal == CY_SYSPM_SUCCESS) { /* Call the registered callback functions with the * CY_SYSPM_BEFORE_TRANSITION parameter. The return value * should be CY_SYSPM_SUCCESS. */ interruptState = Cy_SysLib_EnterCriticalSection(); if(0U != curRegisteredCallbacks) { (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_ENTER_LOWPOWER_MODE, CY_SYSPM_BEFORE_TRANSITION); } /* Configure the low-power operating mode for LDO regulator */ if(Cy_SysPm_LdoIsEnabled()) { SRSS->PWR_CTL |= (_VAL2FLD(SRSS_PWR_CTL_LINREG_LPMODE, 1U) | _VAL2FLD(SRSS_PWR_CTL_PORBOD_LPMODE, 1U) | _VAL2FLD(SRSS_PWR_CTL_BGREF_LPMODE, 1U) | _VAL2FLD(SRSS_PWR_CTL_VREFBUF_LPMODE, 1U) | _VAL2FLD(SRSS_PWR_CTL_IREF_LPMODE, 1U)); } else { /* Configure the low-power operating mode for Buck regulator */ SRSS->PWR_CTL |= (_VAL2FLD(SRSS_PWR_CTL_PORBOD_LPMODE, 1U) | _VAL2FLD(SRSS_PWR_CTL_BGREF_LPMODE, 1U) | _VAL2FLD(SRSS_PWR_CTL_VREFBUF_LPMODE, 1U) | _VAL2FLD(SRSS_PWR_CTL_IREF_LPMODE, 1U)); } /* This wait time allows the circuits to remove their dependence on * the Active mode circuits, such as Active Reference. */ Cy_SysLib_DelayUs(CY_SYSPM_ACTIVE_TO_LP_WAIT_US); /* Disabling active reference */ SRSS->PWR_CTL |= _VAL2FLD(SRSS_PWR_CTL_ACT_REF_DIS, 1U); Cy_SysLib_ExitCriticalSection(interruptState); /* Call the registered callback functions with the * CY_SYSPM_AFTER_TRANSITION parameter. The return value * should be CY_SYSPM_SUCCESS. */ if(0U != curRegisteredCallbacks) { (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_ENTER_LOWPOWER_MODE, CY_SYSPM_AFTER_TRANSITION); } } else { /* Execute callback functions with the CY_SYSPM_CHECK_FAIL parameter to * undo everything done in the callback with the CY_SYSPM_CHECK_READY * parameter. The return value should be CY_SYSPM_SUCCESS. */ (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_ENTER_LOWPOWER_MODE, CY_SYSPM_CHECK_FAIL); retVal = CY_SYSPM_FAIL; } } else { retVal = CY_SYSPM_FAIL; } } else { /* Do nothing because the device is already in Low Power mode. */ } return retVal; } /******************************************************************************* * Function Name: Cy_SysPm_ExitLowPowerMode ****************************************************************************//** * * Exits the device from Low Power mode. * * Returns the device to the Active mode. In the Active power mode, the operating * current can be increased to the normal mode limit. The clock frequencies also * can be increased to the normal mode limit. Refer to the device TRM for the * current and frequency limitations in the Active power mode. * * Prior to exiting Low Power mode, all the registered CY_SYSPM_EXIT_LOWPOWER_MODE * callbacks with the CY_SYSPM_CHECK_READY parameter are called. This allows * the driver to signal if it is not ready to exit * Low Power mode. If any CY_SYSPM_EXIT_LOWPOWER_MODE callbacks with * the CY_SYSPM_CHECK_READY parameter call returns CY_SYSPM_FAIL, the remaining * CY_SYSPM_EXIT_LOWPOWER_MODE callbacks with the CY_SYSPM_CHECK_READY parameter calls * are skipped. After a CY_SYSPM_FAIL, all of the CY_SYSPM_EXIT_LOWPOWER_MODE callbacks * with CY_SYSPM_CHECK_FAIL parameter are executed that correspond to the * CY_SYSPM_EXIT_LOWPOWER_MODE callbacks with CY_SYSPM_CHECK_READY parameter calls that * occurred up to the point of failure. Active mode is not entered and the * Cy_SysPm_ExitLowPowerMode() function returns CY_SYSPM_FAIL. * * If all CY_SYSPM_EXIT_LOWPOWER_MODE callbacks with CY_SYSPM_CHECK_READY calls return * CY_SYSPM_SUCCESS, then all the CY_SYSPM_EXIT_LOWPOWER_MODE callbacks with * the CY_SYSPM_CHECK_FAIL parameter calls are skipped and all * CY_SYSPM_EXIT_LOWPOWER_MODE callbacks with the CY_SYSPM_BEFORE_TRANSITION parameter * calls are executed allowing the peripherals to prepare for Active mode. * Low Power mode is then exited. * * After exiting Low Power mode, all of the registered callbacks that have * type CY_SYSPM_EXIT_LOWPOWER_MODE are executed with the CY_SYSPM_AFTER_TRANSITION * parameter to complete preparing the peripherals for Active mode operation. * The Cy_SysPm_ExitLowPowerMode() function returns CY_SYSPM_SUCCESS. * No CY_SYSPM_EXIT_LOWPOWER_MODE callbacks with the CY_SYSPM_BEFORE_TRANSITION or * CY_SYSPM_AFTER_TRANSITION parameter are executed if Low Power mode is * not exited. * * \note The last callback that returned CY_SYSPM_FAIL is not executed with the * CY_SYSPM_CHECK_FAIL parameter because of the FAIL. * * The return values from executed callback functions with the * CY_SYSPM_CHECK_FAIL, CY_SYSPM_BEFORE_TRANSITION, and CY_SYSPM_AFTER_TRANSITION * modes are ignored. * * \note The callbacks are not executed if the device is not already in Low * Power mode. * * \return * See \ref cy_en_syspm_status_t. <br> * CY_SYSPM_SUCCESS - Exited from the LPActive power mode, or the device is * already in Active mode. <br> * CY_SYSPM_FAIL - Exit from the LPActive mode is not done. * * \warning This function blocks as it waits until Active Reference is ready * to enter to the normal mode. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_ExitLowPowerMode * *******************************************************************************/ cy_en_syspm_status_t Cy_SysPm_ExitLowPowerMode(void) { uint32_t interruptState; uint32_t timeOut = CY_SYSPM_WAIT_DELAY_TRYES; cy_en_syspm_status_t retVal = CY_SYSPM_SUCCESS; /* Check if the device is in the low power mode */ if(0U != (_FLD2VAL(SRSS_PWR_CTL_ACT_REF_DIS, SRSS->PWR_CTL))) { /* Call the registered callback functions with the * CY_SYSPM_CHECK_READY parameter. */ if(0U != curRegisteredCallbacks) { retVal = Cy_SysPm_ExecuteCallback(CY_SYSPM_EXIT_LOWPOWER_MODE, CY_SYSPM_CHECK_READY); } /* The device (core) can switch into the Low Power mode only in the * condition that all executed registered callback functions with the * CY_SYSPM_CHECK_READY parameter return CY_SYSPM_SUCCESS. */ if(retVal == CY_SYSPM_SUCCESS) { /* Call the registered callback functions with the * CY_SYSPM_BEFORE_TRANSITION parameter. The return value should be * CY_SYSPM_SUCCESS. */ interruptState = Cy_SysLib_EnterCriticalSection(); if(0U != curRegisteredCallbacks) { (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_EXIT_LOWPOWER_MODE, CY_SYSPM_BEFORE_TRANSITION); } /* Set the normal operation mode for LDO regulator if * it is enabled */ if(Cy_SysPm_LdoIsEnabled()) { SRSS->PWR_CTL &= ((uint32_t)~(SRSS_PWR_CTL_LINREG_LPMODE_Msk)); } /* Configure the normal operating mode for the POR/BOD circuits and * for the Bandgap Voltage and Current References */ SRSS->PWR_CTL &= ((uint32_t)~(_VAL2FLD(SRSS_PWR_CTL_PORBOD_LPMODE, 1U) | _VAL2FLD(SRSS_PWR_CTL_ACT_REF_DIS, 1U) | _VAL2FLD(SRSS_PWR_CTL_VREFBUF_LPMODE, 1U) | _VAL2FLD(SRSS_PWR_CTL_IREF_LPMODE, 1U))); /* This wait time allows setting Active Reference */ Cy_SysLib_DelayUs(CY_SYSPM_LP_TO_ACTIVE_WAIT_BEFORE_US); while((0U == _FLD2VAL(SRSS_PWR_CTL_ACT_REF_OK, SRSS->PWR_CTL)) && (0U != timeOut)) { timeOut--; } if(0U == timeOut) { retVal = CY_SYSPM_TIMEOUT; Cy_SysLib_ExitCriticalSection(interruptState); } else { /* Configure the normal operation mode */ SRSS->PWR_CTL &= ((uint32_t) (~SRSS_PWR_CTL_BGREF_LPMODE_Msk)); /* This wait time allows setting Active Reference */ Cy_SysLib_DelayUs(CY_SYSPM_LP_TO_ACTIVE_WAIT_AFTER_US); Cy_SysLib_ExitCriticalSection(interruptState); /* Call registered callback functions with CY_SYSPM_AFTER_TRANSITION * parameter. Return value should be CY_SYSPM_SUCCESS. */ if(0U != curRegisteredCallbacks) { (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_EXIT_LOWPOWER_MODE, CY_SYSPM_AFTER_TRANSITION); } } } else { /* Execute callback functions with the CY_SYSPM_CHECK_FAIL parameter to * undo everything done in the callback with the CY_SYSPM_CHECK_READY * parameter. The return value should be CY_SYSPM_SUCCESS. */ (void) Cy_SysPm_ExecuteCallback(CY_SYSPM_EXIT_LOWPOWER_MODE, CY_SYSPM_CHECK_FAIL); retVal = CY_SYSPM_FAIL; } } else { /* Do nothing because the device is already in the Active power mode */ } return retVal; } /******************************************************************************* * Function Name: Cy_SysPm_SleepOnExit ****************************************************************************//** * * This function configures the Sleep-on-exit feature of the core. * * This API sets the SLEEPONEXIT bit of the SCR register. * * When the Sleep-on-exit feature is enabled (SLEEPONEXIT bit is set), * the core wakes up to service the interrupt and then immediately goes * back to sleep. Because of this, the unstacking process is not carried out, so * this feature is useful for the interrupt driven application and helps to * reduce the unnecessary stack push and pop operations. * The core does not go to sleep if the interrupt handler returns to * another interrupt handler (nested interrupt). * You can use this feature in applications that require only the core to run * when an interrupt occurs. * * When the Sleep-on-exit feature is disabled (SLEEPONEXIT bit is cleared), * the core returns back to the main thread after servicing the interrupt * without going back to sleep. * * Refer to the ARM documentation about the Sleep-on-exit feature and * SLEEPONEXIT of the SCR register. * * \param enable * true - enable Sleep-on-exit feature <br> false - disable * Sleep-on-exit feature. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_SleepOnExit * *******************************************************************************/ void Cy_SysPm_SleepOnExit(bool enable) { uint32_t interruptState; interruptState = Cy_SysLib_EnterCriticalSection(); if(enable) { /* Enable Sleep-on-exit mode */ SCB->SCR |= _VAL2FLD(SCB_SCR_SLEEPONEXIT, 1U); } else { /* Disable Sleep-on-exit mode */ SCB->SCR &= ((uint32_t) ~(SCB_SCR_SLEEPONEXIT_Msk)); } Cy_SysLib_ExitCriticalSection(interruptState); } /******************************************************************************* * Function Name: Cy_SysPm_SetHibernateWakeupSource ****************************************************************************//** * * This function configures sources to wake up the device from the Hibernate * power mode. Such sources can be wakeup pins, LPComparators, Watchdog (WDT) * interrupt, or a Real-Time clock (RTC) alarm (interrupt). * * Wakeup pins: * * A wakeup is supported by up to two pins with programmable polarity. These pins * may be connected to the I/O pins or on-chip peripherals under some conditions. * Setting the wakeup pin to this level will cause a wakeup from Hibernate * mode. The wakeup pins are active/low by default. * * LPComparators: * * A wakeup is supported by up to two LPComps with programmable polarity. These * LPComp may be connected to the I/O pins or on-chip peripherals under some * conditions. * Setting the LPComp to this level will cause a wakeup from Hibernate * mode. The wakeup LPComp are active-low by default. * * \note The low-power comparators should be configured and enabled before * switching into the hibernate low power mode. Refer to the LPComp * driver description for more details. * * Watchdog Timer: * * \note The WDT should be configured and enabled before entering into the * Hibernate power mode. * * A wakeup is performed by a WDT interrupt and a normal boot procedure * after a device reset. The device can wake up from Hibernate after a WDT * device reset, if the WDT was configured to wake up, the device on its * interrupt and WDT was enabled. * * Real-time Clock: * * A wakeup is performed by the RTC alarm and a normal boot procedure * after a device reset. * Refer to the Real-Time Clock (RTC) driver description for more details. * * For information about wakeup sources and their assignment in the specific * families devices, refer to the appropriate device TRM. * * \param wakeupSource * The source to be configured as a wakeup source from * the Hibernate power mode, see \ref cy_en_syspm_hibernate_wakeup_source_t. * The input parameters values can be ORed. For example, if you want to set * LPComp0 (active high) and WDT, call this function: * Cy_SysPm_SetHibernateWakeupSource(CY_SYSPM_HIBERNATE_LPCOMP0_HIGH | CY_SYSPM_HIBERNATE_WDT). * * \warning Do not call this function with different polarity levels for the same * wakeup source. For example, do not call a function like this: * Cy_SysPm_SetHibernateWakeupSource(CY_SYSPM_HIBERNATE_LPCOMP0_LOW, CY_SYSPM_HIBERNATE_LPCOMP0_HIGH); * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_SetHibernateWakeupSource * *******************************************************************************/ void Cy_SysPm_SetHibernateWakeupSource(uint32_t wakeupSource) { CY_ASSERT_L3(CY_SYSPM_IS_WAKE_UP_SOURCE_VALID(wakeupSource)); /* Reconfigure the wake-up pins and LPComp polarity based on the input */ if(0U != ((uint32_t) wakeupSource & CY_SYSPM_WAKEUP_LPCOMP0)) { SRSS->PWR_HIBERNATE &= ((uint32_t) ~_VAL2FLD(SRSS_PWR_HIBERNATE_POLARITY_HIBPIN, CY_SYSPM_WAKEUP_LPCOMP0_BIT)); } if(0U != ((uint32_t) wakeupSource & CY_SYSPM_WAKEUP_LPCOMP1)) { SRSS->PWR_HIBERNATE &= ((uint32_t) ~_VAL2FLD(SRSS_PWR_HIBERNATE_POLARITY_HIBPIN, CY_SYSPM_WAKEUP_LPCOMP1_BIT)); } if(0U != ((uint32_t) wakeupSource & CY_SYSPM_WAKEUP_PIN0)) { SRSS->PWR_HIBERNATE &= ((uint32_t) ~_VAL2FLD(SRSS_PWR_HIBERNATE_POLARITY_HIBPIN, CY_SYSPM_WAKEUP_PIN0_BIT)); } if(0U != ((uint32_t) wakeupSource & CY_SYSPM_WAKEUP_PIN1)) { SRSS->PWR_HIBERNATE &= ((uint32_t) ~_VAL2FLD(SRSS_PWR_HIBERNATE_POLARITY_HIBPIN, CY_SYSPM_WAKEUP_PIN1_BIT)); } SRSS->PWR_HIBERNATE |= ((uint32_t) wakeupSource); /* Read register to make sure it is settled */ (void) SRSS->PWR_HIBERNATE; } /******************************************************************************* * Function Name: Cy_SysPm_ClearHibernateWakeupSource ****************************************************************************//** * * This function disables a wakeup source that was previously configured to * wake up the device from the hibernate power mode. * * \param wakeupSource * For the source to be disabled, see \ref cy_en_syspm_hibernate_wakeup_source_t. * The input parameters values can be ORed. For example, if you want to disable * LPComp0 (active high) and WDT call this function: * Cy_SysPm_ClearHibernateWakeupSource(CY_SYSPM_HIBERNATE_LPCOMP0_HIGH | CY_SYSPM_HIBERNATE_WDT). * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_ClearHibernateWakeupSource * *******************************************************************************/ void Cy_SysPm_ClearHibernateWakeupSource(uint32_t wakeupSource) { uint32_t clearWakeupSource; CY_ASSERT_L3(CY_SYSPM_IS_WAKE_UP_SOURCE_VALID(wakeupSource)); if (0U != _FLD2VAL(SRSS_PWR_HIBERNATE_POLARITY_HIBPIN, wakeupSource)) { /* Clear the high active level of the requested sources */ if((uint32_t) CY_SYSPM_HIBERNATE_LPCOMP0_HIGH == ((uint32_t) wakeupSource & (uint32_t) CY_SYSPM_HIBERNATE_LPCOMP0_HIGH)) { SRSS->PWR_HIBERNATE &= ((uint32_t) ~_VAL2FLD(SRSS_PWR_HIBERNATE_POLARITY_HIBPIN, CY_SYSPM_WAKEUP_LPCOMP0_BIT)); } if((uint32_t) CY_SYSPM_HIBERNATE_LPCOMP1_HIGH == ((uint32_t) wakeupSource & (uint32_t) CY_SYSPM_HIBERNATE_LPCOMP1_HIGH)) { SRSS->PWR_HIBERNATE &= ((uint32_t) ~_VAL2FLD(SRSS_PWR_HIBERNATE_POLARITY_HIBPIN, CY_SYSPM_WAKEUP_LPCOMP1_BIT)); } if((uint32_t) CY_SYSPM_HIBERNATE_PIN0_HIGH == ((uint32_t) wakeupSource & (uint32_t) CY_SYSPM_HIBERNATE_PIN0_HIGH)) { SRSS->PWR_HIBERNATE &= ((uint32_t) ~_VAL2FLD(SRSS_PWR_HIBERNATE_POLARITY_HIBPIN, CY_SYSPM_WAKEUP_PIN0_BIT)); } if((uint32_t) CY_SYSPM_HIBERNATE_PIN1_HIGH == ((uint32_t) wakeupSource & (uint32_t) CY_SYSPM_HIBERNATE_PIN1_HIGH)) { SRSS->PWR_HIBERNATE &= ((uint32_t) ~_VAL2FLD(SRSS_PWR_HIBERNATE_POLARITY_HIBPIN, CY_SYSPM_WAKEUP_PIN1_BIT)); } } /* Remove the polarity bits from the input value */ clearWakeupSource = ((uint32_t) wakeupSource & ((uint32_t) ~ SRSS_PWR_HIBERNATE_POLARITY_HIBPIN_Msk)); SRSS->PWR_HIBERNATE &= ((uint32_t) ~ clearWakeupSource); /* Read register to make sure it is settled */ (void) SRSS->PWR_HIBERNATE; } #if(0u != SRSS_BUCKCTL_PRESENT) /******************************************************************************* * Function Name: Cy_SysPm_BuckEnable ****************************************************************************//** * * Switch the power supply regulator to Buck regulator instead of the LDO. * The Buck core regulator provides output voltage(s) using one external * inductor and can supply Vccd with higher efficiency than the LDO under some * conditions, such as high external supply voltage. * * Before changing from LDO to Buck, ensure that the circuit board has * connected Vccbuck1 to Vccd and also populated the * necessary external components for the Buck regulator, including an * inductor and a capacitor for each output. * Refer to the device TRM for more details. * * When changing from a higher voltage to a lower voltage * (from LDO 1.1V to Buck 0.9V), ensure that: * * The device maximum operating frequency for all the Clk_HF paths, peripheral, * and slow clock are under the ULP limitations. * * The total current consumption is under the ULP limitations. * * * The appropriate wait states values are set for the flash using * the Cy_SysLib_SetWaitStates() function as explained below. * * <b>Setting wait states values for flash</b> * * The flash access time when the core output voltage is 0.9 V (nominal) is * longer than at 1.1 V (nominal). Therefore, the number of the wait states must * be adjusted. Use the Cy_SysLib_SetWaitStates() function to set the appropriate * wait state values for flash. * * To change from a higher voltage (LDO 1.1 V) to a lower voltage (Buck 0.9 V), * call the Cy_SysLib_SetWaitStates(true, hfClkFreqMz) function before changing * the voltage, where hfClkFreqMz is the frequency of HfClk0 in MHz. * * To change from a lower voltage (LDO 0.9 V) to a higher voltage (Buck 1.1 V), * calling the Cy_SysLib_SetWaitStates(false, hfClkFreqMz) function is to set * the wait states is optional, but can be done to improve the performance. * The clock frequency may now be increased up to LP mode for a new voltage. * * \note 1. The final Buck output is set to 0.9 V (nominal) - the flash works * in the Read-only operation. * \note 2. The final Buck output is set to 1.1 V (nominal) - the flash works * in the Read and Write operations. * \note 3. The actual device Vccd voltage can be different from the nominal * voltage because the actual voltage value depends on the conditions * including the load current. * * \warning There is no way to go back to the LDO after the * Buck regulator supplies a core. The function switches off the LDO. * * For more details refer to the \ref group_syspm_managing_core_regulators * section. * Refer to the \ref group_syslib driver for more details about setting the wait * states. * * \note * The function is applicable for devices with the Buck regulator. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_BuckEnable * *******************************************************************************/ void Cy_SysPm_BuckEnable(cy_en_syspm_buck_voltage1_t voltage) { CY_ASSERT_L3(CY_SYSPM_IS_BUCK_VOLTAGE1_VALID(voltage)); uint32_t interruptState; cy_en_syspm_ldo_voltage_t curLdoVoltage; curLdoVoltage = Cy_SysPm_LdoGetVoltage(); interruptState = Cy_SysLib_EnterCriticalSection(); /* When the LDO is 1.1V and final target Buck 0.9V need to update the * RAM and ROM trim values */ if ((CY_SYSPM_BUCK_OUT1_VOLTAGE_0_9V == voltage) && (CY_SYSPM_LDO_VOLTAGE_1_1V == curLdoVoltage)) { /* Set the analog signal bit for the flash before the voltage is * changed from 1.1V to 0.9V */ SetVoltageBitForFlash(); /* Update read-write margin value for the ULP mode */ SetReadMarginTrimUlp(); /* Reduce LDO output voltage to 0.95 V nominal */ SRSS->PWR_TRIM_PWRSYS_CTL = _CLR_SET_FLD32U((SRSS->PWR_TRIM_PWRSYS_CTL), SRSS_PWR_TRIM_PWRSYS_CTL_ACT_REG_TRIM, LDO_OUT_VOLTAGE_0_95V); /* Update write assist value for the ULP mode */ SetWriteAssistTrimUlp(); } /* When the LDO is 0.9V and final target Buck 1.1 V need to update the * RAM and ROM trim values */ else if ((CY_SYSPM_BUCK_OUT1_VOLTAGE_1_1V == voltage) && (CY_SYSPM_LDO_VOLTAGE_0_9V == curLdoVoltage)) { /* Increase LDO to 0.95 V */ SRSS->PWR_TRIM_PWRSYS_CTL = _CLR_SET_FLD32U((SRSS->PWR_TRIM_PWRSYS_CTL), SRSS_PWR_TRIM_PWRSYS_CTL_ACT_REG_TRIM, LDO_OUT_VOLTAGE_0_95V); /* Wait until regulator is stable */ Cy_SysLib_DelayUs(LDO_STABILIZATION_DELAY_US); /* Update write assist value for the LP mode */ SetWriteAssistTrimLp(); /* Increase LDO to 1.1 V */ SRSS->PWR_TRIM_PWRSYS_CTL = _CLR_SET_FLD32U((SRSS->PWR_TRIM_PWRSYS_CTL), SRSS_PWR_TRIM_PWRSYS_CTL_ACT_REG_TRIM, LDO_OUT_VOLTAGE_1_1V); /* Wait until regulator is stable */ Cy_SysLib_DelayUs(LDO_STABILIZATION_DELAY_US); /* Update read-write margin value for the LP mode */ SetReadMarginTrimLp(); /* Set the LDO 1.15V as final Buck output is 1.1 V */ SRSS->PWR_TRIM_PWRSYS_CTL = _CLR_SET_FLD32U((SRSS->PWR_TRIM_PWRSYS_CTL), SRSS_PWR_TRIM_PWRSYS_CTL_ACT_REG_TRIM, LDO_OUT_VOLTAGE_1_15V); /* Clear the analog signal bit for the flash before the voltage is * changed from 1.1 V to 0.9 V */ ClearVoltageBitForFlash(); } /* If LDO is 0.9V and final Buck is 0.9V increase the LDO on 50 mV*/ else if ((CY_SYSPM_BUCK_OUT1_VOLTAGE_0_9V == voltage) && (CY_SYSPM_LDO_VOLTAGE_0_9V == curLdoVoltage)) { SRSS->PWR_TRIM_PWRSYS_CTL = _CLR_SET_FLD32U((SRSS->PWR_TRIM_PWRSYS_CTL), SRSS_PWR_TRIM_PWRSYS_CTL_ACT_REG_TRIM, LDO_OUT_VOLTAGE_0_95V); } /* If LDO is 1.1V and final Buck is 1.1 V increase the LDO on 50 mV*/ else { SRSS->PWR_TRIM_PWRSYS_CTL = _CLR_SET_FLD32U((SRSS->PWR_TRIM_PWRSYS_CTL), SRSS_PWR_TRIM_PWRSYS_CTL_ACT_REG_TRIM, LDO_OUT_VOLTAGE_1_15V); } /* A delay for the supply to stabilize at the new higher voltage */ Cy_SysLib_DelayUs(LDO_STABILIZATION_DELAY_US); /* Disable the Deep Sleep, nWell, and Retention regulators */ SRSS->PWR_CTL |= (_VAL2FLD(SRSS_PWR_CTL_DPSLP_REG_DIS, 1U) | _VAL2FLD(SRSS_PWR_CTL_RET_REG_DIS, 1U) | _VAL2FLD(SRSS_PWR_CTL_NWELL_REG_DIS, 1U)); /* Configure the Buck regulator */ SRSS->PWR_BUCK_CTL = _CLR_SET_FLD32U((SRSS->PWR_BUCK_CTL), SRSS_PWR_BUCK_CTL_BUCK_OUT1_SEL, (uint32_t) voltage); /* Check whether the Buck regulator is already enabled */ if(!Cy_SysPm_BuckIsEnabled()) { SRSS->PWR_BUCK_CTL |= _VAL2FLD(SRSS_PWR_BUCK_CTL_BUCK_EN, 1U); } SRSS->PWR_BUCK_CTL |= _VAL2FLD(SRSS_PWR_BUCK_CTL_BUCK_OUT1_EN, 1U); /* Wait until Buck output 1 is stable */ Cy_SysLib_DelayUs(CY_SYSPM_BUCK_CORE_SUPPLY_STABLE_US); /* Disable the LDO, because Vbuckout1 and LDO are shorted */ SRSS->PWR_CTL |= _VAL2FLD(SRSS_PWR_CTL_LINREG_DIS, 1U); Cy_SysLib_ExitCriticalSection(interruptState); } /******************************************************************************* * Function Name: Cy_SysPm_BuckSetVoltage1 ****************************************************************************//** * * Sets the output 1 voltage for the Buck regulator that can supply core(s). * This output can supply cores instead of the LDO. * * When changing from a higher voltage to a lower voltage, ensure that: * * The device maximum operating frequency for all the Clk_HF paths, peripheral, * and slow clock are under the \ref group_syspm_ulp_limitations. * * The total current consumption is under the \ref group_syspm_ulp_limitations. * * * The appropriate wait states values are set for the flash using * the Cy_SysLib_SetWaitStates() function as explained below. * * <b>Setting wait states values for flash</b> * * The flash access time when the core output voltage is 0.9 V (nominal) is * longer than at 1.1 V (nominal). Therefore, the number of the wait states must * be adjusted. Use the Cy_SysLib_SetWaitStates() function to set the appropriate * wait state values for flash. * * To change from a higher voltage to a lower voltage 0.9 V (nominal), * call the Cy_SysLib_SetWaitStates(true, hfClkFreqMz) function before changing * the voltage, where hfClkFreqMz is the frequency of HfClk0 in MHz. * * To change from a lower voltage to a higher voltage 1.1 V (nominal), calling * the Cy_SysLib_SetWaitStates(false, hfClkFreqMz) function is to set the * wait states is optional, but can be done to improve the performance. * The clock frequency may now be increased up to * \ref group_syspm_lp_limitations for a new voltage. * * \note 1. The output is set to 0.9 V (nominal) - the flash works in the * Read-only operation. * \note 2. The output is set to 1.1 V (nominal) - the flash works in the Read * and Write operations. * \note 3. The actual device Vccd voltage can be different from the nominal * voltage because the actual voltage value depends on the conditions * including the load current. * * For more details refer to the \ref group_syspm_managing_core_regulators * section. * Refer to the \ref group_syslib driver for more details about setting the * wait states. * * \param voltage * The desired output 1 regulator voltage (Vccbuck1). * See \ref cy_en_syspm_buck_voltage1_t * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_VoltageRegulator * *******************************************************************************/ void Cy_SysPm_BuckSetVoltage1(cy_en_syspm_buck_voltage1_t voltage) { CY_ASSERT_L3(CY_SYSPM_IS_BUCK_VOLTAGE1_VALID(voltage)); uint32_t interruptState; interruptState = Cy_SysLib_EnterCriticalSection(); /* Check whether the required voltage is equal to the current voltage */ if (voltage != Cy_SysPm_BuckGetVoltage1()) { if (CY_SYSPM_BUCK_OUT1_VOLTAGE_0_9V == voltage) { /* Set the analog signal bit for the flash before the voltage is * changed from 1.1 V to 0.9 V */ SetVoltageBitForFlash(); /* Update read-write margin value for the ULP mode */ SetReadMarginTrimUlp(); /* Reduce Buck output voltage to 0.95V nominal */ SRSS->PWR_BUCK_CTL = _CLR_SET_FLD32U((SRSS->PWR_BUCK_CTL), SRSS_PWR_BUCK_CTL_BUCK_OUT1_SEL, BUCK_OUT1_VOLTAGE_0_95V); /* Update write assist value for the ULP mode */ SetWriteAssistTrimUlp(); } else { /* Increase Buck output voltage to 0.95 V nominal */ SRSS->PWR_BUCK_CTL = _CLR_SET_FLD32U((SRSS->PWR_BUCK_CTL), SRSS_PWR_BUCK_CTL_BUCK_OUT1_SEL, BUCK_OUT1_VOLTAGE_0_95V); /* Wait until regulator is stable */ Cy_SysLib_DelayUs(BUCK_STABILIZATION_DELAY_US); /* Update write assist value for the LP mode */ SetWriteAssistTrimLp(); } /* The system may continue operating while the voltage on Vccd * discharges to the new voltage. The time it takes to reach the * new voltage depends on the conditions, including the load current * on Vccd and the external capacitor size. */ SRSS->PWR_BUCK_CTL = _CLR_SET_FLD32U((SRSS->PWR_BUCK_CTL), SRSS_PWR_BUCK_CTL_BUCK_OUT1_SEL, (uint32_t) voltage); /* Delay to stabilize at the new voltage is required only * when changing from a lower voltage to a higher voltage. */ if(CY_SYSPM_BUCK_OUT1_VOLTAGE_1_1V == voltage) { Cy_SysLib_DelayUs(BUCK_STABILIZATION_DELAY_US); /* Update read-write margin value for the LP mode */ SetReadMarginTrimLp(); /* Set analog signal bit for flash before voltage is changed * from 0.9 V to 1.1 V. */ ClearVoltageBitForFlash(); } } Cy_SysLib_ExitCriticalSection(interruptState); } /******************************************************************************* * Function Name: Cy_SysPm_BuckIsOutputEnabled ****************************************************************************//** * * This function gets the current output status of the Buck outputs. * * \param output * The Buck regulator output. See \ref cy_en_syspm_buck_out_t. * * \return * The current state of the requested output. True if the requested output * is enabled. * False if the requested output is disabled. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_BuckIsOutputEnabled * *******************************************************************************/ bool Cy_SysPm_BuckIsOutputEnabled(cy_en_syspm_buck_out_t output) { CY_ASSERT_L3(CY_SYSPM_IS_BUCK_OUTPUT_VALID(output)); bool retVal = false; if (output == CY_SYSPM_BUCK_VBUCK_1) { retVal = (_FLD2BOOL(SRSS_PWR_BUCK_CTL_BUCK_OUT1_EN, SRSS->PWR_BUCK_CTL)); } #if (0u != SRSS_SIMOBUCK_PRESENT) if(output == CY_SYSPM_BUCK_VRF) { retVal = ((0U != _FLD2VAL(SRSS_PWR_BUCK_CTL2_BUCK_OUT2_HW_SEL, SRSS->PWR_BUCK_CTL2)) || (0U != _FLD2VAL(SRSS_PWR_BUCK_CTL2_BUCK_OUT2_EN, SRSS->PWR_BUCK_CTL2))); } #endif /* (0u != SRSS_SIMOBUCK_PRESENT) */ return(retVal); } #if(0u != SRSS_SIMOBUCK_PRESENT) /******************************************************************************* * Function Name: Cy_SysPm_BuckEnableVoltage2 ****************************************************************************//** * * Enable the output 2 voltage (Vbuckrf) of the SIMO Buck regulator. * The output 2 voltage (Vbuckrf) of the Buck regulator is used to supply * the BLE HW block. * When the Buck regulator is switched off, the function enables the * regulator and after it, enables output 2. * * \note The function does not affect Buck output 1 that can supply * a core. * * \warning The function does not select the Buck output 2 voltage and * does not set/clear the HW-controlled bit for Buck output 2. Call * Cy_SysPm_BuckSetVoltage2() or Cy_SysPm_BuckSetVoltage2HwControl() to * configure the Buck output 2. * * The function is applicable for devices with the SIMO Buck regulator. * Refer to device datasheet about information if device contains * SIMO Buck. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_BuckEnableVoltage2 * *******************************************************************************/ void Cy_SysPm_BuckEnableVoltage2(void) { if(!Cy_SysPm_BuckIsEnabled()) { /* Enable the SIMO Buck regulator */ SRSS->PWR_BUCK_CTL |= _VAL2FLD(SRSS_PWR_BUCK_CTL_BUCK_EN, 1U); } /* Enable the SIMO Buck output 2 */ SRSS->PWR_BUCK_CTL2 |= _VAL2FLD(SRSS_PWR_BUCK_CTL2_BUCK_OUT2_EN, 1U); /* Wait until the output is stable */ Cy_SysLib_DelayUs(CY_SYSPM_BUCK_BLE_SUPPLY_STABLE_US); } /******************************************************************************* * Function Name: Cy_SysPm_BuckSetVoltage2 ****************************************************************************//** * * This function sets output voltage 2 of the SIMO Buck regulator. * * \param voltage * The voltage of the Buck regulator output 2. * See \ref cy_en_syspm_buck_voltage2_t. * * \param waitToSettle * True - Enable the 200 us delay after setting a higher voltage. * False - Disable the 200 us delay after setting a higher voltage. * * \warning You must enable the delay (waitToSettle = true) * while changing from a lower voltage to a higher voltage. * * \note The 200 us delay is required only when changing from a * lower voltage to a higher voltage. Changing from a higher voltage to a lower one, * the delay is not required. * * The function is applicable for devices with the SIMO Buck regulator. * Refer to device datasheet about information if device contains * SIMO Buck. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_BuckSetVoltage2 * *******************************************************************************/ void Cy_SysPm_BuckSetVoltage2(cy_en_syspm_buck_voltage2_t voltage, bool waitToSettle) { uint32_t curVoltage; CY_ASSERT_L3(CY_SYSPM_IS_BUCK_VOLTAGE2_VALID(voltage)); /* Get the current voltage */ curVoltage = (uint32_t) Cy_SysPm_BuckGetVoltage2(); if((uint32_t) voltage != curVoltage) { SRSS->PWR_BUCK_CTL2 = _CLR_SET_FLD32U((SRSS->PWR_BUCK_CTL2), SRSS_PWR_BUCK_CTL2_BUCK_OUT2_SEL, (uint32_t) voltage); /* Delay to stabilize at the new voltage is required only * when changing from a lower voltage to a higher voltage. */ if(waitToSettle && ((uint32_t) voltage > curVoltage)) { Cy_SysLib_DelayUs(BUCK_STABILIZATION_DELAY_US); } } } #endif /* (0u != SRSS_SIMOBUCK_PRESENT) */ #endif /* (0u != SRSS_BUCKCTL_PRESENT) */ /******************************************************************************* * Function Name: Cy_SysPm_LdoSetVoltage ****************************************************************************//** * * Set an output voltage on the LDO. * * When changing from a higher voltage to a lower voltage, ensure that: * * The device maximum operating frequency for all the Clk_HF paths, peripheral, * and slow clock are under the \ref group_syspm_ulp_limitations. * * The total current consumption is under the \ref group_syspm_ulp_limitations. * * The appropriate wait states values are set for the flash using * the Cy_SysLib_SetWaitStates() function as explained below. * * <b>Setting wait states values for Flash</b> * * The flash access time when the core output voltage is 0.9 V (nominal) is * longer than at 1.1 V (nominal). Therefore, the number of the wait states must * be adjusted. Use the Cy_SysLib_SetWaitStates() function to set the appropriate * wait state values for flash. * * To change from a higher voltage to a lower voltage 0.9 V (nominal), * call the Cy_SysLib_SetWaitStates(true, hfClkFreqMz) function before changing * the voltage, where hfClkFreqMz is the frequency of HfClk0 in MHz. * * To change from a lower voltage to a higher voltage 1.1 V (nominal), calling * the Cy_SysLib_SetWaitStates(false, hfClkFreqMz) function is to set the * wait states is optional, but can be done to improve the performance. * The clock frequency may now be increased up to \ref group_syspm_lp_limitations * for a new voltage. * * \note 1. The output is set to 0.9 V (nominal) - the flash works in the * Read-only operation. * \note 2. The output is set to 1.1 V (nominal) - the flash works in the Read * and Write operations. * \note 3. The actual device Vccd voltage can be different from the nominal * voltage because the actual voltage value depends on the conditions * including the load current. * * For more details refer to the \ref group_syspm_managing_core_regulators * section. * Refer to the \ref group_syslib driver for more details about setting the wait * states. * * \param voltage * The desired output regulator voltage. * See \ref cy_en_syspm_ldo_voltage_t voltage * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_VoltageRegulator * *******************************************************************************/ void Cy_SysPm_LdoSetVoltage(cy_en_syspm_ldo_voltage_t voltage) { CY_ASSERT_L3(CY_SYSPM_IS_LDO_VOLTAGE_VALID(voltage)); uint32_t interruptState; interruptState = Cy_SysLib_EnterCriticalSection(); if (Cy_SysPm_LdoGetVoltage() != voltage) { uint32_t trimVoltage; if (CY_SYSPM_LDO_VOLTAGE_0_9V == voltage) { /* Set the analog signal bit for the flash before the voltage is changed * from 1.1 V to 0.9 V. Store trimmed voltage value into the local variable */ SetVoltageBitForFlash(); /* Update read-write margin value for the ULP mode */ SetReadMarginTrimUlp(); SRSS->PWR_TRIM_PWRSYS_CTL = _CLR_SET_FLD32U((SRSS->PWR_TRIM_PWRSYS_CTL), SRSS_PWR_TRIM_PWRSYS_CTL_ACT_REG_TRIM, LDO_OUT_VOLTAGE_0_95V); /* Update write assist value for the ULP mode */ SetWriteAssistTrimUlp(); trimVoltage = SFLASH->LDO_0P9V_TRIM; } else { SRSS->PWR_TRIM_PWRSYS_CTL = _CLR_SET_FLD32U((SRSS->PWR_TRIM_PWRSYS_CTL), SRSS_PWR_TRIM_PWRSYS_CTL_ACT_REG_TRIM, LDO_OUT_VOLTAGE_0_95V); /* A delay for the supply to stabilize at the new higher voltage */ Cy_SysLib_DelayUs(LDO_STABILIZATION_DELAY_US); /* Update write assist value for the LP mode */ SetWriteAssistTrimLp(); trimVoltage = SFLASH->LDO_1P1V_TRIM; } /* The system may continue operating while the voltage on Vccd * discharges to the new voltage. The time it takes to reach the * new voltage depends on the conditions, including the load current on * Vccd and the external capacitor size */ SRSS->PWR_TRIM_PWRSYS_CTL = _CLR_SET_FLD32U((SRSS->PWR_TRIM_PWRSYS_CTL), SRSS_PWR_TRIM_PWRSYS_CTL_ACT_REG_TRIM, trimVoltage); if (CY_SYSPM_LDO_VOLTAGE_1_1V == voltage) { /* A delay for the supply to stabilize at the new higher voltage */ Cy_SysLib_DelayUs(LDO_STABILIZATION_DELAY_US); /* Update read-write margin value for the LP mode */ SetReadMarginTrimLp(); /* Set the analog signal bit to the flash macro register after * the output voltage is 1.1 V */ ClearVoltageBitForFlash(); } } Cy_SysLib_ExitCriticalSection(interruptState); } /******************************************************************************* * Function Name: Cy_SysPm_RegisterCallback ****************************************************************************//** * * Registers a new syspm callback. * * A callback is a function called after an event in the driver or * middleware module has occurred. The handler callback API will be executed if * the specific event occurs. See \ref cy_stc_syspm_callback_t. * * \note The registered callbacks are executed in two orders, based on callback * mode \ref cy_en_syspm_callback_mode_t. For modes CY_SYSPM_CHECK_READY and * CY_SYSPM_BEFORE_TRANSITION, the order is this: the first registered callback * will be always the first executed. And the last registered callback will be * executed as the last callback. For modes CY_SYSPM_AFTER_TRANSITION and * CY_SYSPM_CHECK_FAIL, the order is this: the first registered callback will be * always the last executed. And the last registered callback will be executed * as the first callback. * * \param handler * The address of the syspm callback structure. * See \ref cy_stc_syspm_callback_t. * \note Do not modify the registered structure in run-time. * * \return * True if a callback was registered; <br> * False if a callback was not registered or maximum callbacks were registered. * * It is allowed to register up to 32 callbacks. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_Callback_Func_Declaration * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_Callback_Params_Declaration * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_Callback_Structure_Declaration * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_Callback_Func_Implementation * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_RegisterCallback * *******************************************************************************/ bool Cy_SysPm_RegisterCallback(cy_stc_syspm_callback_t* handler) { uint32_t interruptState; bool retStatus = false; interruptState = Cy_SysLib_EnterCriticalSection(); /* Check if the maximum callbacks were registered and verify input */ retStatus = ((handler != NULL) && (curRegisteredCallbacks < CY_SYSPM_CALLBACKS_NUMBER_MAX)); if (retStatus) { if ((handler->callbackParams != NULL) && (handler->callback != NULL)) { cy_stc_syspm_callback_t* curCallback = callbackRoot; cy_stc_syspm_callback_t* lastRegCallback = NULL; /* Search last registered callback item */ while (curCallback != NULL) { if (curCallback == handler) { /* Do not register already registered callback item */ retStatus = false; break; } /* Safe callback before switching into the next item */ lastRegCallback = curCallback; curCallback = curCallback->nextItm; } /* Link requested callback item to the linked list */ if (retStatus) { if (callbackRoot == NULL) { /* Link first callback item to the linked list */ callbackRoot = handler; } else { /* Link requested item to previous item */ lastRegCallback->nextItm = handler; } /* Update links to next and previous callback items of requested * callback item */ handler->prevItm = lastRegCallback; handler->nextItm = NULL; /* Increment the value with number of registered callbacks */ ++curRegisteredCallbacks; } } else { retStatus = false; } } Cy_SysLib_ExitCriticalSection(interruptState); return(retStatus); } /******************************************************************************* * Function Name: Cy_SysPm_UnregisterCallback ****************************************************************************//** * * This function unregisters a callback. * * The registered callback can be unregistered. Otherwise, false will be * returned. * * \param handler The item that should be unregistered. * See \ref cy_stc_syspm_callback_t. * * \return * True if on success <br> * False if it was not unregistered or no callbacks were registered. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_UnregisterCallback * *******************************************************************************/ bool Cy_SysPm_UnregisterCallback(cy_stc_syspm_callback_t const *handler) { uint32_t interruptState; bool retStatus = false; interruptState = Cy_SysLib_EnterCriticalSection(); /* Check if there was at least one callback registered */ if (curRegisteredCallbacks > 0UL) { cy_stc_syspm_callback_t* curCallback = callbackRoot; /* Search requested callback item in the linked list */ while (curCallback != NULL) { /* Requested callback is found */ if (curCallback == handler) { retStatus = true; break; } /* Go to next callback item in the linked list */ curCallback = curCallback->nextItm; } if (retStatus) { /* Requested callback is first in the list */ if (callbackRoot == handler) { /* Check whether this the only callback registered */ if (callbackRoot->nextItm != NULL) { callbackRoot = callbackRoot->nextItm; callbackRoot->prevItm = NULL; } } else { /* Update links of related to unregistered callback items */ curCallback->prevItm->nextItm = curCallback->nextItm; if (curCallback->nextItm != NULL) { curCallback->nextItm->prevItm = curCallback->prevItm; } } /* Decrement the value with number of registered callbacks */ --curRegisteredCallbacks; if (curRegisteredCallbacks == 0UL) { callbackRoot = NULL; } } } Cy_SysLib_ExitCriticalSection(interruptState); return(retStatus); } /******************************************************************************* * Function Name: Cy_SysPm_ExecuteCallback ****************************************************************************//** * * The function executes all registered callbacks with provided type and mode. * \note This low-level function is being used by \ref Cy_SysPm_Sleep, * \ref Cy_SysPm_DeepSleep, \ref Cy_SysPm_Hibernate, \ref Cy_SysPm_EnterLowPowerMode * and \ref Cy_SysPm_ExitLowPowerMode API functions, however might be also useful as * an independent API function in some custom applications. * \note The registered callbacks will be executed in order based on * \ref cy_en_syspm_callback_type_t value. * The are possible two orders of callbacks execution: <br> * * From first registered to last registered. Such order is relevant to * callbacks with mode CY_SYSPM_CHECK_READY and CY_SYSPM_BEFORE_TRANSITION. * * Backward flow execution: from last executed callback to the * first registered. Such order is relevant to callbacks with mode * CY_SYSPM_AFTER_TRANSITION and CY_SYSPM_CHECK_FAIL. Note that, the last * registered callback function is skipped with mode CY_SYSPM_CHECK_FAIL. This * is because the callback that returned CY_SYSPM_FAIL already knows that it failed. * * If no callbacks are registered, returns CY_SYSPM_SUCCESS. * * \param type * The callback type. See \ref cy_en_syspm_callback_type_t. * * \param mode * The callback mode. See \ref cy_en_syspm_callback_mode_t. * * \note * If mode is CY_SYSPM_CHECK_READY or CY_SYSPM_BEFORE_TRANSITION the * all required callbacks would be executed in order from first * registered to last registered. * If mode is CY_SYSPM_CHECK_FAIL or CY_SYSPM_AFTER_TRANSITION the * all required callbacks would be executed in order from last executed callback * to first registered. * * \return * CY_SYSPM_SUCCESS Callback successfully completed or nor callbacks registered. * CY_SYSPM_FAIL one of executed callback(s) returned fail. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_ExecuteCallback * *******************************************************************************/ cy_en_syspm_status_t Cy_SysPm_ExecuteCallback(cy_en_syspm_callback_type_t type, cy_en_syspm_callback_mode_t mode) { static cy_stc_syspm_callback_t* lastExecutedCallback = NULL; cy_en_syspm_status_t retVal = CY_SYSPM_SUCCESS; cy_stc_syspm_callback_t* curCallback; cy_stc_syspm_callback_params_t curParams; CY_ASSERT_L3(CY_SYSPM_IS_CALLBACK_TYPE_VALID(type)); CY_ASSERT_L3(CY_SYSPM_IS_CALLBACK_MODE_VALID(mode)); if((mode == CY_SYSPM_BEFORE_TRANSITION) || (mode == CY_SYSPM_CHECK_READY)) { /* Execute registered callbacks with order from first registered to the * last registered. The modes defined in the .skipMode element are not * executed */ curCallback = callbackRoot; while((curCallback != NULL) && (retVal != CY_SYSPM_FAIL)) { if((curCallback->type == type) && ((0U == curCallback->skipMode) || (0U == ((uint32_t) mode & curCallback->skipMode)))) { /* Update elements for local callback parameter values */ curParams.base = curCallback->callbackParams->base; curParams.context = curCallback->callbackParams->context; curParams.mode = mode; retVal = curCallback->callback(&curParams); /* Update callback pointer with value of executed callback. * Such update is required to execute further callbacks in * backward order after exit from low power mode or to undo * configuration after callback returned fail: from last executed * to first registered. */ lastExecutedCallback = curCallback; } curCallback = curCallback->nextItm; } } else { /* Execute registered callbacks with order from lastCallback to * the first registered callback. Such a flow is required if previous * callback function returned CY_SYSPM_FAIL or previous callback mode was * CY_SYSPM_BEFORE_TRANSITION. Such an order is required to undo configurations in * correct backward order. */ curCallback = lastExecutedCallback; /* Skip last executed callback that returned CY_SYSPM_FAIL, as this * callback already knows that it failed */ if ((mode == CY_SYSPM_CHECK_FAIL) && (curCallback != NULL)) { curCallback = curCallback->prevItm; } /* Execute all registered callback functions with required type and mode */ while ((curCallback != NULL) && (retVal != CY_SYSPM_FAIL)) { if ((curCallback->type == type) && ((curCallback->skipMode == 0UL) || (((uint32_t) mode & curCallback->skipMode) == 0UL))) { /* Update elements for local callback parameter values */ curParams.base = curCallback->callbackParams->base; curParams.context = curCallback->callbackParams->context; curParams.mode = mode; retVal = curCallback->callback(&curParams); } curCallback = curCallback->prevItm; } } return (retVal); } /** \cond INTERNAL */ /******************************************************************************* * Function Name: Cy_SysPm_IoFreeze ****************************************************************************//** * * This function saves the output states and configuration of I/O cells. * * I/O-cell configuration can be changed while I/O-cells are frozen. The new * configuration becomes effective only after the pins are unfrozen. * * Cy_SysPm_Hibernate() calls this function to freeze the I/O cells while * entering hibernate. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_Freeze * *******************************************************************************/ void Cy_SysPm_IoFreeze(void) { uint32_t interruptState; uint32_t regValue; interruptState = Cy_SysLib_EnterCriticalSection(); /* Check the FREEZE state to avoid a recurrent I/O-cells freeze attempt, * because the second call to this function will cause an accidental switch * to Hibernate mode (the system will enter Hibernate mode immediately * after writing to the hibernate bit because both UNLOCK and FREEZE were set * correctly in the previous call to this function). */ if(0U == _FLD2VAL(SRSS_PWR_HIBERNATE_FREEZE, SRSS->PWR_HIBERNATE)) { /* Clear the unlock field for correct freeze of the I/O cells */ SRSS->PWR_HIBERNATE = _CLR_SET_FLD32U((SRSS->PWR_HIBERNATE), SRSS_PWR_HIBERNATE_UNLOCK, 0U); /* Disable overriding by the peripherals the next pin-freeze command */ SRSS->PWR_HIBERNATE |= CY_SYSPM_PWR_SET_HIBERNATE; /* The second write causes freeze of I/O cells to save the I/O-cell state */ regValue = SRSS->PWR_HIBERNATE; SRSS->PWR_HIBERNATE = regValue; } Cy_SysLib_ExitCriticalSection(interruptState); } /** \endcond */ /******************************************************************************* * Function Name: Cy_SysPm_IoUnfreeze ****************************************************************************//** * * This function unfreezes the I/O cells which were automatically frozen when the * Hibernate is entered with the call to \ref Cy_SysPm_Hibernate(). * * I/O-cells remain frozen after a wakeup from hibernate mode until the * firmware unfreezes them, by calling this function. * * If the firmware must retain the data value on the port, then the * value must be read and re-written to the data register before calling this * function. Furthermore, the drive mode must be re-programmed before the pins are * unfrozen. If this is not done, the pin will change to the default state * the moment the freeze is removed. * * Note that I/O cell configuration can be changed while frozen. The new * configuration becomes effective only after the pins are unfrozen. * * \funcusage * \snippet syspm/syspm_2_10_sut_01.cydsn/main_cm4.c snippet_Cy_SysPm_IoUnfreeze * *******************************************************************************/ void Cy_SysPm_IoUnfreeze(void) { uint32_t interruptState; interruptState = Cy_SysLib_EnterCriticalSection(); /* Preserve the last reset reason and wakeup polarity. Then, unfreeze I/O: * write PWR_HIBERNATE.FREEZE=0, .UNLOCK=0x3A, .HIBERANTE=0, */ SRSS->PWR_HIBERNATE = (SRSS->PWR_HIBERNATE & CY_SYSPM_PWR_RETAIN_HIBERNATE_STATUS) | CY_SYSPM_PWR_HIBERNATE_UNLOCK; /* Lock the hibernate mode: * write PWR_HIBERNATE.HIBERNATE=0, UNLOCK=0x00, HIBERANTE=0 */ SRSS->PWR_HIBERNATE &= CY_SYSPM_PWR_RETAIN_HIBERNATE_STATUS; /* Read register to make sure it is settled */ (void) SRSS->PWR_HIBERNATE; Cy_SysLib_ExitCriticalSection(interruptState); } /******************************************************************************* * Function Name: SetVoltageBitForFlash ****************************************************************************//** * * The internal function that changes the Vcc setting for the flash. * * Sets the bit for the flash macro register. This bit should be set when the * voltage for the core regulators is less than 0.99 V. * *******************************************************************************/ static void SetVoltageBitForFlash(void) { FLASHC_FM_CTL->ANA_CTL0 |= _VAL2FLD(FLASHC_FM_CTL_ANA_CTL0_VCC_SEL, 1U); } /******************************************************************************* * Function Name: ClearVoltageBitForFlash ****************************************************************************//** * * This is the internal function that changes the Vcc setting for the flash. * * Clears the bit for the flash macro register. This bit should * be cleared if the output voltage for the core regulators is higher than 0.99 V. * *******************************************************************************/ static void ClearVoltageBitForFlash(void) { FLASHC_FM_CTL->ANA_CTL0 &= ((uint32_t) (~_VAL2FLD(FLASHC_FM_CTL_ANA_CTL0_VCC_SEL, 1U))); } #ifdef CY_IP_MXUDB /******************************************************************************* * Function Name: SaveRegisters ****************************************************************************//** * * The internal function saves non-retained registers before entering Deep Sleep. * Cypress ID #280370. * * \param regs * The structure where the registers are saved before Deep Sleep. * *******************************************************************************/ static void SaveRegisters(cy_stc_syspm_backup_regs_t *regs) { /* Save the registers before deep sleep */ regs->CY_UDB_UDBIF_BANK_CTL_REG = UDB->UDBIF.BANK_CTL; regs->CY_UDB_BCTL_MDCLK_EN_REG = UDB->BCTL.MDCLK_EN; regs->CY_UDB_BCTL_MBCLK_EN_REG = UDB->BCTL.MBCLK_EN; regs->CY_UDB_BCTL_BOTSEL_L_REG = UDB->BCTL.BOTSEL_L; regs->CY_UDB_BCTL_BOTSEL_U_REG = UDB->BCTL.BOTSEL_U; regs->CY_UDB_BCTL_QCLK_EN0_REG = UDB->BCTL.QCLK_EN[0U]; regs->CY_UDB_BCTL_QCLK_EN1_REG = UDB->BCTL.QCLK_EN[1U]; regs->CY_UDB_BCTL_QCLK_EN2_REG = UDB->BCTL.QCLK_EN[2U]; } /******************************************************************************* * Function Name: RestoreRegisters ****************************************************************************//** * * The internal function restores the non-retained registers after * leaving the Deep Sleep power mode. Cypress ID #280370. * * \param regs * The structure with data stored into the required non-retained registers * after Deep Sleep. * *******************************************************************************/ static void RestoreRegisters(cy_stc_syspm_backup_regs_t const *regs) { /* Restore the registers after deep sleep */ UDB->BCTL.MDCLK_EN = regs->CY_UDB_BCTL_MDCLK_EN_REG; UDB->BCTL.MBCLK_EN = regs->CY_UDB_BCTL_MBCLK_EN_REG; UDB->BCTL.BOTSEL_L = regs->CY_UDB_BCTL_BOTSEL_L_REG; UDB->BCTL.BOTSEL_U = regs->CY_UDB_BCTL_BOTSEL_U_REG; UDB->BCTL.QCLK_EN[0U] = regs->CY_UDB_BCTL_QCLK_EN0_REG; UDB->BCTL.QCLK_EN[1U] = regs->CY_UDB_BCTL_QCLK_EN1_REG; UDB->BCTL.QCLK_EN[2U] = regs->CY_UDB_BCTL_QCLK_EN2_REG; UDB->UDBIF.BANK_CTL = regs->CY_UDB_UDBIF_BANK_CTL_REG; } #endif /* CY_IP_MXUDB */ #if defined(CY_DEVICE_PSOC6ABLE2) && !defined(CY_PSOC6ABLE2_REV_0A_SUPPORT_DISABLE) /******************************************************************************* * Function Name: Cy_EnterDeepSleep ****************************************************************************//** * * The internal function that prepares the system for Deep Sleep and * restores the system after a wakeup from Deep Sleep. * * \param waitFor Selects wait for action. See \ref cy_en_syspm_waitfor_t. * *******************************************************************************/ #if defined (__ICCARM__) #pragma diag_suppress=Ta023 __ramfunc #else CY_SECTION(".cy_ramfunc") CY_NOINLINE #endif static void Cy_EnterDeepSleep(cy_en_syspm_waitfor_t waitFor) { /* Acquire the IPC to prevent changing of the shared resources at the same time */ while(0U == _FLD2VAL(IPC_STRUCT_ACQUIRE_SUCCESS, SYSPM_IPC_STC->ACQUIRE)) { /* Wait until the IPC structure is released by another core */ } /* Set the flag that current core entered Deep Sleep */ SYSPM_IPC_STC->DATA |= CUR_CORE_DP_MASK; /* Change the slow and fast clock dividers only under condition that * the other core is already in Deep Sleep. Cypress ID #284516 */ if (0U != (SYSPM_IPC_STC->DATA & OTHER_CORE_DP_MASK)) { /* Get the divider values of the slow and high clocks and store them into * the IPC data register */ SYSPM_IPC_STC->DATA = (SYSPM_IPC_STC->DATA & ((uint32_t) ~(SYSPM_FAST_CLK_DIV_Msk | SYSPM_SLOW_CLK_DIV_Msk))) | (((uint32_t)(_FLD2VAL(CPUSS_CM0_CLOCK_CTL_SLOW_INT_DIV, CPUSS->CM0_CLOCK_CTL) << SYSPM_SLOW_CLK_DIV_Pos)) | ((uint32_t)(_FLD2VAL(CPUSS_CM4_CLOCK_CTL_FAST_INT_DIV, CPUSS->CM4_CLOCK_CTL) << SYSPM_FAST_CLK_DIV_Pos))); /* Increase the clock divider for the slow and fast clocks to SYSPM_CLK_DIVIDER */ CPUSS->CM0_CLOCK_CTL = _CLR_SET_FLD32U(CPUSS->CM0_CLOCK_CTL, CPUSS_CM0_CLOCK_CTL_SLOW_INT_DIV, SYSPM_CLK_DIVIDER); CPUSS->CM4_CLOCK_CTL = _CLR_SET_FLD32U(CPUSS->CM4_CLOCK_CTL, CPUSS_CM4_CLOCK_CTL_FAST_INT_DIV, SYSPM_CLK_DIVIDER); /* Read the divider value to make sure it is set */ (void) CPUSS->CM0_CLOCK_CTL; (void) CPUSS->CM4_CLOCK_CTL; } /* Release the IPC */ SYSPM_IPC_STC->RELEASE = 0U; /* Read this register to make sure it is settled */ (void) SYSPM_IPC_STC->RELEASE; #if(0u != CY_CPU_CORTEX_M0P) /* The CPU enters the Deep Sleep mode upon execution of WFI/WFE */ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; if(waitFor != CY_SYSPM_WAIT_FOR_EVENT) { __WFI(); } else { __WFE(); } #else /* Repeat the WFI/WFE instructions if a wake up was not intended. * Cypress ID #272909 */ do { /* The CPU enters Deep Sleep mode upon execution of WFI/WFE */ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; if(waitFor != CY_SYSPM_WAIT_FOR_EVENT) { __WFI(); } else { __WFE(); /* Call the WFE instructions twice to clear the Event register * of the CM4 core. Cypress ID #279077 */ if(wasEventSent) { __WFE(); } wasEventSent = true; } } while (_FLD2VAL(CPUSS_CM4_PWR_CTL_PWR_MODE, CPUSS->CM4_PWR_CTL) == CY_SYSPM_CM4_PWR_RETAINED); #endif /* (0u != CY_CPU_CORTEX_M0P) */ /* Acquire the IPC to prevent changing of the shared resources at the same time */ while(0U == _FLD2VAL(IPC_STRUCT_ACQUIRE_SUCCESS, SYSPM_IPC_STC->ACQUIRE)) { /* Wait until the IPC structure is released by another core */ } /* Read and change the slow and fast clock dividers only under condition * that the other core is already in Deep Sleep. Cypress ID #284516 */ if(0U != (SYSPM_IPC_STC->DATA & OTHER_CORE_DP_MASK)) { /* Restore the clock dividers for the slow and fast clocks */ CPUSS->CM0_CLOCK_CTL = (_CLR_SET_FLD32U(CPUSS->CM0_CLOCK_CTL, CPUSS_CM0_CLOCK_CTL_SLOW_INT_DIV, (_FLD2VAL(SYSPM_SLOW_CLK_DIV, SYSPM_IPC_STC->DATA)))); CPUSS->CM4_CLOCK_CTL = (_CLR_SET_FLD32U(CPUSS->CM4_CLOCK_CTL, CPUSS_CM4_CLOCK_CTL_FAST_INT_DIV, (_FLD2VAL(SYSPM_FAST_CLK_DIV, SYSPM_IPC_STC->DATA)))); } /* Indicate that the current core is out of Deep Sleep */ SYSPM_IPC_STC->DATA &= ((uint32_t) ~CUR_CORE_DP_MASK); /* Release the IPC */ SYSPM_IPC_STC->RELEASE = 0U; } #if defined (__ICCARM__) #pragma diag_default=Ta023 #endif #endif /* defined(CY_DEVICE_PSOC6ABLE2) && !defined(CY_PSOC6ABLE2_REV_0A_SUPPORT_DISABLE) */ /******************************************************************************* * Function Name: EnterDeepSleep ****************************************************************************//** * * The internal function that prepares the system for Deep Sleep, * sets the CPU core to the Deep Sleep, and restores the system after a * wakeup from Deep Sleep. * * \param waitFor * Selects wait for action. See \ref cy_en_syspm_waitfor_t. * *******************************************************************************/ #if defined (__ICCARM__) #pragma diag_suppress=Ta023 __ramfunc #else CY_SECTION(".cy_ramfunc") CY_NOINLINE #endif static void EnterDeepSleep(cy_en_syspm_waitfor_t waitFor) { #if(0u != CY_CPU_CORTEX_M0P) /* The CPU enters the Deep Sleep mode upon execution of WFI/WFE */ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; if(waitFor != CY_SYSPM_WAIT_FOR_EVENT) { __WFI(); } else { __WFE(); } #else /* Repeat the WFI/WFE instructions if a wake up was not intended. * Cypress ID #272909 */ do { /* The CPU enters Deep Sleep mode upon execution of WFI/WFE */ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; if(waitFor != CY_SYSPM_WAIT_FOR_EVENT) { __WFI(); } else { __WFE(); /* Call the WFE instructions twice to clear the Event register * of the CM4 core. Cypress ID #279077 */ if(wasEventSent) { __WFE(); } wasEventSent = true; } } while (_FLD2VAL(CPUSS_CM4_PWR_CTL_PWR_MODE, CPUSS->CM4_PWR_CTL) == CY_SYSPM_CM4_PWR_RETAINED); #endif /* (0u != CY_CPU_CORTEX_M0P) */ /* Acquire the IPC to prevent changing of the shared resources at the same time. * Shared resources is the BIST_DATA[0] register. */ while(0U == _FLD2VAL(IPC_STRUCT_ACQUIRE_SUCCESS, SYSPM_IPC_STC->ACQUIRE)) { /* Wait until the IPC structure is released by another core */ } /* Set 10 uS delay only under condition that the DELAY_DONE_FLAG is * cleared. Cypress ID #288510 */ if(DELAY_DONE_FLAG->BIST_DATA[0] == NEED_DELAY) { /* Configure the counter to be sourced by IMO */ TST_DDFT_SLOW_CTL_REG = TST_DDFT_SLOW_CTL_MASK; CLK_OUTPUT_SLOW_REG = CLK_OUTPUT_SLOW_MASK; TST_DDFT_FAST_CTL_REG = TST_DDFT_FAST_CTL_MASK; /* Load the down-counter to count the 10 uS */ CLK_CAL_CNT1_REG = IMO_10US_DELAY; while(0U == (CLK_CAL_CNT1_REG & CLK_CAL_CNT1_DONE)) { /* Wait until the counter stops counting */ } /* Indicate that 10 uS delay was done */ DELAY_DONE_FLAG->BIST_DATA[0] = DELAY_DONE; } /* Release the IPC structure in do while loop just to sure that this code * is not optimized */ do { SYSPM_IPC_STC->RELEASE = 0U; } while (0U != 0U); } #if defined (__ICCARM__) #pragma diag_default=Ta023 #endif /******************************************************************************* * Function Name: SetReadMarginTrimUlp ****************************************************************************//** * * This is the internal function that updates the read-margin trim values for the * RAM and ROM. The trim update is done during transition of regulator voltage * from higher to a lower one. * *******************************************************************************/ static void SetReadMarginTrimUlp(void) { /* Update read-write margin value for the ULP mode. Cypress ID#297292 */ CPUSS->TRIM_RAM_CTL = (CPUSS->TRIM_RAM_CTL & ((uint32_t) ~CPUSS_TRIM_RAM_CTL_RM_Msk)) | (CPUSS_TRIM_RAM_ULP & CPUSS_TRIM_RAM_CTL_RM_Msk); CPUSS->TRIM_ROM_CTL = (CPUSS->TRIM_ROM_CTL & ((uint32_t) ~CPUSS_TRIM_ROM_CTL_RM_Msk)) | (CPUSS_TRIM_ROM_ULP & CPUSS_TRIM_ROM_CTL_RM_Msk); } /******************************************************************************* * Function Name: SetReadMarginTrimLp ****************************************************************************//** * * The internal function which updates the read-margin trim values for the * RAM and ROM. The trim update is done during transition of regulator voltage * from lower to a higher one. * *******************************************************************************/ static void SetReadMarginTrimLp(void) { /* Update read-write margin value for the LP mode. Cypress ID#297292 */ CPUSS->TRIM_RAM_CTL = (CPUSS->TRIM_RAM_CTL & ((uint32_t) ~CPUSS_TRIM_RAM_CTL_RM_Msk)) | (CPUSS_TRIM_RAM_LP & CPUSS_TRIM_RAM_CTL_RM_Msk); CPUSS->TRIM_ROM_CTL = (CPUSS->TRIM_ROM_CTL & ((uint32_t) ~CPUSS_TRIM_ROM_CTL_RM_Msk)) | (CPUSS_TRIM_ROM_LP & CPUSS_TRIM_ROM_CTL_RM_Msk); } /******************************************************************************* * Function Name: SetWriteAssistTrimUlp ****************************************************************************//** * * This is the internal function that updates the write assistant trim value for the * RAM. The trim update is done during transition of regulator voltage * from higher to a lower. * *******************************************************************************/ static void SetWriteAssistTrimUlp(void) { /* Update write assist value for the ULP mode. Cypress ID#297292 */ CPUSS->TRIM_RAM_CTL = (CPUSS->TRIM_RAM_CTL & ((uint32_t) ~CPUSS_TRIM_RAM_CTL_WA_Msk)) | (CPUSS_TRIM_RAM_ULP & CPUSS_TRIM_RAM_CTL_WA_Msk); } /******************************************************************************* * Function Name: SetWriteAssistTrimLp ****************************************************************************//** * * This is the internal function that updates the write assistant trim value for the * RAM. The trim update is done during transition of regulator voltage * from lower to a higher one. * *******************************************************************************/ static void SetWriteAssistTrimLp(void) { /* Update write assist value for the LP mode. Cypress ID#297292 */ CPUSS->TRIM_RAM_CTL = (CPUSS->TRIM_RAM_CTL & ((uint32_t) ~CPUSS_TRIM_RAM_CTL_WA_Msk)) | (CPUSS_TRIM_RAM_LP & CPUSS_TRIM_RAM_CTL_WA_Msk); } /* [] END OF FILE */
<filename>vm_tools/concierge/tap_device_builder.h // Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef VM_TOOLS_CONCIERGE_TAP_DEVICE_BUILDER_H_ #define VM_TOOLS_CONCIERGE_TAP_DEVICE_BUILDER_H_ #include <stdint.h> #include <string> #include <base/files/scoped_file.h> #include <chromeos/patchpanel/mac_address_generator.h> namespace vm_tools { namespace concierge { // Builds and configures a tap device. If the returned ScopedFD is valid then // the device has been properly configured. base::ScopedFD BuildTapDevice(const patchpanel::MacAddress& mac_addr, uint32_t ipv4_addr, uint32_t ipv4_netmask, bool vnet_hdr); // Opens and configures a tap device. If the returned ScopedFD is valid then // the device has been properly configured. // If |ifname_out| is non-null, it is populated with the final interface name. base::ScopedFD OpenTapDevice(const std::string& ifname_in, bool vnet_hdr, std::string* ifname_out); } // namespace concierge } // namespace vm_tools #endif // VM_TOOLS_CONCIERGE_TAP_DEVICE_BUILDER_H_
<gh_stars>0 /*- * Copyright (c) 2002-2018 The UbixOS Project. * All rights reserved. * * This was developed by <NAME> for the UbixOS Project. * * 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, the following disclaimer and the list of authors. * 2) Redistributions in binary form must reproduce the above copyright notice, this list of * conditions, the following disclaimer and the list of authors in the documentation and/or * other materials provided with the distribution. * 3) Neither the name of the UbixOS Project nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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. */ #include <ubixos/fork.h> #include <sys/types.h> #include <ubixos/sched.h> #include <ubixos/tty.h> #include <ubixos/vitals.h> #include <vmm/vmm.h> #include <string.h> #include <assert.h> #include <lib/kprintf.h> #include <sys/descrip.h> int sys_fork(struct thread *td, struct sys_fork_args *args) { struct taskStruct *newProcess; newProcess = schedNewTask(); /* * * Initalize New Task Information From Parrent * */ /* Set CWD */ memcpy(newProcess->oInfo.cwd, _current->oInfo.cwd, 1024); /* Set PPID */ newProcess->ppid = _current->id; /* Set PGRP */ newProcess->pgrp = _current->pgrp; /* Copy File Descriptor Table */ //memcpy(newProcess->files, _current->files, sizeof(fileDescriptor_t *) * MAX_OFILES); for (int i = 3; i < 64; i++) if (td->o_files[i]) { newProcess->td.o_files[i] = (struct file *)kmalloc(sizeof(struct file)); memcpy(newProcess->td.o_files[i], td->o_files[i], sizeof(struct file)); if (((struct file *)td->o_files[i])->fd) { ((struct file *)newProcess->td.o_files[i])->fd = kmalloc(sizeof(fileDescriptor_t)); memcpy( ((struct file *)newProcess->td.o_files[i])->fd, ((struct file *)td->o_files[i])->fd, sizeof(fileDescriptor_t)); if (((struct file *)td->o_files[i])->fd->buffer) { ((struct file *)newProcess->td.o_files[i])->fd->buffer = kmalloc(4096); memcpy(((struct file *)newProcess->td.o_files[i])->fd->buffer, ((struct file *)td->o_files[i])->fd->buffer, 4096); } } } /* Set Up Task State */ newProcess->tss.eip = td->frame->tf_eip; newProcess->oInfo.vmStart = _current->oInfo.vmStart; newProcess->term = _current->term; newProcess->term->owner = newProcess->id; newProcess->uid = _current->uid; newProcess->gid = _current->gid; newProcess->tss.back_link = 0x0; newProcess->tss.esp0 = _current->tss.esp0; newProcess->tss.ss0 = 0x10; newProcess->tss.esp1 = 0x0; newProcess->tss.ss1 = 0x0; newProcess->tss.esp2 = 0x0; newProcess->tss.ss2 = 0x0; newProcess->tss.eflags = td->frame->tf_eflags; newProcess->tss.eax = 0x0; newProcess->tss.ebx = td->frame->tf_ebx; newProcess->tss.ecx = td->frame->tf_ecx; newProcess->tss.edx = td->frame->tf_edx; newProcess->tss.esi = td->frame->tf_esi; newProcess->tss.edi = td->frame->tf_edi; newProcess->tss.ebp = td->frame->tf_ebp; newProcess->tss.esp = td->frame->tf_esp; newProcess->tss.cs = td->frame->tf_cs; // & 0xFF; newProcess->tss.ss = td->frame->tf_ss; // & 0xFF; newProcess->tss.ds = td->frame->tf_ds; //_current->tss.ds & 0xFF; newProcess->tss.fs = td->frame->tf_fs; //_current->tss.fs & 0xFF; newProcess->tss.gs = _current->tss.gs & 0xFF; newProcess->tss.es = td->frame->tf_es; //_current->tss.es & 0xFF; newProcess->tss.ldt = 0x18; newProcess->tss.trace_bitmap = 0x0000; newProcess->tss.io_map = 0x8000; newProcess->td.vm_tsize = _current->td.vm_tsize; newProcess->td.vm_taddr = _current->td.vm_taddr; newProcess->td.vm_dsize = _current->td.vm_dsize; newProcess->td.vm_daddr = _current->td.vm_daddr; //kprintf("Copying Mem Space! [0x%X:0x%X:0x%X:0x%X:0x%X:%i:%i]\n", newProcess->tss.esp0, newProcess->tss.esp, newProcess->tss.ebp, td->frame->tf_esi, td->frame->tf_eip, newProcess->id, _current->id); newProcess->tss.cr3 = (uInt32) vmm_copyVirtualSpace(newProcess->id); //kprintf( "Copied Mem Space! [0x%X]\n", newProcess->tss.cr3 ); newProcess->state = FORK; /* Fix gcc optimization problems */ while (newProcess->state == FORK) sched_yield(); newProcess->parent = _current; _current->children++; /* Return Id of Proccess */ td->td_retval[0] = newProcess->id; return (0); } /***************************************************************************************** Functoin: static int fork_copyProcess(struct taskStruct *newProcess,long ebp,long edi, long esi, long none,long ebx,long ecx,long edx,long eip,long cs,long eflags, long esp,long ss) Desc: This function will copy a process Notes: *****************************************************************************************/ /* Had to remove static though tihs function is only used in this file */ int fork_copyProcess(struct taskStruct *newProcess, long ebp, long edi, long esi, long none, long ebx, long ecx, long edx, long eip, long cs, long eflags, long esp, long ss) { volatile struct taskStruct * tmpProcPtr = newProcess; assert(newProcess); assert(_current); /* Set Up New Tasks Information */ memcpy(newProcess->oInfo.cwd, _current->oInfo.cwd, 1024); //kprintf( "Initializing New CWD!\n" ); newProcess->tss.eip = eip; newProcess->oInfo.vmStart = _current->oInfo.vmStart; newProcess->term = _current->term; newProcess->term->owner = newProcess->id; newProcess->uid = _current->uid; newProcess->gid = _current->gid; newProcess->tss.back_link = 0x0; newProcess->tss.esp0 = _current->tss.esp0; newProcess->tss.ss0 = 0x10; newProcess->tss.esp1 = 0x0; newProcess->tss.ss1 = 0x0; newProcess->tss.esp2 = 0x0; newProcess->tss.ss2 = 0x0; newProcess->tss.eflags = eflags; newProcess->tss.eax = 0x0; newProcess->tss.ebx = ebx; newProcess->tss.ecx = ecx; newProcess->tss.edx = edx; newProcess->tss.esi = esi; newProcess->tss.edi = edi; newProcess->tss.ebp = ebp; newProcess->tss.esp = esp; newProcess->tss.cs = cs & 0xFF; newProcess->tss.ss = ss & 0xFF; newProcess->tss.ds = _current->tss.ds & 0xFF; newProcess->tss.fs = _current->tss.fs & 0xFF; newProcess->tss.gs = _current->tss.gs & 0xFF; newProcess->tss.es = _current->tss.es & 0xFF; newProcess->tss.ldt = 0x18; newProcess->tss.trace_bitmap = 0x0000; newProcess->tss.io_map = 0x8000; newProcess->td.vm_tsize = _current->td.vm_tsize; newProcess->td.vm_taddr = _current->td.vm_taddr; newProcess->td.vm_dsize = _current->td.vm_dsize; newProcess->td.vm_daddr = _current->td.vm_daddr; /* Create A Copy Of The VM Space For New Task */ //MrOlsen 2018kprintf("Copying Mem Space! [0x%X:0x%X:0x%X:0x%X:0x%X:%i:%i:0x%X]\n", newProcess->tss.esp0, newProcess->tss.esp, newProcess->tss.ebp, esi, eip, newProcess->id, _current->id, newProcess->td.vm_daddr); newProcess->tss.cr3 = (uInt32) vmm_copyVirtualSpace(newProcess->id); //kprintf( "Copied Mem Space!\n" ); newProcess->state = FORK; /* Fix gcc optimization problems */ while (tmpProcPtr->state == FORK) sched_yield(); /* Return Id of Proccess */ kprintf("Returning! [%i]", _current->id); return (newProcess->id); } void qT() { kprintf("qT\n"); } /***************************************************************************************** Functoin: void sysFork(); Desc: This function will fork a new task Notes: 08/01/02 - This Seems To Be Working Fine However I'm Not Sure If I Chose The Best Path To Impliment It I Guess We Will See What The Future May Bring *****************************************************************************************/ //asm volatile( __asm( ".globl sysFork_old \n" "sysFork_old: \n" " xor %eax,%eax \n" " call schedNewTask \n" " testl %eax,%eax \n" " je fork_ret \n" " pushl %esi \n" " pushl %edi \n" " pushl %ebp \n" " pushl %eax \n" " call fork_copyProcess \n" " movl %eax,(%ebx) \n" " addl $16,%esp \n" "fork_ret: \n" " ret \n" ); /*** END ***/
<reponame>Fookdies301/GrinPlusPlus #pragma once #include <Crypto/Models/ed25519_public_key.h> #include <Crypto/Models/ed25519_secret_key.h> struct ed25519_keypair_t { ed25519_keypair_t() = default; ed25519_keypair_t(ed25519_public_key_t&& public_key_, ed25519_secret_key_t&& secret_key_) : public_key(std::move(public_key_)), secret_key(std::move(secret_key_)) { } ed25519_public_key_t public_key; ed25519_secret_key_t secret_key; };
<reponame>BryanHuang66/mn-addon-api #import <Foundation/NSObject.h> #import <Foundation/NSArray.h> #import <Foundation/NSRange.h> @import Foundation; @import JavaScriptCore; @protocol JSBNSObject; @protocol JSBNSFileHandle <JSExport, JSBNSObject> #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" @property (copy) void (^readabilityHandler)(NSFileHandle *); @property (copy) void (^writeabilityHandler)(NSFileHandle *); + (id)fileHandleWithStandardInput; + (id)fileHandleWithStandardOutput; + (id)fileHandleWithStandardError; + (id)fileHandleWithNullDevice; + (id)fileHandleForReadingAtPath:(NSString *)path; + (id)fileHandleForWritingAtPath:(NSString *)path; + (id)fileHandleForUpdatingAtPath:(NSString *)path; + (id)fileHandleForReadingFromURL:(NSURL *)url error:(NSError **)error; + (id)fileHandleForWritingToURL:(NSURL *)url error:(NSError **)error; + (id)fileHandleForUpdatingURL:(NSURL *)url error:(NSError **)error; - (NSData *)availableData; - (NSData *)readDataToEndOfFile; - (NSData *)readDataOfLength:(NSUInteger)length; - (void)writeData:(NSData *)data; - (unsigned long long)offsetInFile; - (unsigned long long)seekToEndOfFile; - (void)seekToFileOffset:(unsigned long long)offset; - (void)truncateFileAtOffset:(unsigned long long)offset; - (void)synchronizeFile; - (void)closeFile; - (void)readInBackgroundAndNotifyForModes:(NSArray *)modes; - (void)readInBackgroundAndNotify; - (void)readToEndOfFileInBackgroundAndNotifyForModes:(NSArray *)modes; - (void)readToEndOfFileInBackgroundAndNotify; - (void)acceptConnectionInBackgroundAndNotifyForModes:(NSArray *)modes; - (void)acceptConnectionInBackgroundAndNotify; - (void)waitForDataInBackgroundAndNotifyForModes:(NSArray *)modes; - (void)waitForDataInBackgroundAndNotify; - (int)fileDescriptor; #pragma clang diagnostic pop @end
// // MeasurNetTools.h // // // Created by jordan on 16/7/25. // Copyright © 2016年 MD313. All rights reserved. // typedef void (^measureBlock) (float speed); typedef void (^finishMeasureBlock) (float speed); #define timeCount .2 #import <Foundation/Foundation.h> @interface MeasurNetTools : NSObject /** * 初始化测速方法 * * @param measureBlock 实时返回测速信息 * @param finishMeasureBlock 最后完成时候返回平均测速信息 * * @return MeasurNetTools对象 */ - (instancetype)initWithblock:(measureBlock)measureBlock finishMeasureBlock:(finishMeasureBlock)finishMeasureBlock failedBlock:(void (^) (NSError *error))failedBlock; /** * 开始测速 */ -(void)startMeasur; /** * 停止测速,会通过block立即返回测试信息 */ -(void)stopMeasur; @end
/* * Generated by class-dump 3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2012 by <NAME>. */ #import "NSObject.h" #import "WKConnectionDelegate.h" #import "WKProcessGroupDelegate.h" @class NSArray, NSMapTable, NSMutableArray, NSString, WKBrowsingContextGroup; @interface MUIWebDocumentViewGroup : NSObject <WKConnectionDelegate, WKProcessGroupDelegate> { NSString *_userStyleSheet; NSArray *_userScripts; NSString *_processGroupName; unsigned long long _maxProcessCount; NSMutableArray *_processGroups; unsigned long long _processRotator; WKBrowsingContextGroup *_browsingContextGroup; NSMapTable *_wkConnectionsByProcessGroup; } + (id)_defaultUserStyleSheet; @property(retain, nonatomic) NSMapTable *wkConnectionsByProcessGroup; // @synthesize wkConnectionsByProcessGroup=_wkConnectionsByProcessGroup; @property(retain, nonatomic) WKBrowsingContextGroup *browsingContextGroup; // @synthesize browsingContextGroup=_browsingContextGroup; @property(nonatomic) unsigned long long processRotator; // @synthesize processRotator=_processRotator; @property(retain, nonatomic) NSMutableArray *processGroups; // @synthesize processGroups=_processGroups; @property(readonly, nonatomic) unsigned long long maxProcessCount; // @synthesize maxProcessCount=_maxProcessCount; @property(readonly, nonatomic) NSString *processGroupName; // @synthesize processGroupName=_processGroupName; @property(copy, nonatomic) NSArray *userScripts; - (void)_refreshUserScripts; - (id)_defaultUserScripts; - (id)effectiveUserStyle; @property(copy, nonatomic) NSString *userStyleSheet; - (void)_refreshUserStyleSheet; - (void)connectionDidClose:(id)arg1; - (void)connection:(id)arg1 didReceiveMessageWithName:(id)arg2 body:(id)arg3; - (void)processGroup:(id)arg1 didCreateConnectionToWebProcessPlugIn:(id)arg2; - (id)processGroup; - (void)dealloc; - (id)initWithMaxProcessCount:(unsigned long long)arg1 groupName:(id)arg2; - (id)init; @end
// // DDMService.h // DDMNetworking // // Created by NEUSOFT on 17/6/20. // Copyright © 2017年 NEUSOFT. All rights reserved. // #import <Foundation/Foundation.h> #import "DDMURLResponse.h" // 所有DDMService的派生类都要符合这个protocol @protocol DDMServiceProtocol <NSObject> @property (nonatomic, readonly) BOOL isOnline; @property (nonatomic, readonly) NSString *offlineApiBaseUrl; @property (nonatomic, readonly) NSString *onlineApiBaseUrl; @property (nonatomic, readonly) NSString *offlineApiVersion; @property (nonatomic, readonly) NSString *onlineApiVersion; @property (nonatomic, readonly) NSString *onlinePublicKey; @property (nonatomic, readonly) NSString *offlinePublicKey; @property (nonatomic, readonly) NSString *onlinePrivateKey; @property (nonatomic, readonly) NSString *offlinePrivateKey; @optional //为某些Service需要拼凑额外字段到URL处 - (NSDictionary *)extraParmas; //为某些Service需要拼凑额外的HTTPToken,如accessToken - (NSDictionary *)extraHttpHeadParmasWithMethodName:(NSString *)method; - (NSString *)urlGeneratingRuleByMethodName:(NSString *)method; //- (void)successedOnCallingAPI:(DDMURLResponse *)response; //提供拦截器集中处理Service错误问题,比如token失效要抛通知等 - (BOOL)shouldCallBackByFailedOnCallingAPI:(DDMURLResponse *)response; - (id)sessionManager; - (NSString *)downloadManagerPlistPath; - (NSInteger)maxConcurrentDownloadCount; @end @interface DDMService : NSObject @property (nonatomic, strong, readonly) NSString *publicKey; @property (nonatomic, strong, readonly) NSString *privateKey; @property (nonatomic, strong, readonly) NSString *apiBaseUrl; @property (nonatomic, strong, readonly) NSString *apiVersion; @property (nonatomic, weak, readonly) id<DDMServiceProtocol> child; /* * 因为考虑到每家公司的拼凑逻辑都有或多或少不同, * 如有的公司为http://abc.com/v2/api/login或者http://v2.abc.com/api/login * 所以将默认的方式,有versioin时,则为http://abc.com/v2/api/login * 否则,则为http://abc.com/v2/api/login */ - (NSString *)urlGeneratingRuleByMethodName:(NSString *)method; @end
#pragma once #include <Arduino.h> typedef enum { WL_IDLE_STATUS = 0, WL_NO_SSID_AVAIL = 1, WL_SCAN_COMPLETED = 2, WL_CONNECTED = 3, WL_CONNECT_FAILED = 4, WL_CONNECTION_LOST = 5, WL_WRONG_PASSWORD = 6, WL_DISCONNECTED = 7 } wl_status_t; /* Encryption modes */ enum wl_enc_type { /* Values map to 802.11 encryption suites... */ ENC_TYPE_WEP = 5, ENC_TYPE_TKIP = 2, ENC_TYPE_CCMP = 4, /* ... except these two, 7 and 8 are reserved in 802.11-2007 */ ENC_TYPE_NONE = 7, ENC_TYPE_AUTO = 8 }; enum wl_tcp_state { CLOSED = 0, LISTEN = 1, SYN_SENT = 2, SYN_RCVD = 3, ESTABLISHED = 4, FIN_WAIT_1 = 5, FIN_WAIT_2 = 6, CLOSE_WAIT = 7, CLOSING = 8, LAST_ACK = 9, TIME_WAIT = 10 };
// Copyright (c) 2014 Greenheart Games Pty. Ltd. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef SRC_GREENWORKS_WORKSHOP_WORKERS_H_ #define SRC_GREENWORKS_WORKSHOP_WORKERS_H_ #include "steam_async_worker.h" #include <map> #include <vector> #include "steam/steam_api.h" namespace greenworks { class FileShareWorker : public SteamCallbackAsyncWorker { public: FileShareWorker(Nan::Callback *success_callback, Nan::Callback *error_callback, const std::string &file_path); void OnFileShareCompleted(RemoteStorageFileShareResult_t *result, bool io_failure); void Execute() override; void HandleOKCallback() override; private: const std::string file_path_; UGCHandle_t share_file_handle_; CCallResult<FileShareWorker, RemoteStorageFileShareResult_t> call_result_; }; struct WorkshopFileProperties { static constexpr int MAX_TAGS = 100; std::string file_path; std::string image_path; std::string title; std::string description; std::vector<std::string> tags_scratch; const char *tags[MAX_TAGS]; }; class PublishWorkshopFileWorker : public SteamCallbackAsyncWorker { public: PublishWorkshopFileWorker(Nan::Callback *success_callback, Nan::Callback *error_callback, uint32 app_id, const WorkshopFileProperties &properties); void OnFilePublishCompleted(RemoteStoragePublishFileResult_t *result, bool io_failure); void Execute() override; void HandleOKCallback() override; private: uint32 app_id_; WorkshopFileProperties properties_; PublishedFileId_t publish_file_id_; CCallResult<PublishWorkshopFileWorker, RemoteStoragePublishFileResult_t> call_result_; }; class UpdatePublishedWorkshopFileWorker : public SteamCallbackAsyncWorker { public: UpdatePublishedWorkshopFileWorker(Nan::Callback *success_callback, Nan::Callback *error_callback, PublishedFileId_t published_file_id, const WorkshopFileProperties &properties); void OnCommitPublishedFileUpdateCompleted(RemoteStorageUpdatePublishedFileResult_t *result, bool io_failure); void Execute() override; private: PublishedFileId_t published_file_id_; WorkshopFileProperties properties_; CCallResult<UpdatePublishedWorkshopFileWorker, RemoteStorageUpdatePublishedFileResult_t> update_published_file_call_result_; }; // A base worker class for querying (user/all) ugc. class QueryUGCWorker : public SteamCallbackAsyncWorker { public: QueryUGCWorker(Nan::Callback *success_callback, Nan::Callback *error_callback); void OnUGCQueryCompleted(SteamUGCQueryCompleted_t *result, bool io_failure); void HandleOKCallback() override; void HandleErrorCallback() override; protected: std::vector<SteamUGCDetails_t> ugc_items_; std::map<PublishedFileId_t, PublishedFileId_t *> child_map_; std::map<PublishedFileId_t, std::string *> key_value_tags_keys_; std::map<PublishedFileId_t, std::string *> key_value_tags_values_; std::map<PublishedFileId_t, uint32> num_tags_; std::map<PublishedFileId_t, std::string *> tags_; std::map<PublishedFileId_t, std::string *> tags_display_names_; std::map<PublishedFileId_t, std::string *> additional_preview_urls_; std::map<PublishedFileId_t, EItemPreviewType *> additional_preview_types_; std::map<PublishedFileId_t, std::string> metadata_; std::map<PublishedFileId_t, std::string> preview_urls_; uint32 total_matching_results_; uint32 num_results_returned_; CCallResult<QueryUGCWorker, SteamUGCQueryCompleted_t> ugc_query_call_result_; }; // A base worker class for querying ugc details. class QueryUGCDetailsWorker : public QueryUGCWorker { public: QueryUGCDetailsWorker(Nan::Callback *success_callback, Nan::Callback *error_callback, PublishedFileId_t *id_list, uint32 num_ids); void Execute() override; void HandleOKCallback() override; void HandleErrorCallback() override; protected: PublishedFileId_t *item_ids_; uint32 num_ids_; }; class QueryUnknownUGCWorker : public QueryUGCWorker { public: QueryUnknownUGCWorker(Nan::Callback *success_callback, Nan::Callback *error_callback, EUGCMatchingUGCType ugc_matching_type, uint32 app_id, uint32 page_num); protected: EUGCMatchingUGCType ugc_matching_type_; uint32 app_id_; uint32 page_num_; }; class QueryAllUGCWorker : public QueryUnknownUGCWorker { public: QueryAllUGCWorker(Nan::Callback *success_callback, Nan::Callback *error_callback, EUGCMatchingUGCType ugc_matching_type, EUGCQuery ugc_query_type, uint32 app_id, uint32 page_num, std::string required_tag); void Execute() override; private: EUGCQuery ugc_query_type_; std::string required_tag_; }; class QueryUserUGCWorker : public QueryUnknownUGCWorker { public: QueryUserUGCWorker(Nan::Callback *success_callback, Nan::Callback *error_callback, EUGCMatchingUGCType ugc_matching_type, EUserUGCList ugc_list, EUserUGCListSortOrder ugc_list_sort_order, uint32 app_id, uint32 page_num, std::string required_tag); void Execute() override; private: EUserUGCList ugc_list_; std::string required_tag_; EUserUGCListSortOrder ugc_list_sort_order_; }; class DownloadItemWorker : public SteamCallbackAsyncWorker { public: DownloadItemWorker(Nan::Callback *success_callback, Nan::Callback *error_callback, PublishedFileId_t published_file_id); void HandleOKCallback() override; void Execute() override; private: PublishedFileId_t published_file_id_; EResult result_; STEAM_CALLBACK(DownloadItemWorker, OnDownloadCompleted, DownloadItemResult_t, m_CallbackDownloadCompleted); }; class DeleteItemWorker : public SteamCallbackAsyncWorker { public: DeleteItemWorker(Nan::Callback *success_callback, Nan::Callback *error_callback, PublishedFileId_t published_file_id); void OnDeleteCompleted(DeleteItemResult_t *result, bool io_failure); void HandleOKCallback() override; void Execute() override; private: PublishedFileId_t published_file_id_; EResult result_; CCallResult<DeleteItemWorker, DeleteItemResult_t> delete_call_result_; }; class SynchronizeItemsWorker : public SteamCallbackAsyncWorker { public: SynchronizeItemsWorker(Nan::Callback *success_callback, Nan::Callback *error_callback, const std::string &download_dir, uint32 app_id, uint32 page_num); void OnUGCQueryCompleted(SteamUGCQueryCompleted_t *result, bool io_failure); void OnDownloadCompleted(RemoteStorageDownloadUGCResult_t *result, bool io_failure); void Execute() override; void HandleOKCallback() override; void HandleErrorCallback() override; private: size_t current_download_items_pos_; std::string download_dir_; std::vector<SteamUGCDetails_t> ugc_items_; std::vector<UGCHandle_t> download_ugc_items_handle_; uint32 app_id_; uint32 page_num_; std::map<PublishedFileId_t, PublishedFileId_t *> child_map_; std::map<PublishedFileId_t, std::string *> key_value_tags_keys_; std::map<PublishedFileId_t, std::string *> key_value_tags_values_; std::map<PublishedFileId_t, uint32> num_tags_; std::map<PublishedFileId_t, std::string *> tags_; std::map<PublishedFileId_t, std::string *> tags_display_names_; std::map<PublishedFileId_t, std::string *> additional_preview_urls_; std::map<PublishedFileId_t, EItemPreviewType *> additional_preview_types_; std::map<PublishedFileId_t, std::string> metadata_; CCallResult<SynchronizeItemsWorker, RemoteStorageDownloadUGCResult_t> download_call_result_; CCallResult<SynchronizeItemsWorker, SteamUGCQueryCompleted_t> ugc_query_call_result_; }; class UnsubscribePublishedFileWorker : public SteamCallbackAsyncWorker { public: UnsubscribePublishedFileWorker(Nan::Callback *success_callback, Nan::Callback *error_callback, PublishedFileId_t unsubscribe_file_id); void OnUnsubscribeCompleted(RemoteStorageUnsubscribePublishedFileResult_t *result, bool io_failure); void HandleOKCallback() override; void Execute() override; private: PublishedFileId_t unsubscribe_file_id_; EResult result_; CCallResult<UnsubscribePublishedFileWorker, RemoteStorageUnsubscribePublishedFileResult_t> call_result_; }; class SubscribePublishedFileWorker : public SteamCallbackAsyncWorker { public: SubscribePublishedFileWorker(Nan::Callback *success_callback, Nan::Callback *error_callback, PublishedFileId_t subscribe_file_id); void OnSubscribeCompleted(RemoteStorageSubscribePublishedFileResult_t *result, bool io_failure); void HandleOKCallback() override; void Execute() override; private: PublishedFileId_t subscribe_file_id_; EResult result_; CCallResult<SubscribePublishedFileWorker, RemoteStorageSubscribePublishedFileResult_t> call_result_; }; } // namespace greenworks #endif // SRC_GREENWORKS_WORKSHOP_WORKERS_H_
<reponame>wschaub/BlinkenBone /* realcons_pdp11_20.c : Logic for the specific 11/20 panel Copyright (c) 2012-2018, <NAME> <EMAIL>, www.retrocmp.com 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 JOERG HOPPE 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. 21-Mar-2018 JH Reset (HALT+START) load PC, merged with current SimH 23-Apr-2016 JH cloned from 11/70 Inputs: - cpu state (PDP11 as set by SimH) - blinkenlight API panel input (switches) Outputs: - cpu state (as checked by SimH, example: HALT state) - blinkenlight API panel outputs (lamps) - SimH command string Class hierarchy: base panel = generic machine with properties requiered by SimH everthing accessed in scp.c is "base" inherited pdp11_20 (or other architecure) an actual Panel has an actual machine state. (For instance, a 11/05 has almost the same machine state, but quite a different panel) */ #ifdef USE_REALCONS #include <assert.h> #include "sim_defs.h" #include "realcons.h" #include "realcons_console_pdp11_20.h" // indexes of used general timers #define TIMER_TEST 0 #define TIMER_DATA_FLASH 1 #define TIME_TEST_MS 3000 // self test terminates after 3 seconds #define TIME_DATA_FLASH_MS 0 // do DAT l3ds flash on 11/20? // the LEDs behaves a bit difficult, so distinguish these states: #define RUN_STATE_HALT 0 #define RUN_STATE_RESET 1 #define RUN_STATE_WAIT 2 #define RUN_STATE_RUN 3 /* * SimH gives not the CPU registers, if their IO page addresses are exam/deposit * So convert addr -> reg, and revers in the *_operator_reg_exam_deposit() */ static t_addr realcons_console_pdp11_20_addr_inc(t_addr addr) { // no 1-byte inc for register space? // if (addr >= 0777700 && addr <= 0777707) // addr += 1; // inc to next register // else addr += 2; // inc by word addr &= 017777777; // trunc to 22 bit return addr; } // generate SimH expression for panel address // - result string to be used in "sim>" exam or deposit cmd // - translate memory addr to register, if CPU is accessed // translate 2218bit 11/20 IOpage addr to 22bit SimH address static char *realcons_console_pdp11_20_addr_panel2simh(t_addr panel_addr) { static char buff[40]; // physical 18 bit address switch (panel_addr) { case 017777700: return "r0"; case 017777701: return "r1"; case 017777702: return "r2"; case 017777703: return "r3"; case 017777704: return "r4"; case 017777705: return "r5"; case 017777706: return "sp"; case 017777707: return "pc"; default: panel_addr &= ~1; // clear LSB, according to DEC doc sprintf(buff, "%o", panel_addr); return buff; } } /* PDP-11/20 is 16 bit, SimH is 22 bit Internal the console address uses a 18 bit register. "The processor ignores bits 17 and 16; these switches may be set to either position. For addresses using bits 17 and 16, these bits are set within the processor if bits 15, 14, and 13 are set." expand a 16 bit address to 22 bit: bits 21:16 = 11, if bits 15,14,13 =111 (IOpage) */ static t_addr encode_SR_addr_16_to_22(t_addr sr_addr) { sr_addr &= 0177777; // trunc to 16 if ((sr_addr & 0160000) == 0160000) // IO page return 017600000 | sr_addr; // 18 bit io page addr else return sr_addr; } // if a 22 bit SimH addr is to be displayed on the 18 bit address LEDs static t_addr encode_SimH_addr_22_to_18(t_addr addr) { return addr & 0777777; } /* make a 16 bit value from the 18 bit SR switches " The processor ignores bits 17 and 16; these switches may be set to either position." */ static t_value encode_SR_18_to_16(t_value sr_val) { return sr_val & 0177777; // trunc to 16 } /* * constructor / destructor */ realcons_console_logic_pdp11_20_t *realcons_console_pdp11_20_constructor(realcons_t *realcons) { realcons_console_logic_pdp11_20_t *_this; _this = (realcons_console_logic_pdp11_20_t *) malloc(sizeof(realcons_console_logic_pdp11_20_t)); _this->realcons = realcons; // connect to parent _this->run_state = 0; return _this; } void realcons_console_pdp11_20_destructor(realcons_console_logic_pdp11_20_t *_this) { free(_this); } /* * Interface to external simulation: * signaled by SimH for state changes of CPU * Here used to set DMUX, which is used to drive DATA leds * * CPU conditions: * HALT instruction has R(00) * RESET instruction has R(00) * WAIT instruction has R(IR) * SINGLE STEP and HALT switch has Processor Status (PS) * * Console switches: * LOAD ADRS - the transferred Switch register address. * DEP - the Switch register data just deposited. * EXAM - the information from the address examined. * HALT - displays the current Processor Status (PS) word. * * Called high speed in simulator loop! * return 0, if not accepted */ // SHORTER macros for signal access // assume "realcons_console_logic_pdp11_20_t *_this" in context #define SIGNAL_SET(signal,value) REALCONS_SIGNAL_SET(_this,signal,value) #define SIGNAL_GET(signal) REALCONS_SIGNAL_GET(_this,signal) void realcons_console_pdp11_20_event_connect(realcons_console_logic_pdp11_20_t *_this) { // set panel mode to "powerless". all lights go off, // On Java panels the power switch should flip to the ON position realcons_power_mode(_this->realcons, 1); } void realcons_console_pdp11_20_event_disconnect(realcons_console_logic_pdp11_20_t *_this) { // set panel mode to "powerless". all lights go off, // On Java panels the power switch should flip to the OFF position realcons_power_mode(_this->realcons, 0); } void realcons_console_pdp11_20__event_opcode_any(realcons_console_logic_pdp11_20_t *_this) { // other opcodes executed by processor if (_this->realcons->debug) printf("realcons_console_pdp11_20__event_opcode_any\n"); // SIGNAL_SET(cpu_is_running, 1); // after any opcode: ADDR shows PC, DATA shows IR = opcode SIGNAL_SET(cpusignal_memory_address_phys_register, SIGNAL_GET(cpusignal_PC)); _this->DATA_reg = SIGNAL_GET(cpusignal_DATAPATH_shifter); // show internal data // opcode fetch: ALU_output already set SIGNAL_SET(cpusignal_memory_data_register, SIGNAL_GET(cpusignal_instruction_register)); // SIGNAL_SET(cpusignal_bus_register, SIGNAL_GET(cpusignal_instruction_register)); _this->run_state = RUN_STATE_RUN; } void realcons_console_pdp11_20__event_opcode_halt(realcons_console_logic_pdp11_20_t *_this) { if (_this->realcons->debug) printf("realcons_console_pdp11_20__event_opcode_halt\n"); // SIGNAL_SET(cpusignal_console_halt, 1); SIGNAL_SET(cpusignal_memory_address_phys_register, SIGNAL_GET(cpusignal_PC)-2); // what is in the unibus interface on HALT? IR == HALT Opcode? // SIGNAL_SET(cpusignal_busregister, ...) _this->DATA_reg = SIGNAL_GET(cpusignal_R0); // show R0 on halt _this->run_state = RUN_STATE_HALT; // show signal R0 } void realcons_console_pdp11_20__event_opcode_reset(realcons_console_logic_pdp11_20_t *_this) { if (_this->realcons->debug) printf("realcons_console_pdp11_20__event_opcode_reset\n"); // SIGNAL_SET(cpusignal_console_halt, 0); SIGNAL_SET(cpusignal_memory_address_phys_register, SIGNAL_GET(cpusignal_PC)); // what is in the unibus interface on RESET? IR == RESET Opcode ? // SIGNAL_SET(cpusignal_busregister, ...) // _this->DMUX = SIGNAL_GET(cpusignal_R0); _this->run_state = RUN_STATE_RESET; // duration of RESET on 11/20 unclear. do 70ms, as on 11/40 realcons_ms_sleep(_this->realcons, 70); // keep realcons logic active } void realcons_console_pdp11_20__event_opcode_wait(realcons_console_logic_pdp11_20_t *_this) { if (_this->realcons->debug) printf("realcons_console_pdp11_20__event_opcode_wait\n"); // SIGNAL_SET(cpusignal_console_halt, 0); SIGNAL_SET(cpusignal_memory_address_phys_register, SIGNAL_GET(cpusignal_PC)); SIGNAL_SET(cpusignal_memory_data_register, SIGNAL_GET(cpusignal_instruction_register)); //SIGNAL_SET(cpusignal_bus_register, SIGNAL_GET(cpusignal_instruction_register)); _this->run_state = RUN_STATE_WAIT; // RUN led off } void realcons_console_pdp11_20__event_run_start(realcons_console_logic_pdp11_20_t *_this) { if (_this->realcons->debug) printf("realcons_console_pdp11_20__event_run_start\n"); if (_this->switch_HALT->value) return; // do not accept RUN command // set property RUNMODE, so SimH can read it back // SIGNAL_SET(cpusignal_console_halt, 0); // running _this->run_state = RUN_STATE_RUN; } void realcons_console_pdp11_20__event_step_start(realcons_console_logic_pdp11_20_t *_this) { if (_this->realcons->debug) printf("realcons_console_pdp11_20__event_step_start\n"); // SIGNAL_SET(cpusignal_console_halt, 0); // running } void realcons_console_pdp11_20__event_operator_halt(realcons_console_logic_pdp11_20_t *_this) { if (_this->realcons->debug) printf("realcons_console_pdp11_20__event_operator_halt\n"); SIGNAL_SET(cpusignal_memory_address_phys_register, SIGNAL_GET(cpusignal_PC) - 2); // SIGNAL_SET(cpusignal_console_halt, 1); // SIGNAL_SET(cpusignal_memory_address_register, SIGNAL_GET(cpusignal_PC)); // SIGNAL_SET(cpusignal_DATAPATH_shifter, SIGNAL_GET(cpusignal_PSW)); _this->run_state = RUN_STATE_HALT; } void realcons_console_pdp11_20__event_step_halt(realcons_console_logic_pdp11_20_t *_this) { if (_this->realcons->debug) printf("realcons_console_pdp11_20__event_step_halt\n"); // SIGNAL_SET(cpusignal_console_halt, 1); SIGNAL_SET(cpusignal_memory_address_phys_register, SIGNAL_GET(cpusignal_PC)-2); // SIGNAL_SET(cpusignal_DATAPATH_shifter, SIGNAL_GET(cpusignal_PSW)); _this->run_state = RUN_STATE_HALT; } // this is called, when "exam" or "deposit" is entered over the // sim> command prompt by user or as result of an EXAM or DEPOSIT panel switch. // if ADDR SELECT knob is VIRUAL, the virtual address for the // SimH physical address should be displayed. // This is impossible: not every physical addr has a virtual representation // for given address space (KERNEL,SUPER,USER, I/D) // So simpy DO NOT UPDATE panel regsiter if KNBOB is virtual, // then at least the key switch values remain in ADRR LEDs void realcons_console_pdp11_20__event_operator_exam_deposit( realcons_console_logic_pdp11_20_t *_this) { if (_this->realcons->debug) printf("realcons_console_pdp11_20__event_operator_exam\n"); _this->DATA_reg = SIGNAL_GET(cpusignal_memory_data_register); } // Called if Realcons or a user typed "examine <regname>" or "deposit <regname> value". // Realcons accesses only the CPU registers by name, so only these are recognized here // see realcons_console_pdp11_20_addr_panel2simh() ! void realcons_console_pdp11_20__event_operator_reg_exam_deposit( realcons_console_logic_pdp11_20_t *_this) { char *regname = SIGNAL_GET(cpusignal_register_name); // alias t_addr addr = 0; if (_this->realcons->debug) printf("realcons_console_pdp11_20__event_operator_reg_exam_deposit\n"); // exam on SimH console sets also console address (like LOAD ADDR) // convert register into UNIBUS address if (!strcasecmp(regname, "r0")) addr = 017777700; else if (!strcasecmp(regname, "r1")) addr = 017777701; else if (!strcasecmp(regname, "r2")) addr = 017777702; else if (!strcasecmp(regname, "r3")) addr = 017777703; else if (!strcasecmp(regname, "r4")) addr = 017777704; else if (!strcasecmp(regname, "r5")) addr = 017777705; else if (!strcasecmp(regname, "sp")) addr = 017777706; else if (!strcasecmp(regname, "pc")) addr = 017777707; if (addr) { SIGNAL_SET(cpusignal_memory_address_phys_register, addr); realcons_console_pdp11_20__event_operator_exam_deposit(_this); } // other register accesses are ignored by the panel } // Called after CPU has been reinitialized void realcons_console_pdp11_20__event_cpu_reset( realcons_console_logic_pdp11_20_t *_this) { if (_this->realcons->debug) printf("realcons_console_pdp11_20__event_cpu_reset\n"); // TODO: load PC with result from LOAD ADDR, for "HALT+START" reset ? // This does NOT work: // SIGNAL_SET(cpusignal_PC, SIGNAL_GET(cpusignal_memory_address_phys_register)) ; } void realcons_console_pdp11_20_interface_connect(realcons_console_logic_pdp11_20_t *_this, realcons_console_controller_interface_t *intf, char *panel_name) { intf->name = panel_name; intf->constructor_func = (console_controller_constructor_func_t) realcons_console_pdp11_20_constructor; intf->destructor_func = (console_controller_destructor_func_t) realcons_console_pdp11_20_destructor; intf->reset_func = (console_controller_reset_func_t) realcons_console_pdp11_20_reset; intf->service_func = (console_controller_service_func_t) realcons_console_pdp11_20_service; intf->test_func = (console_controller_test_func_t) realcons_console_pdp11_20_test; intf->event_connect = (console_controller_event_func_t) realcons_console_pdp11_20_event_connect; intf->event_disconnect = (console_controller_event_func_t) realcons_console_pdp11_20_event_disconnect; // connect pdp11 cpu signals end events to simulator and realcons state variables { // REALCONS extension in scp.c extern t_addr realcons_memory_address_phys_register; // REALCONS extension in scp.c extern t_value realcons_memory_data_register; // REALCONS extension in scp.c extern char *realcons_register_name; // pseudo: name of last accessed register extern int realcons_console_halt; // 1: CPU halted by realcons console extern volatile t_bool sim_is_running; // global in scp.c extern int32 R[8]; // working registers, global in pdp11_cpu.c extern int32 saved_PC; extern int32 SR; // switch register, global in pdp11_cpu_mod.c //extern t_addr realcons_console_address_register; // set by LOAD ADDR extern t_value realcons_DATAPATH_shifter; // output of ALU extern t_value realcons_IR; // buffer for instruction register (opcode) extern t_value realcons_PSW; // buffer for program status word realcons_console_halt = 0; // from scp.c _this->cpusignal_memory_address_phys_register = &realcons_memory_address_phys_register; _this->cpusignal_register_name = &realcons_register_name; // pseudo: name of last accessed register _this->cpusignal_memory_data_register = &realcons_memory_data_register; // BAR _this->cpusignal_console_halt = &realcons_console_halt; // from pdp11_cpu.c // is "sim_is_running" indeed identical with our "cpu_is_running" ? // may cpu stops, but some device are still serviced? _this->cpusignal_run = &(sim_is_running); _this->cpusignal_DATAPATH_shifter = &realcons_DATAPATH_shifter; // not used //_this->cpusignal_console_address_register = &realcons_console_address_register; // not used // set by LOAD ADDR, on all PDP11's // signal from realcons console to CPU: 1=HALTed // oder gleich "&(_switch_HALT->value)?" _this->cpusignal_instruction_register = &realcons_IR; _this->cpusignal_PSW = &realcons_PSW; _this->cpusignal_R0 = &(R[0]); // R: global of pdp11_cpu.c _this->cpusignal_PC = &saved_PC; // R[7] not valid in console mode _this->cpusignal_switch_register = &SR; // see pdp11_cpumod.SR_rd() } /*** link handler to cpu/device events ***/ { // scp.c extern console_controller_event_func_t realcons_event_run_start; extern console_controller_event_func_t realcons_event_operator_halt; extern console_controller_event_func_t realcons_event_step_start; extern console_controller_event_func_t realcons_event_step_halt; extern console_controller_event_func_t realcons_event_operator_exam; extern console_controller_event_func_t realcons_event_operator_deposit; extern console_controller_event_func_t realcons_event_operator_reg_exam; extern console_controller_event_func_t realcons_event_operator_reg_deposit; extern console_controller_event_func_t realcons_event_cpu_reset; // pdp11_cpu.c extern console_controller_event_func_t realcons_event_opcode_any; // triggered after any opcode execution extern console_controller_event_func_t realcons_event_opcode_halt; extern console_controller_event_func_t realcons_event_opcode_reset; // triggered after execution of RESET extern console_controller_event_func_t realcons_event_opcode_wait; // triggered after execution of WAIT realcons_event_run_start = (console_controller_event_func_t) realcons_console_pdp11_20__event_run_start; realcons_event_step_start = (console_controller_event_func_t) realcons_console_pdp11_20__event_step_start; realcons_event_operator_halt = (console_controller_event_func_t) realcons_console_pdp11_20__event_operator_halt; realcons_event_step_halt = (console_controller_event_func_t) realcons_console_pdp11_20__event_step_halt; realcons_event_operator_exam = realcons_event_operator_deposit = (console_controller_event_func_t) realcons_console_pdp11_20__event_operator_exam_deposit; realcons_event_operator_reg_exam = realcons_event_operator_reg_deposit = (console_controller_event_func_t) realcons_console_pdp11_20__event_operator_reg_exam_deposit; realcons_event_cpu_reset = (console_controller_event_func_t) realcons_console_pdp11_20__event_cpu_reset ; realcons_event_opcode_any = (console_controller_event_func_t) realcons_console_pdp11_20__event_opcode_any; realcons_event_opcode_halt = (console_controller_event_func_t) realcons_console_pdp11_20__event_opcode_halt; realcons_event_opcode_reset = (console_controller_event_func_t) realcons_console_pdp11_20__event_opcode_reset; realcons_event_opcode_wait = (console_controller_event_func_t) realcons_console_pdp11_20__event_opcode_wait; } } // setup first state t_stat realcons_console_pdp11_20_reset(realcons_console_logic_pdp11_20_t *_this) { _this->realcons->simh_cmd_buffer[0] = '\0'; //SIGNAL_SET(cpusignal_console_address_register, 0); SIGNAL_SET(cpusignal_DATAPATH_shifter, 0); // else DATA trash is shown before first EXAM _this->autoinc_addr_action_switch = NULL; // not active _this->DATA_reg = 0 ; /* * direct links to all required controls. * Also check of config file */ if (!(_this->keyswitch_POWER = realcons_console_get_input_control(_this->realcons, "POWER"))) return SCPE_NOATT; if (!(_this->keyswitch_PANEL_LOCK = realcons_console_get_input_control(_this->realcons, "PANEL_LOCK"))) return SCPE_NOATT; if (!(_this->switch_SR = realcons_console_get_input_control(_this->realcons, "SR"))) return SCPE_NOATT; if (!(_this->switch_LOAD_ADDR = realcons_console_get_input_control(_this->realcons, "LOAD_ADDR"))) return SCPE_NOATT; if (!(_this->switch_EXAM = realcons_console_get_input_control(_this->realcons, "EXAM"))) return SCPE_NOATT; if (!(_this->switch_CONT = realcons_console_get_input_control(_this->realcons, "CONT"))) return SCPE_NOATT; if (!(_this->switch_HALT = realcons_console_get_input_control(_this->realcons, "HALT"))) return SCPE_NOATT; if (!(_this->switch_SINST_SCYCLE = realcons_console_get_input_control(_this->realcons, "SCYCLE"))) return SCPE_NOATT; if (!(_this->switch_START = realcons_console_get_input_control(_this->realcons, "START"))) return SCPE_NOATT; if (!(_this->switch_DEPOSIT = realcons_console_get_input_control(_this->realcons, "DEPOSIT"))) return SCPE_NOATT; if (!(_this->leds_ADDRESS = realcons_console_get_output_control(_this->realcons, "ADDRESS"))) return SCPE_NOATT; if (!(_this->leds_DATA = realcons_console_get_output_control(_this->realcons, "DATA"))) return SCPE_NOATT; if (!(_this->led_RUN = realcons_console_get_output_control(_this->realcons, "RUN"))) return SCPE_NOATT; if (!(_this->led_BUS = realcons_console_get_output_control(_this->realcons, "BUS"))) return SCPE_NOATT; if (!(_this->led_FETCH = realcons_console_get_output_control(_this->realcons, "FETCH"))) return SCPE_NOATT; if (!(_this->led_EXEC = realcons_console_get_output_control(_this->realcons, "EXEC"))) return SCPE_NOATT; if (!(_this->led_SOURCE = realcons_console_get_output_control(_this->realcons, "SOURCE"))) return SCPE_NOATT; if (!(_this->led_DESTINATION = realcons_console_get_output_control(_this->realcons, "DESTINATION"))) return SCPE_NOATT; if (!(_this->leds_ADDRESS_CYCLE = realcons_console_get_output_control(_this->realcons, "ADDRESS_CYCLE"))) return SCPE_NOATT; return SCPE_OK; } // process panel state. // operates on Blinkenlight_API panel structs, // but RPC communication is done external t_stat realcons_console_pdp11_20_service(realcons_console_logic_pdp11_20_t *_this) { blinkenlight_panel_t *p = _this->realcons->console_model; // alias int panel_lock; int console_mode; blinkenlight_control_t *action_switch; // current action switch if (_this->keyswitch_POWER->value == 0 ) { SIGNAL_SET(cpusignal_console_halt, 1); // stop execution if (_this->keyswitch_POWER->value_previous == 1) { // Power switch transition to POWER OFF: terminate SimH // This is drastic, but will teach users not to twiddle with the power switch. // when panel is disconnected, panel mode goes to POWERLESS and power switch goes OFF. // But shutdown sequence is not initiated, because we're disconnected then. sprintf(_this->realcons->simh_cmd_buffer, "quit"); // do not confirm the quit with ENTER } // do nothing, if power is off. else cpusignal_console_halt may be deactivate by HALT switch return SCPE_OK; } /* LOCK - Same as POWER, except that the LOAD ADRS, EXAM, DEP, CONT, ENABLE/HALT, S INST/S BUS CYCLE and START switches are disabled. All other switches are operational. */ panel_lock = (_this->keyswitch_PANEL_LOCK->value != 0) ; /* test time expired? */ // STOP by activating HALT? if (!panel_lock && _this->switch_HALT->value && !SIGNAL_GET(cpusignal_console_halt)) { // must be done by SimH.pdp11_cpu.c! } // CONSOLE: processor accepts commands from console panel when HALTed console_mode = !SIGNAL_GET(cpusignal_run) || SIGNAL_GET(cpusignal_console_halt); /************************************************************* * eval switches * react on changed action switches */ // fetch switch register SIGNAL_SET(cpusignal_switch_register, encode_SR_18_to_16((t_value)_this->switch_SR->value)); // fetch HALT mode, must be sensed by simulated processor to produce state OPERATOR_HALT if (panel_lock) SIGNAL_SET(cpusignal_console_halt,0) ; else SIGNAL_SET(cpusignal_console_halt, (t_value )_this->switch_HALT->value); /* which command switch was activated? Process only one of these * "command switch" is NO term of 11/20 docs, but excluding logic seems useful */ action_switch = NULL; if (!panel_lock) { if (!action_switch && _this->switch_LOAD_ADDR->value == 1 && _this->switch_LOAD_ADDR->value_previous == 0) action_switch = _this->switch_LOAD_ADDR; if (!action_switch && _this->switch_EXAM->value == 1 && _this->switch_EXAM->value_previous == 0) action_switch = _this->switch_EXAM; if (!action_switch && _this->switch_DEPOSIT->value == 1 && _this->switch_DEPOSIT->value_previous == 0) action_switch = _this->switch_DEPOSIT; if (!action_switch && _this->switch_CONT->value == 1 && _this->switch_CONT->value_previous == 0) action_switch = _this->switch_CONT; if (!action_switch && // START actions on rising and falling edge! _this->switch_START->value ^ _this->switch_START->value_previous) action_switch = _this->switch_START; } // first: reset "switch changed" condition if (action_switch) action_switch->value_previous = action_switch->value; /* * ATTENTION: * Switch actions may NOT manipulate the console state directly! * They ONLY may generated SimH commands, * which in turn lets SimH signal a changed machine state * which is evaluated for display of panel indicators */ // accept input only in CONSOLE mode. Exception: HALT is always enabled, see above if (!console_mode) action_switch = NULL; if (action_switch) { /* auto addr inc logic */ if (action_switch != _this->autoinc_addr_action_switch) // change of switch: DEP or EXAM sequence broken _this->autoinc_addr_action_switch = NULL; else // inc panel address register SIGNAL_SET(cpusignal_memory_address_phys_register, realcons_console_pdp11_20_addr_inc(SIGNAL_GET(cpusignal_memory_address_phys_register))); // BAR /* "The LOAD ADDR switch transfers the SWITCH REGISTER contents to the Bus Address Register (BAR) through a temporary location (TEMP) within the processor. This bus address, displayed in the ADDRESS REGISTER, provides an address for the console functions of EXAM, DEP, and START."*/ if (action_switch == _this->switch_LOAD_ADDR) { SIGNAL_SET(cpusignal_memory_address_phys_register, // BAR (realcons_machine_word_t ) encode_SR_addr_16_to_22(encode_SR_18_to_16((t_value)_this->switch_SR->value))); SIGNAL_SET(cpusignal_DATAPATH_shifter, 0); // 11/40 videos show: DATA is cleared if (_this->realcons->debug) printf("LOADADR %o\n", SIGNAL_GET(cpusignal_memory_address_phys_register)); // flash with DATA LEDs on 11/40. 11/70 ? _this->realcons->timer_running_msec[TIMER_DATA_FLASH] = _this->realcons->service_cur_time_msec + TIME_DATA_FLASH_MS; } if (action_switch == _this->switch_EXAM) { // t_addr pa; // physical address _this->autoinc_addr_action_switch = _this->switch_EXAM; // inc addr on next EXAM // generate simh "exam cmd" // fix octal, should use SimH-radix sprintf(_this->realcons->simh_cmd_buffer, "examine %s\n", realcons_console_pdp11_20_addr_panel2simh(SIGNAL_GET(cpusignal_memory_address_phys_register))); } if (action_switch == _this->switch_DEPOSIT) { // t_addr pa; // physical address unsigned dataval; dataval = (realcons_machine_word_t)encode_SR_18_to_16((t_value)_this->switch_SR->value); // trunc to switches 15..0 _this->autoinc_addr_action_switch = _this->switch_DEPOSIT; // inc addr on next DEP // produce SimH cmd. fix octal, should use SimH-radix sprintf(_this->realcons->simh_cmd_buffer, "deposit %s %o\n", realcons_console_pdp11_20_addr_panel2simh( SIGNAL_GET(cpusignal_memory_address_phys_register)), dataval); // flash with DATA LEDs _this->realcons->timer_running_msec[TIMER_DATA_FLASH] = _this->realcons->service_cur_time_msec + TIME_DATA_FLASH_MS; } /* function of CONT, START mixed with HALT: * Switch HALT SimH Function * ------ ---- ---- --------- * START ON reset INITIALIZE * START OFF run <r_adrsc> INITIALIZE, and start processor operation at R_ADRSC * CONT ON step 1 execute next single step * CONT OFF cont continue execution at PC * * The 11/20 has no BOOT switch. */ /*"When ENABLE/HALT is set to ENABLE, depressing START provides a system dear operation and then begins processor operation. A LOAD ADDR operation pre-establishes the starting address. When ENABLE/HALT is set to HALT, depressing START provides a system clear (initialize) only. The processor does not start; the Bus Address Register is loaded from a temporary processor register (TEMP) which is usually pre-loaded by LOAD ADDR. This provides the only method of reading TEMP when it does not contain the LOAD ADDR value." */ if (action_switch == _this->switch_START) { // START has actions on rising AND falling edge! if (_this->switch_START->value && _this->switch_HALT->value) { // rising edge and HALT: INITIALIZE = SimH "RESET" sprintf(_this->realcons->simh_cmd_buffer, "reset all\n"); } if (_this->switch_START->value && !_this->switch_HALT->value) { // rising edge and not HALT: will start on falling edge // but CONSOLE LED goes of now! Too difficult .... // console_led_prestart_off = 1; } if (!_this->switch_START->value && !_this->switch_HALT->value) { // falling edge and not HALT: start // INITIALIZE, and start processor operation at R_ADRSC // not documented, but start at virtual addr must be also be converted to physical sprintf(_this->realcons->simh_cmd_buffer, "run %o\n", SIGNAL_GET(cpusignal_memory_address_phys_register) // always 22 bit physical ? ); // flash with DATA LEDs _this->realcons->timer_running_msec[TIMER_DATA_FLASH] = _this->realcons->service_cur_time_msec + TIME_DATA_FLASH_MS; } } else if (action_switch == _this->switch_CONT && _this->switch_HALT->value) { // single step = SimH "STEP 1" sprintf(_this->realcons->simh_cmd_buffer, "step 1\n"); } else if (action_switch == _this->switch_CONT && !_this->switch_HALT->value) { // continue = SimH "CONT" sprintf(_this->realcons->simh_cmd_buffer, "cont\n"); } } // action_switch /*************************************************** * update lights */ // while test not expired: do lamp test if (!_this->realcons->lamp_test && _this->realcons->timer_running_msec[TIMER_TEST]) realcons_lamp_test(_this->realcons, 1); // begin lamptest if (_this->realcons->lamp_test && !_this->realcons->timer_running_msec[TIMER_TEST]) realcons_lamp_test(_this->realcons, 0); // end lamptest if (_this->realcons->lamp_test) return SCPE_OK; // no lights need to be set // if (_this->realcons->debug) // printf("led_ADDRESS=%o, ledDATA=%o\n", (unsigned) _this->led_ADDRESS->value, // (unsigned) _this->led_DATA->value); /*"ADDRESS REGISTER: Displays the address in the bus address register (BAR) of the processor. This is the address last used by the processor on the bus. The BAR is 18 bits, allowing for future expansion. At present, the two most significant bits (A17, A16) are ordered according to the lower 16 bits; they are set only when bits A15, A14, and A13 are set. Addresses between 160000 and 177777, therefore, are translated to addresses between 760000 and 777777, respectively. When console switches are used, information shown on the ADDRESS REGISTER display is as follows: LOAD ADDR - the transferred SWITCH REGISTER information DEP or EXAM — indicates the bus address just deposited into or examined. S-INST or S-CYCLE — indicates the last processor bus address. During a programmed HALT or WAIT instruction, the ADDRESS REGISTER displays the address of the instruction. The program counter (PC) is the BAR value plus 2. During direct memory access (DMA) operations, the processor is not involved in the data transfer functions, and the address displayed in the ADDRESS REGISTER is not that of the last bus operation. "*/ _this->leds_ADDRESS->value = SIGNAL_GET(cpusignal_memory_address_phys_register); // all logic must influence cpusignal_memory_address_register ! // cpusignal_memory_address_register is updated by simulator /* "DATA: When console switches are used, information shown on the DATA display is as follows: LOAD ADDR - no indication DEP - the SWITCH REGISTER information just deposited. Note that the data and address correlated. The address is where this data was stored. EXAM - the information from the address examined - note address and data correlation. S-INST - when stepping through a program a single instruction at a time, there is no indication on the DATA display. S-CYCLE - the information last in the data paths (refer to flow diagram). Usually is a derivative of last bus data. During HALT and WAIT instructions, information shown on DATA display is as follows: WAIT - The RUN light is on, no indication on DATA display. HALT - when bus control is transferred to the console on a HALT instruction, processor register RO is displayed. This allows program identification of halts. During direct memory access (EMA) operations, the processor is not involved in data transfer functions. Therefore, the data displayed in the DATA display is not that of the last bus operation." */ if (_this->realcons->timer_running_msec[TIMER_DATA_FLASH]) // all LEDs pulse ON after DEPOSIT, LOADADR etc _this->leds_DATA->value = 0xfffff; else _this->leds_DATA->value = _this->DATA_reg; // RUN: /*"When the RUN indicator is on, the processor dock is running. The processor has control of the bus and is operating on an instruction. When the RUN indicator is off, the processor is waiting for an asynchronous peripheral data response; or the processor has given up bus control to the console or to a peripheral. During normal machine operation the RUN light will flicker on and off (indicated by a faint glow). Special situations exist for programmed HALT and WAIT instructions: WAIT — the RUN light is completely on HALT — the RUN light is off During machine operation, with S-INST or S-CYCLE control transferred to the console, the RUN light is not on." */ // bright on HALT, off after RESET, "faint glow" in normal machine operation, if (SIGNAL_GET(cpusignal_run)) { if (_this->run_state == RUN_STATE_RESET || _this->run_state == RUN_STATE_HALT ) _this->led_RUN->value = 0; // RESET undefined by docs else if (_this->run_state == RUN_STATE_WAIT) _this->led_RUN->value = 1; else // Running: ON 1/4 of the time => flickering and "faint glow": 50% _this->led_RUN->value = !(_this->realcons->service_cycle_count % 2); } else // not running. _this->led_RUN->value = 0; /*" When the BUS indicator is on, a peripheral device (other than the console) is controlling the bus. When both the BUS and RUN indicators are off, the bus control has been transferred to the console. The bus light probably is never seen except when there is a bus malfunction or when a peripheral holds the bus for excessive periods of time. Refer to Paragraph 3.3 for further discussion of BUS and RUN indicator combinations. During machine operation with S-INST or S-CYCLE, control is transferred to the console and the BUS indicator is not on. FETCH: "When on, the processor is in the FETCH major state and is obtaining an instruction. During the Fetch major state, only FETCH and RUN indicators are on if no NPRs are honored." EXEC: When on the processor is in the EXECUTE major state. The processor performs the action specified by the instruction. (HALT, WAIT, and trap instructions are executed in Service.) During the Execute major state, only EXEC and RUN indicators are on if no NPRs are honored. SOURCE: When on, the processor is in the Source major state and is obtaining source operand data. The processor calculates source address data as indicated by cycles of the ADDRESS lights. During the Source major state, SOURCE and RUN indicators are both on; ADDRESS lights may be on in various combinations. The BUS indicator is off if no NPRs are honored. DESTINATION: When on, the processor is in the Destination major state and is obtaining destination operand data. The processor calculates destination address data as indicated by cycles of the ADDRESS lights. During the Destination major state, DESTINATION and RUN indicators are both on; ADDRESS lights may be on in various combinations. The BUS indicator is off if no NPRs are honored. ADDRESS: When lit, indicate bus cycles used to obtain address data during Source and Destination major states. The 2-bit binary code indicates which address cycle (1, 2, or 3) the machine is in during the Source or Destination major state. Whenever either one or both ADDRESS lights are lit, either the SOURCE or DESTINATION indicator is on. The BUS indicator is off if no NPRs are honored. "*/ // if CPU is running, simulate some plausible light patterns (SimH does not simulate single cycles) // FETCH 50%, EXEC 33%, SOURCE 25%, DESTINATION 15%, ADDRESS: 20% 1 access, 5% 2 accesses, 0 % 3 accesses _this->led_BUS = 0; // well ... if (SIGNAL_GET(cpusignal_run) && _this->run_state == RUN_STATE_RUN) { int n; _this->led_FETCH->value = !(_this->realcons->service_cycle_count % 2); _this->led_EXEC->value = !(_this->realcons->service_cycle_count % 3); _this->led_SOURCE->value = !(_this->realcons->service_cycle_count % 4); _this->led_DESTINATION->value = !(_this->realcons->service_cycle_count % 6); n = 0; if (!(_this->realcons->service_cycle_count % 5)) n = 1; else if (!(_this->realcons->service_cycle_count % 20)) n = 2; _this->leds_ADDRESS_CYCLE->value = n ; } else _this->led_FETCH->value = _this->led_EXEC->value = _this->led_SOURCE->value = _this->led_DESTINATION->value = _this->leds_ADDRESS_CYCLE->value = 0; return SCPE_OK; } /* * start 1 sec test sequence. * - lamps ON for 1 sec: TIME_TEST_MS * - print state of all switches */ int realcons_console_pdp11_20_test(realcons_console_logic_pdp11_20_t *_this, int arg) { // send end time for test: 1 second = curtime + 1000 // lamp test is set in service() _this->realcons->timer_running_msec[TIMER_TEST] = _this->realcons->service_cur_time_msec + TIME_TEST_MS; realcons_printf(_this->realcons, stdout, "Verify lamp test!\n"); realcons_printf(_this->realcons, stdout, "Switch SR = %llo\n", _this->switch_SR->value); realcons_printf(_this->realcons, stdout, "Switch LOAD ADDR = %llo\n", _this->switch_LOAD_ADDR->value); realcons_printf(_this->realcons, stdout, "Switch EXAM = %llo\n", _this->switch_EXAM->value); realcons_printf(_this->realcons, stdout, "Switch CONT = %llo\n", _this->switch_CONT->value); realcons_printf(_this->realcons, stdout, "Switch ENABLE/HALT = %llo\n", _this->switch_HALT->value); realcons_printf(_this->realcons, stdout, "Switch S-INST/S-CYCLE = %llo\n", _this->switch_SINST_SCYCLE->value); realcons_printf(_this->realcons, stdout, "Switch START = %llo\n", _this->switch_START->value); realcons_printf(_this->realcons, stdout, "Switch DEPOSIT = %llo\n", _this->switch_DEPOSIT->value); return 0; // OK } #endif // USE_REALCONS
<reponame>egasimus/blind /* See LICENSE file for copyright and license details. */ #include "common.h" USAGE("[-r]") static size_t fm; static double fm_double; static float fm_float; static int reverse = 0; #define PROCESS(TYPE)\ do {\ size_t i = (size_t)(stream->alpha_chan) * stream->chan_size;\ TYPE a = fm ? (TYPE)(reverse ? f : fm - f) / fm_##TYPE : (TYPE)0.5;\ for (; i < n; i += stream->pixel_size)\ *(TYPE *)(stream->buf + i) *= a;\ } while (0) static void process_lf(struct stream *stream, size_t n, size_t f) {PROCESS(double);} static void process_f (struct stream *stream, size_t n, size_t f) {PROCESS(float);} int main(int argc, char *argv[]) { struct stream stream; void (*process)(struct stream *stream, size_t n, size_t f); ARGBEGIN { case 'r': reverse = 1; break; default: usage(); } ARGEND; if (argc) usage(); eopen_stream(&stream, NULL); SELECT_PROCESS_FUNCTION(&stream); CHECK_CHANS(&stream, != -1, == stream.luma_chan); if (!stream.frames) eprintf("video's length is not recorded"); fprint_stream_head(stdout, &stream); efflush(stdout, "<stdout>"); fm_double = (double)(fm = stream.frames - 1); fm_float = (float)fm_double; process_each_frame_segmented(&stream, STDOUT_FILENO, "<stdout>", process); return 0; }
#ifndef __WIN32_HELPER__ #define __WIN32_HELPER__ #ifdef __cplusplus extern "C" { #endif #include <Windows.h> // 检查表达式是否为真 #define CHECK(call) ;\ if (!(call)) {\ SetLastError(-1);\ Perror(#call);\ }\ ; // 检查Win32系统调用 #define SYSCALL(call) ;\ SetLastError(0);\ call;\ Perror(#call);\ ; // 检查Win32系统调用,同时将返回值赋值给某变量 #define SYSCALL2(call, recv) ;\ SetLastError(0);\ recv = call;\ Perror(#call);\ ; #define Perror(x) _Perror(x, __FILE__, __LINE__) void win32_init(); void init_locale(const char *locale); long _Perror(char *op, const char *file, int line); // ANSI转义序列 #define GREEN "\x1B[32m" #define RED "\x1B[91m" #define RESET "\x1B[0m" void enable_virtual_terminal_processing(); void alloc_console(); void balloon_notification(HWND hwnd, UINT id, const wchar_t *message); wchar_t *utf8to16(const char *str); char *utf16to8(const wchar_t *str); #ifdef __cplusplus } #endif #endif // __WIN32_HELPER__
<filename>Sources/KSPTableSection+Private.h // // KPTableSection+Private.h // KSPFetchedResultsController // // Created by <NAME> on 05.09.14. // Copyright (c) 2016 <NAME>. All rights reserved. // #import "KSPTableSection.h" @interface KSPTableSection () @property(readwrite, strong, nonatomic, nullable) NSArray<__kindof NSManagedObject*>* nestedObjects; // Returns a backing mutable array without making an immutable copy. - (nullable NSArray<__kindof NSManagedObject*>*) nestedObjectsNoCopy; @end
<filename>cef_binary_3.1547.1412_windows64/cefclient/resource.h //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by cefclient.rc // #define IDC_MYICON 2 #define IDD_CEFCLIENT_DIALOG 102 #define IDS_APP_TITLE 103 #define IDD_ABOUTBOX 103 #define IDM_ABOUT 104 #define IDM_EXIT 105 #define IDI_CEFCLIENT 107 #define IDI_SMALL 108 #define IDC_CEFCLIENT 109 #define IDS_OSR_WIDGET_CLASS 110 #define IDR_MAINFRAME 128 #define IDC_NAV_BACK 200 #define IDC_NAV_FORWARD 201 #define IDC_NAV_RELOAD 202 #define IDC_NAV_STOP 203 #define BINARY 256 #define IDS_BINDING 1000 #define IDS_DIALOGS 1001 #define IDS_DOMACCESS 1002 #define IDS_LOCALSTORAGE 1003 #define IDS_LOGO 1004 #define IDS_LOGOBALL 1005 #define IDS_OSRTEST 1006 #define IDS_OTHER_TESTS 1007 #define IDS_PERFORMANCE 1008 #define IDS_TRANSPARENCY 1009 #define IDS_WINDOW 1010 #define IDS_XMLHTTPREQUEST 1011 #define IDS_PERFORMANCE2 1012 #define ID_WARN_CONSOLEMESSAGE 32000 #define ID_WARN_DOWNLOADCOMPLETE 32001 #define ID_WARN_DOWNLOADERROR 32002 #define ID_QUIT 32500 #define ID_TESTS_GETSOURCE 32700 #define ID_TESTS_GETTEXT 32701 #define ID_TESTS_OTHER_TESTS 32702 #define ID_TESTS_PLUGIN_INFO 32703 #define ID_TESTS_POPUP 32704 #define ID_TESTS_REQUEST 32705 #define ID_TESTS_TRACING_BEGIN 32706 #define ID_TESTS_TRACING_END 32707 #define ID_TESTS_ZOOM_IN 32708 #define ID_TESTS_ZOOM_OUT 32709 #define ID_TESTS_ZOOM_RESET 32710 #define IDC_STATIC -1 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 #define _APS_NEXT_RESOURCE_VALUE 130 #define _APS_NEXT_COMMAND_VALUE 32774 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 111 #endif #endif
/* * Copyright (c) 2013-2018 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * * @precisions normal z -> s d c * */ #include "common.h" #include "dplasma/include/dplasmatypes.h" #include "parsec/data_dist/matrix/sym_two_dim_rectangle_cyclic.h" #include "parsec/data_dist/matrix/two_dim_rectangle_cyclic.h" #include "parsec/interfaces/superscalar/insert_function.h" #include "dplasma/lib/flops.h" enum regions { TILE_FULL, }; int parsec_core_potrf(parsec_execution_stream_t *es, parsec_task_t *this_task) { (void)es; PLASMA_enum uplo; int m, lda, *info; parsec_complex64_t *A; parsec_dtd_unpack_args(this_task, &uplo, &m, &A, &lda, &info); CORE_zpotrf(uplo, m, A, lda, info); return PARSEC_HOOK_RETURN_DONE; } int parsec_core_trsm(parsec_execution_stream_t *es, parsec_task_t *this_task) { (void)es; PLASMA_enum side, uplo, trans, diag; int m, n, lda, ldc; parsec_complex64_t alpha; parsec_complex64_t *A, *C; parsec_dtd_unpack_args(this_task, &side, &uplo, &trans, &diag, &m, &n, &alpha, &A, &lda, &C, &ldc); CORE_ztrsm(side, uplo, trans, diag, m, n, alpha, A, lda, C, ldc); return PARSEC_HOOK_RETURN_DONE; } int parsec_core_herk(parsec_execution_stream_t *es, parsec_task_t *this_task) { (void)es; PLASMA_enum uplo, trans; int m, n, lda, ldc; parsec_complex64_t alpha; parsec_complex64_t beta; parsec_complex64_t *A; parsec_complex64_t *C; parsec_dtd_unpack_args(this_task, &uplo, &trans, &m, &n, &alpha, &A, &lda, &beta, &C, &ldc); CORE_zherk(uplo, trans, m, n, alpha, A, lda, beta, C, ldc); return PARSEC_HOOK_RETURN_DONE; } int parsec_core_gemm(parsec_execution_stream_t *es, parsec_task_t *this_task) { (void)es; PLASMA_enum transA, transB; int m, n, k, lda, ldb, ldc; parsec_complex64_t alpha, beta; parsec_complex64_t *A; parsec_complex64_t *B; parsec_complex64_t *C; parsec_dtd_unpack_args(this_task, &transA, &transB, &m, &n, &k, &alpha, &A, &lda, &B, &ldb, &beta, &C, &ldc); CORE_zgemm(transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc); return PARSEC_HOOK_RETURN_DONE; } int main(int argc, char **argv) { parsec_context_t* parsec; int iparam[IPARAM_SIZEOF]; PLASMA_enum uplo = PlasmaUpper; int info = 0; int ret = 0; int m, n, k, total; /* loop counter */ /* Parameters passed on to Insert_task() */ int tempkm, tempmm, ldak, ldam, side, transA_p, transA_g, diag, trans, transB, ldan; parsec_complex64_t alpha_trsm, alpha_herk, beta; /* Set defaults for non argv iparams */ iparam_default_facto(iparam); iparam_default_ibnbmb(iparam, 0, 180, 180); #if defined(PARSEC_HAVE_CUDA) iparam[IPARAM_NGPUS] = 0; #endif /* Initialize PaRSEC */ parsec = setup_parsec(argc, argv, iparam); PASTE_CODE_IPARAM_LOCALS(iparam); PASTE_CODE_FLOPS(FLOPS_ZPOTRF, ((DagDouble_t)N)); /* initializing matrix structure */ LDA = dplasma_imax( LDA, N ); LDB = dplasma_imax( LDB, N ); SMB = 1; SNB = 1; PASTE_CODE_ALLOCATE_MATRIX(dcA, 1, sym_two_dim_block_cyclic, (&dcA, matrix_ComplexDouble, nodes, rank, MB, NB, LDA, N, 0, 0, N, N, P, uplo)); /* Initializing dc for dtd */ sym_two_dim_block_cyclic_t *__dcA = &dcA; parsec_dtd_data_collection_init((parsec_data_collection_t *)&dcA); /* matrix generation */ if(loud > 3) printf("+++ Generate matrices ... "); dplasma_zplghe( parsec, (double)(N), uplo, (parsec_tiled_matrix_dc_t *)&dcA, random_seed); if(loud > 3) printf("Done\n"); /* Getting new parsec handle of dtd type */ parsec_taskpool_t *dtd_tp = parsec_dtd_taskpool_new(); /* Allocating data arrays to be used by comm engine */ dplasma_add2arena_tile( parsec_dtd_arenas[TILE_FULL], dcA.super.mb*dcA.super.nb*sizeof(parsec_complex64_t), PARSEC_ARENA_ALIGNMENT_SSE, parsec_datatype_double_complex_t, dcA.super.mb ); /* Registering the handle with parsec context */ parsec_context_add_taskpool( parsec, dtd_tp ); SYNC_TIME_START(); /* #### parsec context Starting #### */ /* start parsec context */ parsec_context_start( parsec ); if( PlasmaLower == uplo ) { side = PlasmaRight; transA_p = PlasmaConjTrans; diag = PlasmaNonUnit; alpha_trsm = 1.0; trans = PlasmaNoTrans; alpha_herk = -1.0; beta = 1.0; transB = PlasmaConjTrans; transA_g = PlasmaNoTrans; total = dcA.super.mt; /* Testing Insert Function */ for( k = 0; k < total; k++ ) { tempkm = (k == (dcA.super.mt - 1)) ? dcA.super.m - k * dcA.super.mb : dcA.super.mb; ldak = BLKLDD(&dcA.super, k); parsec_dtd_taskpool_insert_task( dtd_tp, parsec_core_potrf, (total - k) * (total-k) * (total - k)/*priority*/, "Potrf", sizeof(int), &uplo, VALUE, sizeof(int), &tempkm, VALUE, PASSED_BY_REF, TILE_OF(A, k, k), INOUT | TILE_FULL | AFFINITY, sizeof(int), &ldak, VALUE, sizeof(int *), &info, SCRATCH, PARSEC_DTD_ARG_END ); for( m = k+1; m < total; m++ ) { tempmm = m == dcA.super.mt - 1 ? dcA.super.m - m * dcA.super.mb : dcA.super.mb; ldam = BLKLDD(&dcA.super, m); parsec_dtd_taskpool_insert_task( dtd_tp, parsec_core_trsm, (total - m) * (total-m) * (total - m) + 3 * ((2 * total) - k - m - 1) * (m - k)/*priority*/, "Trsm", sizeof(int), &side, VALUE, sizeof(int), &uplo, VALUE, sizeof(int), &transA_p, VALUE, sizeof(int), &diag, VALUE, sizeof(int), &tempmm, VALUE, sizeof(int), &dcA.super.nb, VALUE, sizeof(parsec_complex64_t), &alpha_trsm, VALUE, PASSED_BY_REF, TILE_OF(A, k, k), INPUT | TILE_FULL, sizeof(int), &ldak, VALUE, PASSED_BY_REF, TILE_OF(A, m, k), INOUT | TILE_FULL | AFFINITY, sizeof(int), &ldam, VALUE, PARSEC_DTD_ARG_END ); } parsec_dtd_data_flush( dtd_tp, TILE_OF(A, k, k) ); for( m = k+1; m < dcA.super.nt; m++ ) { tempmm = m == dcA.super.mt - 1 ? dcA.super.m - m * dcA.super.mb : dcA.super.mb; ldam = BLKLDD(&dcA.super, m); parsec_dtd_taskpool_insert_task( dtd_tp, parsec_core_herk, (total - m) * (total - m) * (total - m) + 3 * (m - k)/*priority*/, "Herk", sizeof(int), &uplo, VALUE, sizeof(int), &trans, VALUE, sizeof(int), &tempmm, VALUE, sizeof(int), &dcA.super.mb, VALUE, sizeof(parsec_complex64_t), &alpha_herk, VALUE, PASSED_BY_REF, TILE_OF(A, m, k), INPUT | TILE_FULL, sizeof(int), &ldam, VALUE, sizeof(parsec_complex64_t), &beta, VALUE, PASSED_BY_REF, TILE_OF(A, m, m), INOUT | TILE_FULL | AFFINITY, sizeof(int), &ldam, VALUE, PARSEC_DTD_ARG_END ); for( n = m+1; n < total; n++ ) { ldan = BLKLDD(&dcA.super, n); parsec_dtd_taskpool_insert_task( dtd_tp, parsec_core_gemm, (total - m) * (total - m) * (total - m) + 3 * ((2 * total) - m - n - 3) * (m - n) + 6 * (m - k) /*priority*/, "Gemm", sizeof(int), &transA_g, VALUE, sizeof(int), &transB, VALUE, sizeof(int), &tempmm, VALUE, sizeof(int), &dcA.super.mb, VALUE, sizeof(int), &dcA.super.mb, VALUE, sizeof(parsec_complex64_t), &alpha_herk, VALUE, PASSED_BY_REF, TILE_OF(A, n, k), INPUT | TILE_FULL, sizeof(int), &ldan, VALUE, PASSED_BY_REF, TILE_OF(A, m, k), INPUT | TILE_FULL, sizeof(int), &ldam, VALUE, sizeof(parsec_complex64_t), &beta, VALUE, PASSED_BY_REF, TILE_OF(A, n, m), INOUT | TILE_FULL | AFFINITY, sizeof(int), &ldan, VALUE, PARSEC_DTD_ARG_END ); } parsec_dtd_data_flush( dtd_tp, TILE_OF(A, m, k) ); } } } else { side = PlasmaLeft; transA_p = PlasmaConjTrans; diag = PlasmaNonUnit; alpha_trsm = 1.0; trans = PlasmaConjTrans; alpha_herk = -1.0; beta = 1.0; transB = PlasmaNoTrans; transA_g = PlasmaConjTrans; total = dcA.super.nt; for( k = 0; k < total; k++ ) { tempkm = k == dcA.super.nt-1 ? dcA.super.n-k*dcA.super.nb : dcA.super.nb; ldak = BLKLDD(&dcA.super, k); parsec_dtd_taskpool_insert_task( dtd_tp, parsec_core_potrf, (total - k) * (total-k) * (total - k)/*priority*/, "Potrf", sizeof(int), &uplo, VALUE, sizeof(int), &tempkm, VALUE, PASSED_BY_REF, TILE_OF(A, k, k), INOUT | TILE_FULL | AFFINITY, sizeof(int), &ldak, VALUE, sizeof(int *), &info, SCRATCH, PARSEC_DTD_ARG_END ); for( m = k+1; m < total; m++ ) { tempmm = m == dcA.super.nt-1 ? dcA.super.n-m*dcA.super.nb : dcA.super.nb; parsec_dtd_taskpool_insert_task( dtd_tp, parsec_core_trsm, (total - m) * (total-m) * (total - m) + 3 * ((2 * total) - k - m - 1) * (m - k)/*priority*/, "Trsm", sizeof(int), &side, VALUE, sizeof(int), &uplo, VALUE, sizeof(int), &transA_p, VALUE, sizeof(int), &diag, VALUE, sizeof(int), &dcA.super.nb, VALUE, sizeof(int), &tempmm, VALUE, sizeof(parsec_complex64_t), &alpha_trsm, VALUE, PASSED_BY_REF, TILE_OF(A, k, k), INPUT | TILE_FULL, sizeof(int), &ldak, VALUE, PASSED_BY_REF, TILE_OF(A, k, m), INOUT | TILE_FULL | AFFINITY, sizeof(int), &ldak, VALUE, PARSEC_DTD_ARG_END ); } parsec_dtd_data_flush( dtd_tp, TILE_OF(A, k, k) ); for( m = k+1; m < dcA.super.mt; m++ ) { tempmm = m == dcA.super.nt-1 ? dcA.super.n-m*dcA.super.nb : dcA.super.nb; ldam = BLKLDD(&dcA.super, m); parsec_dtd_taskpool_insert_task( dtd_tp, parsec_core_herk, (total - m) * (total - m) * (total - m) + 3 * (m - k)/*priority*/, "Herk", sizeof(int), &uplo, VALUE, sizeof(int), &trans, VALUE, sizeof(int), &tempmm, VALUE, sizeof(int), &dcA.super.mb, VALUE, sizeof(parsec_complex64_t), &alpha_herk, VALUE, PASSED_BY_REF, TILE_OF(A, k, m), INPUT | TILE_FULL, sizeof(int), &ldak, VALUE, sizeof(parsec_complex64_t), &beta, VALUE, PASSED_BY_REF, TILE_OF(A, m, m), INOUT | TILE_FULL | AFFINITY, sizeof(int), &ldam, VALUE, PARSEC_DTD_ARG_END ); for( n = m+1; n < total; n++ ) { ldan = BLKLDD(&dcA.super, n); parsec_dtd_taskpool_insert_task( dtd_tp, parsec_core_gemm, (total - m) * (total - m) * (total - m) + 3 * ((2 * total) - m - n - 3) * (m - n) + 6 * (m - k) /*priority*/, "Gemm", sizeof(int), &transA_g, VALUE, sizeof(int), &transB, VALUE, sizeof(int), &dcA.super.mb, VALUE, sizeof(int), &tempmm, VALUE, sizeof(int), &dcA.super.mb, VALUE, sizeof(parsec_complex64_t), &alpha_herk, VALUE, PASSED_BY_REF, TILE_OF(A, k, m), INPUT | TILE_FULL, sizeof(int), &ldak, VALUE, PASSED_BY_REF, TILE_OF(A, k, n), INPUT | TILE_FULL, sizeof(int), &ldak, VALUE, sizeof(parsec_complex64_t), &beta, VALUE, PASSED_BY_REF, TILE_OF(A, m, n), INOUT | TILE_FULL | AFFINITY, sizeof(int), &ldan, VALUE, PARSEC_DTD_ARG_END ); } parsec_dtd_data_flush( dtd_tp, TILE_OF(A, k, m) ); } } } parsec_dtd_data_flush_all( dtd_tp, (parsec_data_collection_t *)&dcA ); /* finishing all the tasks inserted, but not finishing the handle */ parsec_dtd_taskpool_wait( parsec, dtd_tp ); /* Waiting on all handle and turning everything off for this context */ parsec_context_wait( parsec ); /* #### PaRSEC context is done #### */ SYNC_TIME_PRINT(rank, ("\tPxQ= %3d %-3d NB= %4d N= %7d : %14f gflops\n", P, Q, NB, N, gflops=(flops/1e9)/sync_time_elapsed)); /* Cleaning up the parsec handle */ parsec_taskpool_free( dtd_tp ); if( 0 == rank && info != 0 ) { printf("-- Factorization is suspicious (info = %d) ! \n", info); ret |= 1; } if( !info && check ) { /* Check the factorization */ PASTE_CODE_ALLOCATE_MATRIX(dcA0, check, sym_two_dim_block_cyclic, (&dcA0, matrix_ComplexDouble, nodes, rank, MB, NB, LDA, N, 0, 0, N, N, P, uplo)); dplasma_zplghe( parsec, (double)(N), uplo, (parsec_tiled_matrix_dc_t *)&dcA0, random_seed); ret |= check_zpotrf( parsec, (rank == 0) ? loud : 0, uplo, (parsec_tiled_matrix_dc_t *)&dcA, (parsec_tiled_matrix_dc_t *)&dcA0); /* Check the solution */ PASTE_CODE_ALLOCATE_MATRIX(dcB, check, two_dim_block_cyclic, (&dcB, matrix_ComplexDouble, matrix_Tile, nodes, rank, MB, NB, LDB, NRHS, 0, 0, N, NRHS, SMB, SNB, P)); dplasma_zplrnt( parsec, 0, (parsec_tiled_matrix_dc_t *)&dcB, random_seed+1); PASTE_CODE_ALLOCATE_MATRIX(dcX, check, two_dim_block_cyclic, (&dcX, matrix_ComplexDouble, matrix_Tile, nodes, rank, MB, NB, LDB, NRHS, 0, 0, N, NRHS, SMB, SNB, P)); dplasma_zlacpy( parsec, PlasmaUpperLower, (parsec_tiled_matrix_dc_t *)&dcB, (parsec_tiled_matrix_dc_t *)&dcX ); dplasma_zpotrs(parsec, uplo, (parsec_tiled_matrix_dc_t *)&dcA, (parsec_tiled_matrix_dc_t *)&dcX ); ret |= check_zaxmb( parsec, (rank == 0) ? loud : 0, uplo, (parsec_tiled_matrix_dc_t *)&dcA0, (parsec_tiled_matrix_dc_t *)&dcB, (parsec_tiled_matrix_dc_t *)&dcX); /* Cleanup */ parsec_data_free(dcA0.mat); dcA0.mat = NULL; parsec_tiled_matrix_dc_destroy( (parsec_tiled_matrix_dc_t*)&dcA0 ); parsec_data_free(dcB.mat); dcB.mat = NULL; parsec_tiled_matrix_dc_destroy( (parsec_tiled_matrix_dc_t*)&dcB ); parsec_data_free(dcX.mat); dcX.mat = NULL; parsec_tiled_matrix_dc_destroy( (parsec_tiled_matrix_dc_t*)&dcX ); } /* Cleaning data arrays we allocated for communication */ parsec_matrix_del2arena( parsec_dtd_arenas[TILE_FULL] ); parsec_dtd_data_collection_fini( (parsec_data_collection_t *)&dcA ); parsec_data_free(dcA.mat); dcA.mat = NULL; parsec_tiled_matrix_dc_destroy( (parsec_tiled_matrix_dc_t*)&dcA); cleanup_parsec(parsec, iparam); return ret; }
// // SDMChooseKindView.h // ToyotaSearch // // Created by <NAME> on 2021/4/21. // #import <UIKit/UIKit.h> #import "SDMMainKindView.h" #import "SDMBrunckPicksView.h" NS_ASSUME_NONNULL_BEGIN @interface SDMChooseKindView : UIView @property (weak, nonatomic) IBOutlet UIScrollView *ScrollView; @property (weak, nonatomic) IBOutlet UIView *ChooseOneView; @property (weak, nonatomic) IBOutlet UIView *ChooseTwoView; @property (weak, nonatomic) IBOutlet UIView *ChooseThreeView; @property (weak, nonatomic) IBOutlet SDMMainKindView *ChooseOneKindView; @property (weak, nonatomic) IBOutlet SDMBrunckPicksView *ChooseTwoKindView; @property (weak, nonatomic) IBOutlet SDMBrunckPicksView *ChooseThreeKindView; @end NS_ASSUME_NONNULL_END
#import <SSignalKit/SSignalKit.h> @interface TGTwoStepSetPaswordSignal : NSObject + (SSignal *)setPasswordWithCurrentSalt:(NSData *)currentSalt currentPassword:(NSString *)currentPassword nextSalt:(NSData *)nextSalt nextPassword:(NSString *)nextPassword nextHint:(NSString *)nextHint email:(NSString *)email; + (SSignal *)setRecoveryEmail:(NSData *)currentSalt currentPassword:(NSString *)currentPassword recoveryEmail:(NSString *)recoveryEmail; @end
// vtkdevideIOWin32Header - manage Windows system differences // $Id: vtkdevideIOWin32Header.h,v 1.1 2004/01/15 11:00:55 cpbotha Exp $ // The vtkdevideIOWin32Header captures some system differences between Unix // and Windows operating systems. #ifndef __vtkdevideIOWin32Header_h #define __vtkdevideIOWin32Header_h #include <vtkdevideConfigure.h> #if defined(WIN32) && !defined(VTK_DEVIDE_STATIC) #if defined(vtkdevideIO_EXPORTS) #define VTK_DEVIDE_IO_EXPORT __declspec( dllexport ) #else #define VTK_DEVIDE_IO_EXPORT __declspec( dllimport ) #endif #else #define VTK_DEVIDE_IO_EXPORT #endif #endif
<filename>base/src/silc_mgmtd/mgmtd/src/silc_mgmtd_memdb.c #include "silc_common.h" #include "silc_mgmtd_error.h" #include "silc_mgmtd_memdb.h" #include "silc_mgmtd_interface.h" static silc_mgmtd_node s_silc_mgmtd_memdb_root; static silc_bool s_silc_mgmtd_memdb_config_unsave = silc_false; int silc_mgmtd_memdb_init() { #ifdef SILC_MGMTD_LOCAL_DEBUG silc_log_level_set(SILC_LOG_LEVEL_DEBUG); #endif silc_list_init(&s_silc_mgmtd_memdb_root.sub_node_list); silc_list_init(&s_silc_mgmtd_memdb_root.do_ops_err_list); silc_list_init(&s_silc_mgmtd_memdb_root.ref_node_list); return 0; } void silc_mgmtd_memdb_deinit() { silc_mgmtd_node *p_sub_node, *p_tmp_node; silc_list_for_each_entry_safe(p_sub_node, p_tmp_node, &s_silc_mgmtd_memdb_root.sub_node_list, node) { silc_mgmtd_memdb_delete_node(p_sub_node); } silc_list_init(&s_silc_mgmtd_memdb_root.sub_node_list); } void silc_mgmtd_memdb_set_config_saved() { s_silc_mgmtd_memdb_config_unsave = silc_false; } void silc_mgmtd_memdb_set_config_unsave() { s_silc_mgmtd_memdb_config_unsave = silc_true; } silc_bool silc_mgmtd_memdb_is_config_saved() { return !s_silc_mgmtd_memdb_config_unsave; } /* * node lock */ pthread_mutex_t* silc_mgmtd_memdb_node_create_lock() { pthread_mutex_t* p_lock = malloc(sizeof(pthread_mutex_t)); if(!p_lock) { silc_mgmtd_err_set(MGMTD_ERR_CLIB, __func__); return NULL; } pthread_mutex_init(p_lock, NULL); return p_lock; } silc_mgmtd_node* silc_mgmtd_memdb_find_config_module_node(silc_mgmtd_node* p_node) { silc_mgmtd_node* p_curr = p_node; silc_mgmtd_node* p_parent = p_node->p_parent; while(p_parent) { if(strcmp(p_parent->name, "config") == 0) { if(!p_node->p_lock) // module node need a lock { p_node->p_lock = silc_mgmtd_memdb_node_create_lock(); if(!p_node->p_lock) return NULL; } return p_node; } p_curr = p_parent; p_parent = p_curr->p_parent; } silc_mgmtd_err_set(MGMTD_ERR_MEMDB_NOT_CONFIG_NODE, __func__); return NULL; } int silc_mgmtd_memdb_node_r_lock(silc_mgmtd_node* p_node) { if(pthread_mutex_trylock(p_node->p_lock) == 0) { p_node->rlocked_cnt++; pthread_mutex_unlock(p_node->p_lock); } else { char info[200]; sprintf(info, "Locked by user %s", silc_mgmtd_if_server_get_conn_index_user(p_node->wlock_owner)); silc_mgmtd_err_set(MGMTD_ERR_MEMDB_NODE_LOCKED, info); return -1; } return 0; } void silc_mgmtd_memdb_node_r_unlock(silc_mgmtd_node* p_node) { pthread_mutex_lock(p_node->p_lock); p_node->rlocked_cnt--; pthread_mutex_unlock(p_node->p_lock); } int silc_mgmtd_memdb_node_w_lock(silc_mgmtd_node* p_node, uint16_t wlock_owner, silc_bool is_wait) { pthread_mutex_lock(p_node->p_lock); if(p_node->rlocked_cnt) { pthread_mutex_unlock(p_node->p_lock); if(!is_wait) { char info[200]; sprintf(info, "Locked by user %s", silc_mgmtd_if_server_get_conn_index_user(p_node->wlock_owner)); silc_mgmtd_err_set(MGMTD_ERR_MEMDB_NODE_LOCKED, info); return -1; } while(1) { pthread_mutex_lock(p_node->p_lock); if(p_node->rlocked_cnt == 0) { break; } else { pthread_mutex_unlock(p_node->p_lock); usleep(10000); } } } p_node->wlock_owner = wlock_owner; return 0; } void silc_mgmtd_memdb_node_w_unlock(silc_mgmtd_node* p_node) { p_node->wlock_owner = 0; pthread_mutex_unlock(p_node->p_lock); } silc_cstr silc_mgmtd_memdb_path_get_last_name(const silc_cstr path) { int loop; int path_len = strlen(path); for(loop=path_len; loop>=0; loop--) { if(path[loop] == '/') return path+loop+1; } return path; } /* * not safe */ silc_cstr silc_mgmtd_memdb_get_node_path(silc_mgmtd_node* p_node, silc_cstr path) { char tmp[SILC_MGMTD_IF_PATH_MAX_LEN]; strcpy(path, ""); while(p_node) { strcpy(tmp, path); if(p_node->type == MEMDB_NODE_TYPE_DYNAMIC) silc_mgmtd_var_to_str(&p_node->value, path, 200); else sprintf(path, "%s", p_node->name); if(strlen(tmp) != 0) { strcat(path, "/"); strcat(path, tmp); } p_node = p_node->p_parent; } if(strlen(path) == 0) strcpy(path, "/"); return path; } silc_mgmtd_node* silc_mgmtd_memdb_create_node(const silc_cstr node_name, silc_mgmtd_if_privilege level, silc_mgmtd_node_type node_type, silc_mgmtd_var_type val_type, const silc_cstr val_str, silc_mgmtd_node_callback do_ops, int timeout) { silc_mgmtd_node* p_node; p_node = malloc(sizeof(silc_mgmtd_node)); if(!p_node) { silc_mgmtd_err_set(MGMTD_ERR_CLIB, __func__); return NULL; } memset(p_node, 0, sizeof(silc_mgmtd_node)); strcpy(p_node->name, node_name); p_node->type = node_type; p_node->if_level = level; p_node->do_ops = do_ops; p_node->do_ops_timeout = timeout; p_node->value.type = val_type; if(p_node->value.type != SILC_MGMTD_VAR_NULL && val_str && strcmp(val_str, "None") != 0 && strcmp(val_str, "null") != 0) { if(silc_mgmtd_var_set_by_str(&p_node->value, val_str) < 0) { free(p_node); silc_mgmtd_err_set(MGMTD_ERR_MGMTD_LIB, val_str); return NULL; } } p_node->tmp_value.type = SILC_MGMTD_VAR_NULL; silc_list_init(&p_node->sub_node_list); silc_list_init(&p_node->ref_node_list); silc_list_init(&p_node->do_ops_err_list); return p_node; } void silc_mgmtd_memdb_insert_node(silc_mgmtd_node* p_node, silc_mgmtd_node* p_parent) { p_node->p_parent = p_parent; silc_list_add_tail(&p_node->node, &p_parent->sub_node_list); } int silc_mgmtd_memdb_add_node(const silc_cstr node_path, silc_mgmtd_if_privilege level, silc_mgmtd_node_type node_type, silc_mgmtd_var_type val_type, const silc_cstr val_str, silc_mgmtd_node_callback do_ops, int timeout) { silc_mgmtd_node *p_node, *p_parent; silc_cstr node_name; p_node = silc_mgmtd_memdb_find_node(node_path); if(p_node) return 0; p_parent = silc_mgmtd_memdb_find_parent(node_path); if(!p_parent) return -1; node_name = silc_mgmtd_memdb_path_get_last_name(node_path); p_node = silc_mgmtd_memdb_create_node(node_name, level, node_type, val_type, val_str, do_ops, timeout); if(!p_node) return -1; // for init, set the tmp value to enable the configuration silc_mgmtd_var_copy(&p_node->value, &p_node->tmp_value); silc_mgmtd_memdb_insert_node(p_node, p_parent); return 0; } int silc_mgmtd_memdb_add_node_ref(const silc_cstr node_path, const silc_cstr path, silc_mgmtd_node_ref_callback do_ref) { silc_mgmtd_node_ref* p_ref; silc_mgmtd_node *p_node, *p_parent; p_parent = silc_mgmtd_memdb_find_parent(node_path); if(!p_parent) return -1; if(silc_list_empty(&p_parent->sub_node_list)) { silc_mgmtd_err_set(MGMTD_ERR_MEMDB_PARENT_NO_CHILD, __func__); return -1; } p_node = silc_list_entry(p_parent->sub_node_list.next, silc_mgmtd_node, node); if(p_node->type != MEMDB_NODE_TYPE_TEMPLATE) { silc_mgmtd_err_set(MGMTD_ERR_MEMDB_NOT_DYNC_NODE, __func__); return -1; } p_ref = malloc(sizeof(silc_mgmtd_node_ref) + strlen(path) + 1); if(!p_ref) { silc_mgmtd_err_set(MGMTD_ERR_CLIB, __func__); return -1; } p_ref->do_ref = do_ref; p_ref->path = (silc_cstr)(p_ref+1); strcpy(p_ref->path, path); silc_list_add_tail(&p_ref->node, &p_node->ref_node_list); return 0; } int silc_mgmtd_memdb_clone_node_inner(silc_mgmtd_node* p_src_node, silc_mgmtd_node* p_dst_parent) { silc_mgmtd_node* p_node; silc_mgmtd_node* p_src_sub_node; char val_str[200]; if(p_src_node->type != MEMDB_NODE_TYPE_TEMPLATE_SUB && p_src_node->type != MEMDB_NODE_TYPE_TEMPLATE) { silc_mgmtd_err_set(MGMTD_ERR_MEMDB_NOT_DYNC_NODE, __func__); return -1; } p_node = silc_mgmtd_memdb_create_node(p_src_node->name, p_src_node->if_level, p_src_node->type, p_src_node->value.type, silc_mgmtd_var_to_str(&p_src_node->value, val_str, 200), p_src_node->do_ops, p_src_node->do_ops_timeout); if(!p_node) return -1; if(p_dst_parent->type == MEMDB_NODE_TYPE_TEMPLATE) p_node->type = MEMDB_NODE_TYPE_TEMPLATE_SUB; else if(p_src_node->type == MEMDB_NODE_TYPE_TEMPLATE_SUB) p_node->type = MEMDB_NODE_TYPE_DYNAMIC_SUB; else p_node->type = MEMDB_NODE_TYPE_TEMPLATE; silc_mgmtd_memdb_insert_node(p_node, p_dst_parent); // printf("clone node:%s\n", p_node->name); silc_list_for_each_entry(p_src_sub_node, &p_src_node->sub_node_list, node) { if(silc_mgmtd_memdb_clone_node_inner(p_src_sub_node, p_node) < 0) return -1; } return 0; } silc_mgmtd_node* silc_mgmtd_memdb_clone_node(silc_mgmtd_node* p_src_node) { silc_mgmtd_node* p_node; silc_mgmtd_node* p_src_sub_node; char val_str[200]; if(p_src_node->type != MEMDB_NODE_TYPE_TEMPLATE) { silc_mgmtd_err_set(MGMTD_ERR_MEMDB_NOT_DYNC_NODE, __func__); return NULL; } p_node = silc_mgmtd_memdb_create_node(p_src_node->name, p_src_node->if_level, p_src_node->type, p_src_node->value.type, silc_mgmtd_var_to_str(&p_src_node->value, val_str, 200), p_src_node->do_ops, p_src_node->do_ops_timeout); if(!p_node) return NULL; p_node->type = MEMDB_NODE_TYPE_DYNAMIC; p_node->p_parent = p_src_node->p_parent; silc_list_for_each_entry(p_src_sub_node, &p_src_node->sub_node_list, node) { if(silc_mgmtd_memdb_clone_node_inner(p_src_sub_node, p_node) < 0) { silc_mgmtd_memdb_delete_node(p_node); return NULL; } } return p_node; } void silc_mgmtd_memdb_delete_node(silc_mgmtd_node* p_node) { silc_mgmtd_node *p_sub_node, *p_tmp_node; silc_list_for_each_entry_safe(p_sub_node, p_tmp_node, &p_node->sub_node_list, node) { silc_mgmtd_memdb_delete_node(p_sub_node); } silc_mgmtd_var_clear(&p_node->value); if(!silc_list_empty(&p_node->do_ops_err_list)) { silc_mgmtd_cb_err *p_err, *p_tmp_err; silc_list_for_each_entry_safe(p_err, p_tmp_err, &p_node->do_ops_err_list, node) { free(p_err); } } if(p_node->p_lock) free(p_node->p_lock); free(p_node); } silc_mgmtd_node* silc_mgmtd_memdb_find_node_comm(const silc_cstr node_path, silc_mgmtd_node* p_root) { int name_len; char name[SILC_MGMTD_MEMDB_NAME_MAX_LEN]; silc_mgmtd_node* p_node; silc_cstr sub_path, path; char val_str[200]; if(strcmp(node_path, "/") == 0) return p_root; if(node_path[0] == '/') path = node_path + 1; else path = node_path; if(strlen(path) == 0) return p_root; sub_path = strstr(path, "/"); if(!sub_path) sub_path = path + strlen(path); name_len = sub_path - path; strncpy(name, path, name_len); name[name_len] = '\0'; silc_list_for_each_entry(p_node, &p_root->sub_node_list, node) { if(p_node->type == MEMDB_NODE_TYPE_TEMPLATE || p_node->type == MEMDB_NODE_TYPE_TEMPLATE_SUB) continue; if(p_node->type == MEMDB_NODE_TYPE_DYNAMIC) { if(strcmp(name, silc_mgmtd_var_to_str(&p_node->value, val_str, 200)) == 0) return silc_mgmtd_memdb_find_node_comm(sub_path, p_node); } else { if(strcmp(name, p_node->name) == 0) return silc_mgmtd_memdb_find_node_comm(sub_path, p_node); } } silc_mgmtd_err_set(MGMTD_ERR_MEMDB_NODE_NOTEXIST, node_path); return NULL; } silc_mgmtd_node* silc_mgmtd_memdb_find_node(const silc_cstr node_path) { return silc_mgmtd_memdb_find_node_comm(node_path, &s_silc_mgmtd_memdb_root); } silc_mgmtd_node* silc_mgmtd_memdb_find_init_node_comm(const silc_cstr node_path, silc_mgmtd_node* p_root) { int name_len; char name[SILC_MGMTD_MEMDB_NAME_MAX_LEN]; silc_mgmtd_node* p_node; silc_cstr sub_path, path; if(strcmp(node_path, "/") == 0) return p_root; if(node_path[0] == '/') path = node_path + 1; else path = node_path; if(strlen(path) == 0) return p_root; sub_path = strstr(path, "/"); if(!sub_path) sub_path = path + strlen(path); name_len = sub_path - path; strncpy(name, path, name_len); name[name_len] = '\0'; silc_list_for_each_entry(p_node, &p_root->sub_node_list, node) { if(p_node->type == MEMDB_NODE_TYPE_TEMPLATE) { if(strcmp(name, "*") == 0) return silc_mgmtd_memdb_find_init_node_comm(sub_path, p_node); continue; } if(p_node->type != MEMDB_NODE_TYPE_DYNAMIC) { if(strcmp(name, p_node->name) == 0) return silc_mgmtd_memdb_find_init_node_comm(sub_path, p_node); } } silc_mgmtd_err_set(MGMTD_ERR_MEMDB_NODE_NOTEXIST, node_path); return NULL; } silc_mgmtd_node* silc_mgmtd_memdb_find_init_node(const silc_cstr node_path) { return silc_mgmtd_memdb_find_init_node_comm(node_path, &s_silc_mgmtd_memdb_root); } silc_mgmtd_node* silc_mgmtd_memdb_find_node_top_inner(const silc_cstr node_path, silc_mgmtd_node* p_root) { int name_len; char name[SILC_MGMTD_MEMDB_NAME_MAX_LEN]; silc_mgmtd_node* p_node; silc_cstr sub_path, path; // char val_str[200]; if(strcmp(node_path, "/") == 0) return p_root; if(node_path[0] == '/') path = node_path + 1; else path = node_path; if(strlen(path) == 0) return p_root; sub_path = strstr(path, "/"); if(!sub_path) sub_path = path + strlen(path); name_len = sub_path - path; strncpy(name, path, name_len); name[name_len] = '\0'; silc_list_for_each_entry(p_node, &p_root->sub_node_list, node) { if(strcmp(name, p_node->name) == 0) { if(p_node->do_ops) return p_node; return silc_mgmtd_memdb_find_node_top_inner(sub_path, p_node); } } silc_mgmtd_err_set(MGMTD_ERR_MEMDB_NODE_NOTEXIST, node_path); return NULL; } silc_mgmtd_node* silc_mgmtd_memdb_find_node_top(const silc_cstr node_path) { return silc_mgmtd_memdb_find_node_top_inner(node_path, &s_silc_mgmtd_memdb_root); } silc_mgmtd_node* silc_mgmtd_memdb_find_parent_inner(const silc_cstr node_path, silc_mgmtd_node* p_root) { int name_len; char name[SILC_MGMTD_MEMDB_NAME_MAX_LEN]; silc_mgmtd_node* p_node; silc_cstr sub_path, path; char val_str[200]; if(node_path[0] == '/') path = node_path + 1; else path = node_path; if(strlen(path) == 0) return p_root; sub_path = strstr(path, "/"); if(!sub_path) return p_root; name_len = sub_path - path; strncpy(name, path, name_len); name[name_len] = '\0'; silc_list_for_each_entry(p_node, &p_root->sub_node_list, node) { if(p_node->type == MEMDB_NODE_TYPE_DYNAMIC) { if(strcmp(name, silc_mgmtd_var_to_str(&p_node->value, val_str, 200)) == 0) return silc_mgmtd_memdb_find_parent_inner(sub_path, p_node); } else { if(strcmp(name, p_node->name) == 0) return silc_mgmtd_memdb_find_parent_inner(sub_path, p_node); } } silc_mgmtd_err_set(MGMTD_ERR_MEMDB_PARENT_NOTEXIST, node_path); return NULL; } silc_mgmtd_node* silc_mgmtd_memdb_find_parent(const silc_cstr node_path) { return silc_mgmtd_memdb_find_parent_inner(node_path, &s_silc_mgmtd_memdb_root); } silc_mgmtd_node* silc_mgmtd_memdb_find_sub_node(silc_mgmtd_node* p_node, const silc_cstr name) { char info[200]; silc_mgmtd_node* p_sub_node; silc_list_for_each_entry(p_sub_node, &p_node->sub_node_list, node) { if(strcmp(p_sub_node->name, name) == 0) return p_sub_node; } silc_mgmtd_memdb_get_node_path(p_node, info); sprintf(info+strlen(info), "/%s", name); silc_mgmtd_err_set(MGMTD_ERR_MEMDB_NODE_NOTEXIST, info); return NULL; } silc_mgmtd_node* silc_mgmtd_memdb_find_sub_value(silc_mgmtd_node* p_node, const silc_cstr val_str) { char info[200]; silc_mgmtd_node* p_sub_node; silc_list_for_each_entry(p_sub_node, &p_node->sub_node_list, node) { char val[200]; if(p_sub_node->type == MEMDB_NODE_TYPE_TEMPLATE) continue; silc_mgmtd_var_to_str(&p_sub_node->value, val, 200); if(strcmp(val, val_str) == 0) return p_sub_node; } silc_mgmtd_memdb_get_node_path(p_node, info); sprintf(info+strlen(info), " has not sub value %s", val_str); silc_mgmtd_err_set(MGMTD_ERR_MEMDB_NODE_NOTEXIST, info); return NULL; } int silc_mgmtd_memdb_modify_node(silc_mgmtd_node* p_node, const silc_cstr new_val_str) { if(p_node->value.type == SILC_MGMTD_VAR_NULL) return 0; //if(strlen(new_val_str) == 0) //return 0; if(p_node->type == MEMDB_NODE_TYPE_DYNAMIC) return 0; silc_mgmtd_var_clear(&p_node->tmp_value); p_node->tmp_value.type = p_node->value.type; if(silc_mgmtd_var_set_by_str(&p_node->tmp_value, new_val_str) < 0) { p_node->tmp_value.type = SILC_MGMTD_VAR_NULL; silc_mgmtd_err_set(MGMTD_ERR_MGMTD_LIB, __func__); return -1; } return 0; } int silc_mgmtd_memdb_modify_node_confirm(silc_mgmtd_node* p_node) { if(p_node->tmp_value.type == SILC_MGMTD_VAR_NULL) return 0; silc_mgmtd_var_clear(&p_node->value); if(silc_mgmtd_var_copy(&p_node->tmp_value, &p_node->value) < 0) { silc_mgmtd_err_set(MGMTD_ERR_MGMTD_LIB, __func__); return -1; } return 0; } int silc_mgmtd_memdb_add_cb_err(const silc_cstr node_path, int err_num, const silc_cstr err_str) { silc_mgmtd_cb_err* p_err; silc_mgmtd_node *p_node; p_node = silc_mgmtd_memdb_find_node(node_path); if(!p_node) return -1; p_err = malloc(sizeof(silc_mgmtd_cb_err) + strlen(err_str) + 1); if(!p_err) { silc_mgmtd_err_set(MGMTD_ERR_CLIB, __func__); return -1; } p_err->err_num = err_num; p_err->err_str = (silc_cstr)(p_err+1); strcpy(p_err->err_str, err_str); silc_list_add_tail(&p_err->node, &p_node->do_ops_err_list); return 0; } silc_cstr silc_mgmtd_memdb_get_cb_err(silc_mgmtd_node* p_node, int err_num) { silc_mgmtd_cb_err* p_err; if(!p_node) return NULL; silc_list_for_each_entry(p_err, &p_node->do_ops_err_list, node) { if(p_err->err_num == err_num) return p_err->err_str; } return silc_mgmtd_memdb_get_cb_err(p_node->p_parent, err_num); } int silc_mgmtd_memdb_dnode_tree_traversal_inner(const silc_cstr parent_path, silc_mgmtd_node* p_db_node, silc_mgmtd_if_node* p_if_node, silc_mgmtd_memdb_dnode_traversal_cb cb_func, void* data) { int ret = 0; char path[SILC_MGMTD_IF_PATH_MAX_LEN]; silc_mgmtd_if_node* p_if_sub_node; silc_mgmtd_node* p_db_sub_node; if(!p_db_node) return 0; if(strlen(p_if_node->name) == 0) // node root strcpy(path, ""); else if(strlen(parent_path)) sprintf(path, "%s/%s", parent_path, p_db_node->name); else strcpy(path, p_db_node->name); if(cb_func) ret = cb_func(path, p_if_node, p_db_node, data); if(ret != 0) { silc_mgmtd_err_set(MGMTD_ERR_MEMDB_TRAVERSAL_ERR, path); return ret; } silc_list_for_each_entry(p_if_sub_node, &p_if_node->sub_node_list, node) { if(p_if_sub_node->add_dync) continue; silc_list_for_each_entry(p_db_sub_node, &p_db_node->sub_node_list, node) { if(p_db_sub_node->type == MEMDB_NODE_TYPE_DYNAMIC) { char val_str[100]; silc_mgmtd_var_to_str(&p_db_sub_node->value, val_str, 100); if(strcmp(val_str, p_if_sub_node->name) != 0) continue; } if(strcmp(p_db_sub_node->name, p_if_sub_node->name) != 0) continue; ret = silc_mgmtd_memdb_dnode_tree_traversal_inner(path, p_db_sub_node, p_if_sub_node, cb_func, data); if(ret != 0) return ret; } } return 0; } int silc_mgmtd_memdb_dnode_tree_traversal(silc_mgmtd_node* p_db_node, silc_mgmtd_if_node* p_if_node, silc_mgmtd_memdb_dnode_traversal_cb cb_func, void* cb_data) { return silc_mgmtd_memdb_dnode_tree_traversal_inner("", p_db_node, p_if_node, cb_func, cb_data); } int silc_mgmtd_memdb_node_tree_traversal(const silc_cstr parent_path, silc_mgmtd_node* p_db_node, silc_mgmtd_memdb_node_traversal_cb cb_func, void* cb_data) { int ret = 0; silc_mgmtd_node* p_db_sub_node; char path[SILC_MGMTD_IF_PATH_MAX_LEN]; char val_str[200]; if(strlen(parent_path) == 0) strcpy(path, p_db_node->name); else if(strcmp(parent_path, "/") == 0) sprintf(path, "/%s", p_db_node->name); else if(p_db_node->type == MEMDB_NODE_TYPE_DYNAMIC) sprintf(path, "%s/%s", parent_path, silc_mgmtd_var_to_str(&p_db_node->value, val_str, 200)); else sprintf(path, "%s/%s", parent_path, p_db_node->name); if(cb_func) ret = cb_func(path, p_db_node, cb_data); if(ret != 0) { silc_mgmtd_err_set(MGMTD_ERR_MEMDB_TRAVERSAL_ERR, path); return ret; } silc_list_for_each_entry(p_db_sub_node, &p_db_node->sub_node_list, node) { ret = silc_mgmtd_memdb_node_tree_traversal(path, p_db_sub_node, cb_func, cb_data); } return ret; } int silc_mgmtd_memdb_if_node_tree_traversal(const silc_cstr parent_path, silc_mgmtd_if_node* p_if_node, silc_mgmtd_memdb_if_node_traversal_cb cb_func, void* cb_data) { int ret = 0; silc_mgmtd_if_node* p_if_sub_node; char path[SILC_MGMTD_IF_PATH_MAX_LEN]; if(strlen(parent_path) == 0) strcpy(path, p_if_node->name); else if(strcmp(parent_path, "/") == 0) sprintf(path, "/%s", p_if_node->name); sprintf(path, "%s/%s", parent_path, p_if_node->name); if(cb_func) ret = cb_func(path, p_if_node, cb_data); if(ret != 0) { silc_mgmtd_err_set(MGMTD_ERR_MEMDB_TRAVERSAL_ERR, path); return ret; } silc_list_for_each_entry(p_if_sub_node, &p_if_node->sub_node_list, node) { ret = silc_mgmtd_memdb_if_node_tree_traversal(path, p_if_sub_node, cb_func, cb_data); } return ret; } silc_cstr silc_mgmtd_memdb_get_print_val_str(silc_mgmtd_var* p_var) { static char val_buf[SILC_MGMTD_VAR_VAL_STR_MAX_LEN]; silc_cstr val_str = silc_mgmtd_var_to_str(p_var, val_buf, SILC_MGMTD_VAR_VAL_STR_MAX_LEN); if(!val_str) return "unknown"; return val_str; } int silc_mgmtd_memdb_node_show_cb(const silc_cstr path, silc_mgmtd_node* p_db_node, void* cb_data) { char* type_strs[] = { "NULL", "STATIC", "TEMPLATE", "TEMPLATE_SUB", "DYNAMIC", "DYNAMIC_SUB", "MAX"}; char* val_type_strs[] = { "NULL", "UINT32", "INT32", "UINT64", "INT64", "FLOAT", "DOUBLE", "BOOL", "STRING", "MACADDR", "IPV4ADDR", "DATETIME", "DATE", "TIME", "HEX", "MAX" }; printf("%s, %s, %s, %s", path, type_strs[p_db_node->type], val_type_strs[p_db_node->value.type], val_type_strs[p_db_node->tmp_value.type]); if(strstr(path, "config") != 0) { printf(", %s", silc_mgmtd_memdb_get_print_val_str(&p_db_node->value)); printf(", %s\n", silc_mgmtd_memdb_get_print_val_str(&p_db_node->tmp_value)); } else printf("\n"); return 0; } void silc_mgmtd_memdb_node_show(silc_mgmtd_node* p_db_node) { silc_mgmtd_memdb_node_tree_traversal("", p_db_node, silc_mgmtd_memdb_node_show_cb, NULL); } int silc_mgmtd_memdb_if_node_show_cb(const silc_cstr path, silc_mgmtd_if_node* p_if_node, void* cb_data) { printf("%s, %s\n", path, p_if_node->val_str); return 0; } void silc_mgmtd_memdb_if_node_show(silc_mgmtd_if_node* p_if_node) { silc_mgmtd_memdb_if_node_tree_traversal("", p_if_node, silc_mgmtd_memdb_if_node_show_cb, NULL); } void silc_mgmtd_memdb_show_all() { silc_mgmtd_memdb_node_tree_traversal("/", &s_silc_mgmtd_memdb_root, silc_mgmtd_memdb_node_show_cb, NULL); } int silc_mgmtd_memdb_node_confirm_clean_cb(const silc_cstr path, silc_mgmtd_node* p_db_node, void* cb_data) { int ret = 0; ret = silc_mgmtd_memdb_modify_node_confirm(p_db_node); if(ret != 0) return ret; silc_mgmtd_var_clear(&p_db_node->tmp_value); return 0; } int silc_mgmtd_memdb_modify_node_confirm_tree(silc_mgmtd_node* p_node) { return silc_mgmtd_memdb_node_tree_traversal("", p_node, silc_mgmtd_memdb_node_confirm_clean_cb, NULL); }
#include <sys/types.h> #include <sys/user.h> #include <sys/wait.h> #include <unistd.h> #include <sys/syscall.h> #include <sys/ptrace.h> #include <seccomp.h> #include <errno.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include "sysnames.h" #define MMCHM_PRTACE_EVENT(status) (((status >> 8) ^ SIGTRAP) >> 8) static int on_trap(pid_t child) { unsigned long msg; struct user_regs_struct regs; void *data; if (ptrace(PTRACE_GETEVENTMSG, child, NULL, &msg) != 0) { perror("ptrace(PTRACE_GETEVENTMSG..."); return 2; } if (ptrace(PTRACE_GETREGS, child, NULL, &regs) != 0) { perror("ptrace(PTRACE_GETREGS..."); return 2; } fprintf(stderr, "%5d: syscall is: %s(#%d), arg0: %p\n", child, sysnames[(int)regs.orig_rax], (int)regs.orig_rax, (void *)regs.rdi); /* data = (void *)ptrace(PTRACE_PEEKTEXT, child, (void *)regs.rdi, NULL); */ /* fprintf(stderr, "%5d: %p\n", child, data); */ fprintf(stderr, "%5d: custom message received, %d\n", child, (int)msg); return 0; } static int on_parent(pid_t pid) { pid_t child; int status, sig; int result; if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) == -1) perror("ptrace(PTRACE_ATTACH..."); waitpid(pid, &status, 0); if (ptrace(PTRACE_SETOPTIONS, pid, NULL, (void *)PTRACE_O_TRACESECCOMP) == -1) perror("ptrace(PTRACE_SETOPTIONS..."); if (ptrace(PTRACE_CONT, pid, NULL, NULL) == -1) perror("ptrace(PTRACE_CONT..."); fprintf(stderr, "%5d: tracing start\n", pid); sleep(1); while (1) { child = waitpid(-1, &status, WUNTRACED | WCONTINUED); if (child == -1) { perror("waitpid"); return 1; } if (WIFEXITED(status)) { fprintf(stderr, "%5d: exited, status:%d\n", child, WEXITSTATUS(status)); break; } else if (WIFSIGNALED(status)) { fprintf(stderr, "%5d: signaled, sig:%d, core:%s\n", child, WTERMSIG(status), (WCOREDUMP(status)) ? "yes" : "no"); break; } else if (WIFSTOPPED(status)) { fprintf(stderr, "%5d: got status: event = %04x, signal = %04x.\n", child, MMCHM_PRTACE_EVENT(status), WSTOPSIG(status)); if (WSTOPSIG(status) == SIGTRAP && MMCHM_PRTACE_EVENT(status) == PTRACE_EVENT_SECCOMP) { // trap seccomp event result = on_trap(child); if (result) { fprintf(stderr, "%5d: hook failed.\n", child); return 1; } } else { // not trap fprintf(stderr, "%5d: stopped, sig:%d skip\n", child, WSTOPSIG(status)); sig = WSTOPSIG(status); } } else if (WIFCONTINUED(status)) { fprintf(stderr, "%5d: continued.\n", child); } else { fprintf(stderr, "%5d: illegal status %d.", child, status); return 1; } result = ptrace(PTRACE_CONT, pid, NULL, NULL); if (result == -1) { perror("ptrace(PTRACE_CONT, ...)"); return 1; } } return 0; } int on_child(void) { scmp_filter_ctx ctx; sleep(1); ctx = seccomp_init(SCMP_ACT_ALLOW); /* if (seccomp_rule_add(ctx, SCMP_ACT_KILL, SCMP_SYS(uname), 1, */ /* SCMP_A0(SCMP_CMP_GE, 0)) != 0) { */ if (seccomp_rule_add(ctx, SCMP_ACT_TRACE(2017), SCMP_SYS(uname), 0) != 0) { perror("seccomp_rule_add"); return 1; } if (seccomp_load(ctx) != 0) { perror("seccomp_load"); return 1; } execlp("uname", "uname", "-a", (char *)NULL); return 127; } int main(int argc, char **argv) { pid_t pid; int ret; pid = fork(); if (pid) { fprintf(stderr, "%5d: child started\n", pid); ret = on_parent(pid); } else { ret = on_child(); } return ret; }
/*********************************************************** * Définition des valeurs max et min de la capacité du capteur * date de creation : * Auteur : ch.duhil * ce ficher contient les constantes utililes au fonctionnement du capteur. * * Révision 1 : * ajout de la constante MAXTIME ************************************************************/ #define MAXVALUE 100 // Valeur maximum de la plage du capteur #define MINVALUE 0 // Valeur minimum de la plage du capteur #define MAXTIME 2 // Age max de la donnée
<filename>ZYKit/ZYKit/Component/ZYRequest/ZYRequest.h // // ZYRequest.h // ZYKit // // Created by 张祎 on 2021/4/16 // Copyright © 2021 objcat. All rights reserved. // #import <Foundation/Foundation.h> #import "ZYRequestBag.h" #import "ZYFileObject.h" typedef NS_ENUM(NSUInteger, ZYRequestState) { /** 刷新 */ ZYRequestStateRefresh, /** 加载 */ ZYRequestStateLoad, /** 普通请求 */ ZYRequestStateRequest, /** 搜索请求 */ ZYRequestStateSearch, }; @interface ZYRequest : NSObject /// GET /// @param URLString 地址 /// @param parameters 参数 - 直接拼接在地址栏上 /// @param response 回调 + (ZYRequestBag *)GET:(NSString *)URLString parameters:(NSDictionary *)parameters response:(void (^)(NSURLSessionDataTask *task, id responseObject, BOOL success, NSError *error))response; /// GET /// @param URLString 地址 /// @param parameters 参数 - 直接拼接在地址栏上 /// @param isJson 返回是否是json /// @param headers 请求头 /// @param response 回调 + (ZYRequestBag *)GET:(NSString *)URLString parameters:(NSDictionary *)parameters isJson:(BOOL)isJson headers:(NSDictionary *)headers response:(void (^)(NSURLSessionDataTask *task, id responseObject, BOOL success, NSError *error))response; /// POST /// @param URLString 地址 /// @param parameters 参数 - 放在body中 /// @param response 回调 + (ZYRequestBag *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters response:(void (^)(NSURLSessionDataTask *task, id responseObject, BOOL success, NSError *error))response; /// POST /// @param URLString 地址 /// @param parameters 参数 - 放在body中 /// @param isJson 返回是否是json /// @param headers 请求头 /// @param response 回调 + (ZYRequestBag *)POST:(NSString *)URLString parameters:(NSDictionary *)parameters isJson:(BOOL)isJson headers:(NSDictionary *)headers response:(void (^)(NSURLSessionDataTask *task, id responseObject, BOOL success, NSError *error))response; /// 下载 /// @param URLString 地址 /// @param filePath 保存文件路径 /// @param progress 进度 /// @param response 回调 + (ZYRequestBag *)Download:(NSString *)URLString filePath:(NSString *)filePath progress:(void (^)(NSProgress * downloadProgress))progress response:(void (^)(NSURLSessionDataTask *task, id responseObject, BOOL success, NSError *error))response; /// 上传 /// @param URLString 地址 /// @param parameters 参数 /// @param filesArray 上传 /// @param isJson 返回是否是json /// @param headers 请求头 /// @param progress 进度 /// @param response 回调 + (ZYRequestBag *)Upload:(NSString *)URLString parameters:(NSDictionary *)parameters filesArray:(NSArray *)filesArray isJson:(BOOL)isJson headers:(NSDictionary *)headers progress:(void (^)(NSProgress * uploadProgress))progress response:(void (^)(NSURLSessionDataTask *task, id responseObject, BOOL success, NSError *error))response; /// 判断成功标识 - 系统处理错误的时候会自动调用 /// @param responseObject 数据 + (BOOL)responseIsSuccess:(id)responseObject; @end
<reponame>kecho/coal #pragma once #include <coalpy.files/IFileWatcher.h> #include <string> #include <set> #include <thread> #include <functional> namespace coalpy { struct FileWatchState; class FileWatcher : public IFileWatcher { public: FileWatcher(const FileWatchDesc& desc); ~FileWatcher(); virtual void start() override; virtual void stop() override; virtual void addDirectory(const char* directory) override; virtual void addListener(IFileWatchListener* listener) override; virtual void removeListener(IFileWatchListener* listener) override; private: void onFileListening(); FileWatchDesc m_desc; FileWatchState* m_state = nullptr; }; }
/* * This file is part of libsidplayfp, a SID player engine. * * Copyright 2012-2013 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef SIDMEMORY_H #define SIDMEMORY_H #include <stdint.h> namespace libsidplayfp { /** * An interface that allows access to c64 memory * for loading tunes and apply sid specific hacks. */ class sidmemory { public: /** * Read one byte from memory. * * @param addr the memory location from which to read from */ virtual uint8_t readMemByte(uint_least16_t addr) =0; /** * Read two contiguous bytes from memory. * * @param addr the memory location from which to read from */ virtual uint_least16_t readMemWord(uint_least16_t addr) =0; /** * Write one byte to memory. * * @param addr the memory location where to write * @param value the value to write */ virtual void writeMemByte(uint_least16_t addr, uint8_t value) =0; /** * Write two contiguous bytes to memory. * * @param addr the memory location where to write * @param value the value to write */ virtual void writeMemWord(uint_least16_t addr, uint_least16_t value) =0; /** * Fill ram area with a constant value. * * @param start the start of memory location where to write * @param value the value to write * @param size the number of bytes to fill */ virtual void fillRam(uint_least16_t start, uint8_t value, unsigned int size) =0; /** * Copy a buffer into a ram area. * * @param start the start of memory location where to write * @param source the source buffer * @param size the number of bytes to copy */ virtual void fillRam(uint_least16_t start, const uint8_t* source, unsigned int size) =0; /** * Change the RESET vector. * * @param addr the new addres to point to */ virtual void installResetHook(uint_least16_t addr) =0; /** * Set BASIC Warm Start address. * * @param addr the new addres to point to */ virtual void installBasicTrap(uint_least16_t addr) =0; /** * Set the start tune. * * @param tune the tune number */ virtual void setBasicSubtune(uint8_t tune) =0; protected: ~sidmemory() {} }; } #endif
// // PLUSimpleRequest.h // plurequest // // Created by <NAME> on 16/6/26. // Copyright © 2016年 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import <PLUFoundation/PLUFoundation.h> #import "PLURequestSessionTask.h" /** * 简单原始的系统http请求 */ @interface PLUSimpleRequest : NSObject /** * POSTJSON/String方法,JSON/String放入BODY * * @param urlString 路径,不要带query * @param params json * @param header <#header description#> * @param success <#success description#> * @param failure <#failure description#> * * @return <#return value description#> */ + (id<PLURequestSessionTask>)postByUrlString: (NSString *)urlString params:(id)params requestHead:(NSDictionary *)header success:(void (^) (id responseObject))success failure:(void (^)(NSError *error))failure; /** * GET方法 * * @param urlString 路径,不要带query * @param params query参数 * @param header <#header description#> * @param success <#success description#> * @param failure <#failure description#> * * @return <#return value description#> */ + (id<PLURequestSessionTask>)getByUrlString: (NSString *)urlString params:(NSDictionary *)params requestHead:(NSDictionary *)header success:(void (^) (id responseObject))success failure:(void (^)(NSError *error))failure; @end
#ifndef __map2__H #define __map2__H #include <assert.h> #include <typeinfo> #include <map> using namespace std; //============================================================================== #define MAP2_ template<class T1,class T2> #define _MAP2 map2<T1,T2> MAP2_ class map2 { public : map2(); public : map2(const map2 &); public : T2 Add(T1,T2); public : T1 Add(T2,T1); public : void clear(); public : bool Has(T1); public : bool Has(T2); public : unsigned int size(); public : T1 & operator[](T2); public : T2 & operator[](T1); private: map <T1,T2> T1_2_T2_map; private: map <T2,T1> T2_2_T1_map; private: T1 T10; private: T2 T20; }; #include "map2.tpp" // Go get the code #undef MAP2_ #undef _MAP2 //============================================================================== #endif
<reponame>CEOALT1/RefindPlusUDK<filename>MdePkg/Library/PciSegmentLibSegmentInfo/BasePciSegmentLib.c /** @file Instance of Base PCI Segment Library that support multi-segment PCI configuration access. PCI Segment Library that consumes segment information provided by PciSegmentInfoLib to support multi-segment PCI configuration access through enhanced configuration access mechanism. Copyright (c) 2017, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php. THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include "PciSegmentLibCommon.h" /** Return the virtual address for the physical address. @param Address The physical address. @retval The virtual address. **/ UINTN PciSegmentLibVirtualAddress ( IN UINTN Address ) { return Address; } /** Register a PCI device so PCI configuration registers may be accessed after SetVirtualAddressMap(). If any reserved bits in Address are set, then ASSERT(). @param Address The address that encodes the PCI Bus, Device, Function and Register. @retval RETURN_SUCCESS The PCI device was registered for runtime access. @retval RETURN_UNSUPPORTED An attempt was made to call this function after ExitBootServices(). @retval RETURN_UNSUPPORTED The resources required to access the PCI device at runtime could not be mapped. @retval RETURN_OUT_OF_RESOURCES There are not enough resources available to complete the registration. **/ RETURN_STATUS EFIAPI PciSegmentRegisterForRuntimeAccess ( IN UINTN Address ) { // // Use PciSegmentLibGetEcamAddress() to validate the Address. // DEBUG_CODE ( UINTN Count; PCI_SEGMENT_INFO *SegmentInfo; SegmentInfo = GetPciSegmentInfo (&Count); PciSegmentLibGetEcamAddress (Address, SegmentInfo, Count); ); return RETURN_SUCCESS; }
<reponame>VictorLee1990/WSL309S_Luna<gh_stars>0 /******************************************************************************* * @file at.h * @author MCD Application Team * @version V1.1.4 * @date 08-January-2018 * @brief Header for driver at.c module ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __AT_H__ #define __AT_H__ #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include <stdint.h> /* Exported types ------------------------------------------------------------*/ /* * AT Command Id errors. Note that they are in sync with ATError_description static array * in command.c */ typedef enum eATEerror { AT_OK = 0, AT_ERROR, AT_PARAM_ERROR, AT_BUSY_ERROR, AT_TEST_PARAM_OVERFLOW, AT_NO_NET_JOINED, AT_RX_ERROR, AT_MAX, } ATEerror_t; /* Exported constants --------------------------------------------------------*/ /* External variables --------------------------------------------------------*/ /* Exported macros -----------------------------------------------------------*/ /* AT printf */ #define AT_PRINTF(...) (vcom_Send(__VA_ARGS__)) /* AT Command strings. Commands start with AT */ #define AT_RESET "Z" #define AT_DEUI "+DEUI" #define AT_DADDR "+DADDR" #define AT_APPKEY "+APPKEY" #define AT_NWKSKEY "+NWKSKEY" #define AT_APPSKEY "+APPSKEY" #define AT_APPEUI "+APPEUI" #define AT_ADR "+ADR" #define AT_TXP "+TXP" #define AT_TXO "+TXO" #define AT_DR "+DR" #define AT_DCS "+DCS" #define AT_PNM "+PNM" #define AT_RX2FQ "+RX2FQ" #define AT_RX2DR "+RX2DR" #define AT_RX1DL "+RX1DL" #define AT_RX2DL "+RX2DL" #define AT_JN1DL "+JN1DL" #define AT_JN2DL "+JN2DL" #define AT_NJM "+NJM" #define AT_NWKID "+NWKID" #define AT_FCU "+FCU" #define AT_FCD "+FCD" #define AT_CLASS "+CLASS" #define AT_JOIN "+JOIN" #define AT_NJS "+NJS" #define AT_SENDB "+SENDB" #define AT_SEND "+SEND" #define AT_RECVB "+RECVB" #define AT_RECV "+RECV" #define AT_VER "+VER" #define AT_CFM "+CFM" #define AT_CFS "+CFS" #define AT_SNR "+SNR" #define AT_RSSI "+RSSI" #define AT_BAT "+BAT" #define AT_TRSSI "+TRSSI" #define AT_TTONE "+TTONE" #define AT_TTLRA "+TTLRA" #define AT_TRLRA "+TRLRA" #define AT_TTLRC "+TTLRC" #define AT_TTLRS "+TTLRS" #define AT_TRLRC "+TRLRC" #define AT_TCONF "+TCONF" #define AT_TOFF "+TOFF" #define AT_CERTIF "+CERTIF" #define AT_TRX "+TRX" #define AT_RX1FQ "+RX1FQ" #define AT_TX1FQ "+TX1FQ" #define AT_TX2FQ "+TX2FQ" #define AT_TX3FQ "+TX3FQ" #define AT_TX4FQ "+TX4FQ" #define AT_TX5FQ "+TX5FQ" #define AT_TX6FQ "+TX6FQ" #define AT_TX7FQ "+TX7FQ" #define AT_TX8FQ "+TX8FQ" #define AT_SAVE "+SAVE" /* Exported functions ------------------------------------------------------- */ /** * @brief Store the received data * @param Application port * @param Buffer of the received data * @param Size of the received data * @retval None */ void set_at_receive(uint8_t AppPort, uint8_t* Buff, uint8_t BuffSize); /** * @brief Return AT_OK in all cases * @param Param string of the AT command - unused * @retval AT_OK */ ATEerror_t at_return_ok(const char *param); /** * @brief Return AT_ERROR in all cases * @param Param string of the AT command - unused * @retval AT_ERROR */ ATEerror_t at_return_error(const char *param); /** * @brief Trig a reset of the MCU * @param Param string of the AT command - unused * @retval AT_OK */ ATEerror_t at_reset(const char *param); /** * @brief Print Device EUI * @param Param string of the AT command - unused * @retval AT_OK */ ATEerror_t at_DevEUI_get(const char *param); ATEerror_t at_DevEUI_set(const char *param); /** * @brief Print Application EUI * @param Param string of the AT command * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_AppEUI_get(const char *param); /** * @brief Set Application EUI * @param Param string of the AT command * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_AppEUI_set(const char *param); /** * @brief Set DevAddr * @param String pointing to provided DevAddr * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_DevAddr_set(const char *param); /** * @brief Print the DevAddr * @param String pointing to provided DevAddr * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_DevAddr_get(const char *param); /** * @brief Print Application Key * @param Param string of the AT command * @retval AT_OK */ ATEerror_t at_AppKey_get(const char *param); /** * @brief Set Application Key * @param Param string of the AT command * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_AppKey_set(const char *param); /** * @brief Print Network Session Key * @param String pointing to provided DevAddr * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_NwkSKey_get(const char *param); /** * @brief Set Network Session Key * @param String pointing to provided DevAddr * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_NwkSKey_set(const char *param); /** * @brief Print Application Session Key * @param String pointing to provided DevAddr * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_AppSKey_get(const char *param); /** * @brief Set Application Session Key * @param String pointing to provided DevAddr * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_AppSKey_set(const char *param); /** * @brief Print Adaptative Data Rate setting * @param String pointing to provided ADR setting * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_ADR_get(const char *param); /** * @brief Set Adaptative Data Rate setting * @param String pointing to provided ADR setting * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_ADR_set(const char *param); /** * @brief Print Transmit Power * @param String pointing to provided power * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_TransmitPower_get(const char *param); /** * @brief Set Transmit Power * @param String pointing to provided power * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_TransmitPower_set(const char *param); /** * @brief Print Data Rate * @param String pointing to provided rate * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_DataRate_get(const char *param); /** * @brief Set Data Rate * @param String pointing to provided rate * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_DataRate_set(const char *param); /** * @brief Set ETSI Duty Cycle parameter * @param String pointing to provided Duty Cycle value * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_DutyCycle_set(const char *param); /** * @brief Get ETSI Duty Cycle parameter * @param 0 if disable, 1 if enable * @retval AT_OK */ ATEerror_t at_DutyCycle_get(const char *param); /** * @brief Print Public Network setting * @param String pointing to provided Network setting * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_PublicNetwork_get(const char *param); /** * @brief Set Public Network setting * @param String pointing to provided Network setting * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_PublicNetwork_set(const char *param); /** * @brief Print Rx1 window frequency * @param String pointing to parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Rx1Frequency_get(const char *param); /** * @brief Set Rx1 window frequency * @param String pointing to parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Rx1Frequency_set(const char *param); /** * @brief Print Rx2 window frequency * @param String pointing to parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Rx2Frequency_get(const char *param); /** * @brief Set Rx2 window frequency * @param String pointing to parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Rx2Frequency_set(const char *param); /** * @brief Print Rx2 window data rate * @param String pointing to parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Rx2DataRate_get(const char *param); /** * @brief Set Rx2 window data rate * @param String pointing to parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Rx2DataRate_set(const char *param); /** * @brief Print the delay between the end of the Tx and the Rx Window 1 * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Rx1Delay_get(const char *param); /** * @brief Set the delay between the end of the Tx and the Rx Window 1 * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Rx1Delay_set(const char *param); /** * @brief Print the delay between the end of the Tx and the Rx Window 2 * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Rx2Delay_get(const char *param); /** * @brief Set the delay between the end of the Tx and the Rx Window 2 * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Rx2Delay_set(const char *param); /** * @brief Print the delay between the end of the Tx and the Join Rx Window 1 * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_JoinAcceptDelay1_get(const char *param); /** * @brief Set the delay between the end of the Tx and the Join Rx Window 1 * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_JoinAcceptDelay1_set(const char *param); /** * @brief Print the delay between the end of the Tx and the Join Rx Window 2 * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_JoinAcceptDelay2_get(const char *param); /** * @brief Set the delay between the end of the Tx and the Join Rx Window 2 * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_JoinAcceptDelay2_set(const char *param); /** * @brief Print network join mode * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_NetworkJoinMode_get(const char *param); /** * @brief Set network join mode * @param String pointing to provided param: "1" for OTAA, "0" for ABP * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_NetworkJoinMode_set(const char *param); /** * @brief Print the Network ID * @param String pointing to provided parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_NetworkID_get(const char *param); /** * @brief Set the Network ID * @param String pointing to provided parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_NetworkID_set(const char *param); /** * @brief Print the Uplink Counter * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_UplinkCounter_get(const char *param); /** * @brief Set the Uplink Counter * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_UplinkCounter_set(const char *param); /** * @brief Print the Downlink Counter * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_DownlinkCounter_get(const char *param); /** * @brief Set the Downlink Counter * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_DownlinkCounter_set(const char *param); /** * @brief Print the Device Class * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_DeviceClass_get(const char *param); /** * @brief Set the Device Class * @param String pointing to provided param * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_DeviceClass_set(const char *param); /** * @brief Join a network * @param String parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Join(const char *param); /** * @brief Print the join status * @param String parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_NetworkJoinStatus(const char *param); /** * @brief Send a message * @param String parameter of hexadecimal value * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_SendBinary(const char *param); /** * @brief Print last received message * @param String parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Send(const char *param); /** * @brief Print last received data in binary format with hexadecimal value * @param String parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_ReceiveBinary(const char *param); /** * @brief Print last received data * @param String parameter * @retval AT_OK if OK, or an appropriate AT_xxx error code */ ATEerror_t at_Receive(const char *param); /** * @brief Print the version of the AT_Slave FW * @param String parameter * @retval AT_OK */ ATEerror_t at_version_get(const char *param); /** * @brief Set if message acknowledgment is required (1) or not (0) * @param String parameter * @retval AT_OK */ ATEerror_t at_ack_set(const char *param); /** * @brief Get if message acknowledgment is required (1) or not (0) * @param String parameter * @retval AT_OK */ ATEerror_t at_ack_get(const char *param); /** * @brief Get if the last message has been acknowledged or not * @param String parameter * @retval AT_OK */ ATEerror_t at_isack_get(const char *param); /** * @brief Get the SNR * @param String parameter * @retval AT_OK */ ATEerror_t at_snr_get(const char *param); /** * @brief Get the RSSI * @param String parameter * @retval AT_OK */ ATEerror_t at_rssi_get(const char *param); /** * @brief Get the battery level * @param String parameter * @retval AT_OK */ ATEerror_t at_bat_get(const char *param); /** * @brief Sart Tx test * @param String parameter * @retval AT_OK */ ATEerror_t at_test_txTone(const char *param); /** * @brief Sart Rx tone * @param String parameter * @retval AT_OK */ ATEerror_t at_test_rxTone(const char *param); /** * @brief stop Rx or Tx test * @param String parameter * @retval AT_OK */ ATEerror_t at_test_stop(const char *param); /** * @brief Start Tx LoRa test * @param String parameter * @retval AT_OK */ ATEerror_t at_test_txlora(const char *param); /** * @brief Start Rx LoRa test * @param String parameter * @retval AT_OK */ ATEerror_t at_test_rxlora(const char *param); /** * @brief Start Tx LoRa test * @param String parameter * @retval AT_OK */ ATEerror_t at_test_txclora(const char *param); ATEerror_t at_test_txslora(const char *param); /** * @brief Start Rx LoRa test * @param String parameter * @retval AT_OK */ ATEerror_t at_test_rxclora(const char *param); /** * @brief Set Rx or Tx test config * @param String parameter * @retval AT_OK */ ATEerror_t at_test_set_lora_config(const char *param); /** * @brief Get Rx or Tx test config * @param String parameter * @retval AT_OK */ ATEerror_t at_test_get_lora_config(const char *param); /** * @brief set the Modem in Certif Mode * @param String parameter * @retval AT_OK */ ATEerror_t at_Certif( const char *param ); ATEerror_t at_TRX_get( const char *param ); ATEerror_t at_TRX_set( const char *param ); ATEerror_t at_Tx1Frequency_get(const char *param); ATEerror_t at_Tx1Frequency_set(const char *param); ATEerror_t at_Tx2Frequency_get(const char *param); ATEerror_t at_Tx2Frequency_set(const char *param); ATEerror_t at_Tx3Frequency_get(const char *param); ATEerror_t at_Tx3Frequency_set(const char *param); ATEerror_t at_Tx4Frequency_get(const char *param); ATEerror_t at_Tx4Frequency_set(const char *param); ATEerror_t at_Tx5Frequency_get(const char *param); ATEerror_t at_Tx5Frequency_set(const char *param); ATEerror_t at_Tx6Frequency_get(const char *param); ATEerror_t at_Tx6Frequency_set(const char *param); ATEerror_t at_Tx7Frequency_get(const char *param); ATEerror_t at_Tx7Frequency_set(const char *param); ATEerror_t at_Tx8Frequency_get(const char *param); ATEerror_t at_Tx8Frequency_set(const char *param); ATEerror_t at_OutputPower_get(const char *param); ATEerror_t at_OutputPower_set(const char *param); ATEerror_t at_Save(const char *param); #ifdef __cplusplus } #endif #endif /* __AT_H__ */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<reponame>joseph-hellerstein/RuleBasedProgramming<filename>BioNetGen-2.3.0/source_NFsim/validate/BioNetGen-2.2.6-stable/Network3/src/util/mathutils/cadd.c #include "mathutils.h" /*==========================================================================*/ dcomplex Cadd(dcomplex a, dcomplex b) { dcomplex c; c.r = a.r+b.r; c.i = a.i+b.i; return(c); }
<reponame>fmidev/smartmet-plugin-wms #pragma once #include "WMSConfig.h" #include "WMSGetCapabilities.h" #include <ctpp2/CDT.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <spine/HTTP.h> #include <spine/Value.h> namespace SmartMet { namespace Plugin { namespace WMS { // struct for map info struct tag_map_info { std::string name; // name std::string style; tag_map_info(const std::string& n, const std::string& s) : name(n), style(s) {} }; struct tag_get_map_request_options { std::vector<tag_map_info> map_info_vector; Spine::BoundingBox bbox; // contains crs std::string format; std::string version; // optional bool transparent; struct tab_bgcolor { unsigned int red; unsigned int green; unsigned int blue; } bgcolor; std::string exceptions; boost::optional<boost::posix_time::ptime> reference_time; std::vector<boost::posix_time::ptime> timesteps; boost::optional<int> elevation; unsigned int width; unsigned int height; bool debug; }; class WMSGetMap { public: WMSGetMap(const WMSConfig& theConfig); void parseHTTPRequest(const Engine::Querydata::Engine& theQEngine, Spine::HTTP::Request& theRequest); Json::Value json() const; private: tag_get_map_request_options itsParameters; const WMSConfig& itsConfig; }; } // namespace WMS } // namespace Plugin } // namespace SmartMet
<reponame>se77en/LibCoroC // Copyright 2016 <NAME> (<EMAIL>). All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.txt file. /* Copyright (c) 2005 <NAME>, MIT; see COPYRIGHT */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "libcoroc.h" int quiet = 0; int goal = 100; int buffer = 0; int primetask(void *arg) { coroc_chan_t c, nc; unsigned long p, i; c = arg; coroc_chan_recv(c, &p); if (p > goal) exit(0); if (!quiet) printf("%d\n", p); nc = coroc_chan_allocate(sizeof(unsigned long), buffer); coroc_coroutine_allocate(primetask, nc, "", TSC_COROUTINE_NORMAL, TSC_DEFAULT_PRIO, NULL); for (;;) { coroc_chan_recv(c, &i); if (i % p) coroc_chan_send(nc, &i); } return 0; } void main(int argc, char **argv) { unsigned long i; coroc_chan_t c; printf("goal=%d\n", goal); c = coroc_chan_allocate(sizeof(unsigned long), buffer); coroc_coroutine_allocate(primetask, c, "", TSC_COROUTINE_NORMAL, TSC_DEFAULT_PRIO, NULL); for (i = 2;; i++) coroc_chan_send(c, &i); }
<reponame>funbiscuit/embedded-cli #include <stdlib.h> #include <string.h> #include "embedded_cli.h" #define PREPARE_IMPL(t) \ EmbeddedCliImpl* impl = (EmbeddedCliImpl*)t->_impl; #define IS_FLAG_SET(flags, flag) (((flags) & (flag)) != 0) #define SET_FLAG(flags, flag) ((flags) |= (flag)) #define UNSET_FLAG(flags, flag) ((flags) &= ~(flag)) /** * Marks binding as candidate for autocompletion * This flag is updated each time getAutocompletedCommand is called */ #define BINDING_FLAG_AUTOCOMPLETE 1u /** * Indicates that rx buffer overflow happened. In such case last command * that wasn't finished (no \r or \n were received) will be discarded */ #define CLI_FLAG_OVERFLOW 0x01u /** * Indicates that initialization is completed. Initialization is completed in * first call to process and needed, for example, to print invitation message. */ #define CLI_FLAG_INIT_COMPLETE 0x02u /** * Indicates that CLI structure and internal structures were allocated with * malloc and should bre freed */ #define CLI_FLAG_ALLOCATED 0x04u /** * Indicates that CLI structure and internal structures were allocated with * malloc and should bre freed */ #define CLI_FLAG_ESCAPE_MODE 0x08u /** * Indicates that CLI in mode when it will print directly to output without * clear of current command and printing it back */ #define CLI_FLAG_DIRECT_PRINT 0x10u typedef struct EmbeddedCliImpl EmbeddedCliImpl; typedef struct AutocompletedCommand AutocompletedCommand; typedef struct FifoBuf FifoBuf; typedef struct CliHistory CliHistory; struct FifoBuf { char *buf; /** * Position of first element in buffer. From this position elements are taken */ uint16_t front; /** * Position after last element. At this position new elements are inserted */ uint16_t back; /** * Size of buffer */ uint16_t size; }; struct CliHistory { /** * Items in buffer are separated by null-chars */ char *buf; /** * Total size of buffer */ uint16_t bufferSize; /** * Index of currently selected element. This allows to navigate history * After command is sent, current element is reset to 0 (no element) */ uint16_t current; /** * Number of items in buffer * Items are counted from top to bottom (and are 1 based). * So the most recent item is 1 and the oldest is itemCount. */ uint16_t itemsCount; }; struct EmbeddedCliImpl { /** * Invitation string. Is printed at the beginning of each line with user * input */ const char *invitation; CliHistory history; /** * Buffer for storing received chars. * Chars are stored in FIFO mode. */ FifoBuf rxBuffer; /** * Buffer for current command */ char *cmdBuffer; /** * Size of current command */ uint16_t cmdSize; /** * Total size of command buffer */ uint16_t cmdMaxSize; CliCommandBinding *bindings; /** * Flags for each binding. Sizes are the same as for bindings array */ uint8_t *bindingsFlags; uint16_t bindingsCount; uint16_t maxBindingsCount; /** * Stores last character that was processed. */ char lastChar; /** * Total length of input line. This doesn't include invitation but * includes current command and its live autocompletion */ uint16_t inputLineLength; /** * Flags are defined as CLI_FLAG_* */ uint8_t flags; }; struct AutocompletedCommand { /** * Name of autocompleted command (or first candidate for autocompletion if * there are multiple candidates). * NULL if autocomplete not possible. */ const char *firstCandidate; /** * Number of characters that can be completed safely. For example, if there * are two possible commands "get-led" and "get-adc", then for prefix "g" * autocompletedLen will be 4. If there are only one candidate, this number * is always equal to length of the command. */ size_t autocompletedLen; /** * Total number of candidates for autocompletion */ uint16_t candidateCount; }; static EmbeddedCliConfig defaultConfig; /** * Number of commands that cli adds. Commands: * - help */ static const uint16_t cliInternalBindingCount = 1; static const char *lineBreak = "\r\n"; /** * Navigate through command history back and forth. If navigateUp is true, * navigate to older commands, otherwise navigate to newer. * When history end is reached, nothing happens. * @param cli * @param navigateUp */ static void navigateHistory(EmbeddedCli *cli, bool navigateUp); /** * Process escaped character. After receiving ESC+[ sequence, all chars up to * ending character are sent to this function * @param cli * @param c */ static void onEscapedInput(EmbeddedCli *cli, char c); /** * Process input character. Character is valid displayable char and should be * added to current command string and displayed to client. * @param cli * @param c */ static void onCharInput(EmbeddedCli *cli, char c); /** * Process control character (like \r or \n) possibly altering state of current * command or executing onCommand callback. * @param cli * @param c */ static void onControlInput(EmbeddedCli *cli, char c); /** * Parse command in buffer and execute callback * @param cli */ static void parseCommand(EmbeddedCli *cli); /** * Setup bindings for internal commands, like help * @param cli */ static void initInternalBindings(EmbeddedCli *cli); /** * Show help for given tokens (or default help if no tokens) * @param cli * @param tokens * @param context - not used */ static void onHelp(EmbeddedCli *cli, char *tokens, void *context); /** * Show error about unknown command * @param cli * @param name */ static void onUnknownCommand(EmbeddedCli *cli, const char *name); /** * Return autocompleted command for given prefix. * Prefix is compared to all known command bindings and autocompleted result * is returned * @param cli * @param prefix * @return */ static AutocompletedCommand getAutocompletedCommand(EmbeddedCli *cli, const char *prefix); /** * Prints autocompletion result while keeping current command unchanged * Prints only if autocompletion is present and only one candidate exists. * @param cli */ static void printLiveAutocompletion(EmbeddedCli *cli); /** * Handles autocomplete request. If autocomplete possible - fills current * command with autocompleted command. When multiple commands satisfy entered * prefix, they are printed to output. * @param cli */ static void onAutocompleteRequest(EmbeddedCli *cli); /** * Removes all input from current line (replaces it with whitespaces) * And places cursor at the beginning of the line * @param cli */ static void clearCurrentLine(EmbeddedCli *cli); /** * Write given string to cli output * @param cli * @param str */ static void writeToOutput(EmbeddedCli *cli, const char *str); /** * Returns true if provided char is a supported control char: * \r, \n, \b or 0x7F (treated as \b) * @param c * @return */ static bool isControlChar(char c); /** * Returns true if provided char is a valid displayable character: * a-z, A-Z, 0-9, whitespace, punctuation, etc. * Currently only ASCII is supported * @param c * @return */ static bool isDisplayableChar(char c); /** * How many elements are currently available in buffer * @param buffer * @return number of elements */ static uint16_t fifoBufAvailable(FifoBuf *buffer); /** * Return first character from buffer and remove it from buffer * Buffer must be non-empty, otherwise 0 is returned * @param buffer * @return */ static char fifoBufPop(FifoBuf *buffer); /** * Push character into fifo buffer. If there is no space left, character is * discarded and false is returned * @param buffer * @param a - character to add * @return true if char was added to buffer, false otherwise */ static bool fifoBufPush(FifoBuf *buffer, char a); /** * Copy provided string to the history buffer. * If it is already inside history, it will be removed from it and added again. * So after addition, it will always be on top * If available size is not enough (and total size is enough) old elements will * be removed from history so this item can be put to it * @param history * @param str * @return true if string was put in history */ static bool historyPut(CliHistory *history, const char *str); /** * Get item from history. Items are counted from 1 so if item is 0 or greater * than itemCount, NULL is returned * @param history * @param item * @return true if string was put in history */ static const char *historyGet(CliHistory *history, uint16_t item); /** * Remove specific item from history * @param history * @param str - string to remove * @return */ static void historyRemove(CliHistory *history, const char *str); EmbeddedCliConfig *embeddedCliDefaultConfig(void) { defaultConfig.rxBufferSize = 64; defaultConfig.cmdBufferSize = 64; defaultConfig.historyBufferSize = 128; defaultConfig.cliBuffer = NULL; defaultConfig.cliBufferSize = 0; defaultConfig.maxBindingCount = 8; return &defaultConfig; } uint16_t embeddedCliRequiredSize(EmbeddedCliConfig *config) { uint16_t bindingCount = config->maxBindingCount + cliInternalBindingCount; return sizeof(EmbeddedCli) + sizeof(EmbeddedCliImpl) + config->rxBufferSize * sizeof(char) + config->cmdBufferSize * sizeof(char) + config->historyBufferSize * sizeof(char) + bindingCount * sizeof(CliCommandBinding) + bindingCount * sizeof(uint8_t); } EmbeddedCli *embeddedCliNew(EmbeddedCliConfig *config) { EmbeddedCli *cli = NULL; uint16_t bindingCount = config->maxBindingCount + cliInternalBindingCount; size_t totalSize = embeddedCliRequiredSize(config); bool allocated = false; if (config->cliBuffer == NULL) { config->cliBuffer = malloc(totalSize); if (config->cliBuffer == NULL) return NULL; allocated = true; } else if (config->cliBufferSize < totalSize) { return NULL; } uint8_t *buf = config->cliBuffer; memset(buf, 0, totalSize); cli = (EmbeddedCli *) buf; buf = &buf[sizeof(EmbeddedCli)]; cli->_impl = (EmbeddedCliImpl *) buf; buf = &buf[sizeof(EmbeddedCliImpl)]; PREPARE_IMPL(cli) impl->rxBuffer.buf = (char *) buf; buf = &buf[config->rxBufferSize * sizeof(char)]; impl->cmdBuffer = (char *) buf; buf = &buf[config->cmdBufferSize * sizeof(char)]; impl->bindings = (CliCommandBinding *) buf; buf = &buf[bindingCount * sizeof(CliCommandBinding)]; impl->bindingsFlags = buf; buf = &buf[bindingCount]; impl->history.buf = (char *) buf; impl->history.bufferSize = config->historyBufferSize; if (allocated) SET_FLAG(impl->flags, CLI_FLAG_ALLOCATED); impl->rxBuffer.size = config->rxBufferSize; impl->rxBuffer.front = 0; impl->rxBuffer.back = 0; impl->cmdMaxSize = config->cmdBufferSize; impl->bindingsCount = 0; impl->maxBindingsCount = config->maxBindingCount + cliInternalBindingCount; impl->lastChar = '\0'; impl->invitation = "> "; initInternalBindings(cli); return cli; } EmbeddedCli *embeddedCliNewDefault(void) { return embeddedCliNew(embeddedCliDefaultConfig()); } void embeddedCliReceiveChar(EmbeddedCli *cli, char c) { PREPARE_IMPL(cli) if (!fifoBufPush(&impl->rxBuffer, c)) { SET_FLAG(impl->flags, CLI_FLAG_OVERFLOW); } } void embeddedCliProcess(EmbeddedCli *cli) { if (cli->writeChar == NULL) return; PREPARE_IMPL(cli) if (!IS_FLAG_SET(impl->flags, CLI_FLAG_INIT_COMPLETE)) { SET_FLAG(impl->flags, CLI_FLAG_INIT_COMPLETE); writeToOutput(cli, impl->invitation); } while (fifoBufAvailable(&impl->rxBuffer)) { char c = fifoBufPop(&impl->rxBuffer); if (IS_FLAG_SET(impl->flags, CLI_FLAG_ESCAPE_MODE)) { onEscapedInput(cli, c); } else if (impl->lastChar == 0x1B && c == '[') { //enter escape mode SET_FLAG(impl->flags, CLI_FLAG_ESCAPE_MODE); } else if (isControlChar(c)) { onControlInput(cli, c); } else if (isDisplayableChar(c)) { onCharInput(cli, c); } printLiveAutocompletion(cli); impl->lastChar = c; } // discard unfinished command if overflow happened if (IS_FLAG_SET(impl->flags, CLI_FLAG_OVERFLOW)) { impl->cmdSize = 0; impl->cmdBuffer[impl->cmdSize] = '\0'; UNSET_FLAG(impl->flags, CLI_FLAG_OVERFLOW); } } bool embeddedCliAddBinding(EmbeddedCli *cli, CliCommandBinding binding) { PREPARE_IMPL(cli) if (impl->bindingsCount == impl->maxBindingsCount) return false; impl->bindings[impl->bindingsCount] = binding; ++impl->bindingsCount; return true; } void embeddedCliPrint(EmbeddedCli *cli, const char *string) { if (cli->writeChar == NULL) return; PREPARE_IMPL(cli) // remove chars for autocompletion and live command if (!IS_FLAG_SET(impl->flags, CLI_FLAG_DIRECT_PRINT)) clearCurrentLine(cli); // print provided string writeToOutput(cli, string); writeToOutput(cli, lineBreak); // print current command back to screen if (!IS_FLAG_SET(impl->flags, CLI_FLAG_DIRECT_PRINT)) { writeToOutput(cli, impl->invitation); writeToOutput(cli, impl->cmdBuffer); impl->inputLineLength = impl->cmdSize; printLiveAutocompletion(cli); } } void embeddedCliFree(EmbeddedCli *cli) { PREPARE_IMPL(cli) if (IS_FLAG_SET(impl->flags, CLI_FLAG_ALLOCATED)) { // allocation is done in single call to malloc, so need only single free free(cli); } } void embeddedCliTokenizeArgs(char *args) { if (args == NULL) return; // for now only space, but can add more later const char *separators = " "; size_t len = strlen(args); // place extra null char to indicate end of tokens args[len + 1] = '\0'; if (len == 0) return; // replace all separators with \0 char for (int i = 0; i < len; ++i) { if (strchr(separators, args[i]) != NULL) { args[i] = '\0'; } } // compress all sequential null-chars to single ones, starting from end size_t nextTokenStartIndex = 0; size_t i = len; while (i > 0) { --i; bool isSeparator = strchr(separators, args[i]) != NULL; if (!isSeparator && args[i + 1] == '\0') { // found end of token, move tokens on the right side of this one if (nextTokenStartIndex != 0 && nextTokenStartIndex - i > 2) { // will copy all tokens to the right and two null-chars memmove(&args[i + 2], &args[nextTokenStartIndex], len - nextTokenStartIndex + 1); } } else if (isSeparator && args[i + 1] != '\0') { nextTokenStartIndex = i + 1; } } // remove null chars from the beginning if (args[0] == '\0' && nextTokenStartIndex > 0) { memmove(args, &args[nextTokenStartIndex], len - nextTokenStartIndex + 1); } } const char *embeddedCliGetToken(const char *tokenizedStr, uint8_t pos) { if (tokenizedStr == NULL || pos == 0) return NULL; int i = 0; int tokenCount = 1; while (true) { if (tokenCount == pos) break; if (tokenizedStr[i] == '\0') { ++tokenCount; if (tokenizedStr[i + 1] == '\0') break; } ++i; } if (tokenizedStr[i] != '\0') return &tokenizedStr[i]; else return NULL; } uint8_t embeddedCliFindToken(const char *tokenizedStr, const char *token) { if (tokenizedStr == NULL || token == NULL) return 0; uint8_t size = embeddedCliGetTokenCount(tokenizedStr); for (int i = 0; i < size; ++i) { if (strcmp(embeddedCliGetToken(tokenizedStr, i + 1), token) == 0) return i + 1; } return 0; } uint8_t embeddedCliGetTokenCount(const char *tokenizedStr) { if (tokenizedStr == NULL || tokenizedStr[0] == '\0') return 0; int i = 0; int tokenCount = 1; while (true) { if (tokenizedStr[i] == '\0') { if (tokenizedStr[i + 1] == '\0') break; ++tokenCount; } ++i; } return tokenCount; } static void navigateHistory(EmbeddedCli *cli, bool navigateUp) { PREPARE_IMPL(cli) if (impl->history.itemsCount == 0 || (navigateUp && impl->history.current == impl->history.itemsCount) || (!navigateUp && impl->history.current == 0)) return; clearCurrentLine(cli); writeToOutput(cli, impl->invitation); if (navigateUp) ++impl->history.current; else --impl->history.current; const char *item = historyGet(&impl->history, impl->history.current); // simple way to handle empty command the same way as others if (item == NULL) item = ""; size_t len = strlen(item); memcpy(impl->cmdBuffer, item, len); impl->cmdBuffer[len] = '\0'; impl->cmdSize = len; writeToOutput(cli, impl->cmdBuffer); impl->inputLineLength = impl->cmdSize; printLiveAutocompletion(cli); } static void onEscapedInput(EmbeddedCli *cli, char c) { PREPARE_IMPL(cli) if (c >= 64 && c <= 126) { // handle escape sequence UNSET_FLAG(impl->flags, CLI_FLAG_ESCAPE_MODE); if (c == 'A' || c == 'B') { // treat \e[..A as cursor up and \e[..B as cursor down // there might be extra chars between [ and A/B, just ignore them navigateHistory(cli, c == 'A'); } } } static void onCharInput(EmbeddedCli *cli, char c) { PREPARE_IMPL(cli) // have to reserve two extra chars for command ending (used in tokenization) if (impl->cmdSize + 2 >= impl->cmdMaxSize) return; impl->cmdBuffer[impl->cmdSize] = c; ++impl->cmdSize; impl->cmdBuffer[impl->cmdSize] = '\0'; cli->writeChar(cli, c); } static void onControlInput(EmbeddedCli *cli, char c) { PREPARE_IMPL(cli) // process \r\n and \n\r as single \r\n command if ((impl->lastChar == '\r' && c == '\n') || (impl->lastChar == '\n' && c == '\r')) return; if (c == '\r' || c == '\n') { // try to autocomplete command and then process it onAutocompleteRequest(cli); writeToOutput(cli, lineBreak); if (impl->cmdSize > 0) parseCommand(cli); impl->cmdSize = 0; impl->cmdBuffer[impl->cmdSize] = '\0'; impl->inputLineLength = 0; impl->history.current = 0; writeToOutput(cli, impl->invitation); } else if ((c == '\b' || c == 0x7F) && impl->cmdSize > 0) { // remove char from screen cli->writeChar(cli, '\b'); cli->writeChar(cli, ' '); cli->writeChar(cli, '\b'); // and from buffer --impl->cmdSize; impl->cmdBuffer[impl->cmdSize] = '\0'; } else if (c == '\t') { onAutocompleteRequest(cli); } } static void parseCommand(EmbeddedCli *cli) { PREPARE_IMPL(cli) bool isEmpty = true; for (int i = 0; i < impl->cmdSize; ++i) { if (impl->cmdBuffer[i] != ' ') { isEmpty = false; break; } } // do not process empty commands if (isEmpty) return; // push command to history before buffer is modified historyPut(&impl->history, impl->cmdBuffer); char *cmdName = NULL; char *cmdArgs = NULL; bool nameFinished = false; // find command name and command args inside command buffer for (int i = 0; i < impl->cmdSize; ++i) { char c = impl->cmdBuffer[i]; if (c == ' ') { // all spaces between name and args are filled with zeros // so name is a correct null-terminated string if (cmdArgs == NULL) impl->cmdBuffer[i] = '\0'; if (cmdName != NULL) nameFinished = true; } else if (cmdName == NULL) { cmdName = &impl->cmdBuffer[i]; } else if (cmdArgs == NULL && nameFinished) { cmdArgs = &impl->cmdBuffer[i]; } } // we keep two last bytes in cmd buffer reserved so cmdSize is always by 2 // less than cmdMaxSize impl->cmdBuffer[impl->cmdSize + 1] = '\0'; if (cmdName == NULL) return; // try to find command in bindings for (int i = 0; i < impl->bindingsCount; ++i) { if (strcmp(cmdName, impl->bindings[i].name) == 0) { if (impl->bindings[i].binding == NULL) break; if (impl->bindings[i].tokenizeArgs) embeddedCliTokenizeArgs(cmdArgs); // currently, output is blank line, so we can just print directly SET_FLAG(impl->flags, CLI_FLAG_DIRECT_PRINT); impl->bindings[i].binding(cli, cmdArgs, impl->bindings[i].context); UNSET_FLAG(impl->flags, CLI_FLAG_DIRECT_PRINT); return; } } // command not found in bindings or binding was null // try to call default callback if (cli->onCommand != NULL) { CliCommand command; command.name = cmdName; command.args = cmdArgs; // currently, output is blank line, so we can just print directly SET_FLAG(impl->flags, CLI_FLAG_DIRECT_PRINT); cli->onCommand(cli, &command); UNSET_FLAG(impl->flags, CLI_FLAG_DIRECT_PRINT); } else { onUnknownCommand(cli, cmdName); } } static void initInternalBindings(EmbeddedCli *cli) { PREPARE_IMPL(cli) CliCommandBinding b = { "help", "Print list of commands", true, NULL, onHelp }; embeddedCliAddBinding(cli, b); } static void onHelp(EmbeddedCli *cli, char *tokens, void *context) { PREPARE_IMPL(cli) if (impl->bindingsCount == 0) { writeToOutput(cli, "Help is not available"); writeToOutput(cli, lineBreak); return; } uint8_t tokenCount = embeddedCliGetTokenCount(tokens); if (tokenCount == 0) { for (int i = 0; i < impl->bindingsCount; ++i) { writeToOutput(cli, " * "); writeToOutput(cli, impl->bindings[i].name); writeToOutput(cli, lineBreak); if (impl->bindings[i].help != NULL) { cli->writeChar(cli, '\t'); writeToOutput(cli, impl->bindings[i].help); writeToOutput(cli, lineBreak); } } } else if (tokenCount == 1) { // try find command const char *helpStr = NULL; const char *cmdName = embeddedCliGetToken(tokens, 1); bool found = false; for (int i = 0; i < impl->bindingsCount; ++i) { if (strcmp(impl->bindings[i].name, cmdName) == 0) { helpStr = impl->bindings[i].help; found = true; break; } } if (found && helpStr != NULL) { writeToOutput(cli, " * "); writeToOutput(cli, cmdName); writeToOutput(cli, lineBreak); cli->writeChar(cli, '\t'); writeToOutput(cli, helpStr); writeToOutput(cli, lineBreak); } else if (found) { writeToOutput(cli, "Help is not available"); writeToOutput(cli, lineBreak); } else { onUnknownCommand(cli, cmdName); } } else { writeToOutput(cli, "Command \"help\" receives one or zero arguments"); writeToOutput(cli, lineBreak); } } static void onUnknownCommand(EmbeddedCli *cli, const char *name) { writeToOutput(cli, "Unknown command: \""); writeToOutput(cli, name); writeToOutput(cli, "\". Write \"help\" for a list of available commands"); writeToOutput(cli, lineBreak); } static AutocompletedCommand getAutocompletedCommand(EmbeddedCli *cli, const char *prefix) { AutocompletedCommand cmd = {NULL, 0, 0}; size_t prefixLen = strlen(prefix); PREPARE_IMPL(cli) if (impl->bindingsCount == 0 || prefixLen == 0) return cmd; for (int i = 0; i < impl->bindingsCount; ++i) { const char *name = impl->bindings[i].name; size_t len = strlen(name); // unset autocomplete flag impl->bindingsFlags[i] &= ~BINDING_FLAG_AUTOCOMPLETE; if (len < prefixLen) continue; // check if this command is candidate for autocomplete bool isCandidate = true; for (int j = 0; j < prefixLen; ++j) { if (prefix[j] != name[j]) { isCandidate = false; break; } } if (!isCandidate) continue; impl->bindingsFlags[i] |= BINDING_FLAG_AUTOCOMPLETE; if (cmd.candidateCount == 0 || len < cmd.autocompletedLen) cmd.autocompletedLen = len; ++cmd.candidateCount; if (cmd.candidateCount == 1) { cmd.firstCandidate = name; continue; } for (int j = impl->cmdSize; j < cmd.autocompletedLen; ++j) { if (cmd.firstCandidate[j] != name[j]) { cmd.autocompletedLen = j; break; } } } return cmd; } static void printLiveAutocompletion(EmbeddedCli *cli) { PREPARE_IMPL(cli) AutocompletedCommand cmd = getAutocompletedCommand(cli, impl->cmdBuffer); if (cmd.candidateCount == 0) { cmd.autocompletedLen = impl->cmdSize; } // print live autocompletion (or nothing, if it doesn't exist) for (int i = impl->cmdSize; i < cmd.autocompletedLen; ++i) { cli->writeChar(cli, cmd.firstCandidate[i]); } // replace with spaces previous autocompletion for (int i = cmd.autocompletedLen; i < impl->inputLineLength; ++i) { cli->writeChar(cli, ' '); } impl->inputLineLength = cmd.autocompletedLen; cli->writeChar(cli, '\r'); // print current command again so cursor is moved to initial place writeToOutput(cli, impl->invitation); writeToOutput(cli, impl->cmdBuffer); } static void onAutocompleteRequest(EmbeddedCli *cli) { PREPARE_IMPL(cli) AutocompletedCommand cmd = getAutocompletedCommand(cli, impl->cmdBuffer); if (cmd.candidateCount == 0) return; if (cmd.candidateCount == 1 || cmd.autocompletedLen > impl->cmdSize) { // can copy from index cmdSize, but prefix is the same, so copy everything memcpy(impl->cmdBuffer, cmd.firstCandidate, cmd.autocompletedLen); if (cmd.candidateCount == 1) { impl->cmdBuffer[cmd.autocompletedLen] = ' '; ++cmd.autocompletedLen; } impl->cmdBuffer[cmd.autocompletedLen] = '\0'; writeToOutput(cli, &impl->cmdBuffer[impl->cmdSize]); impl->cmdSize = cmd.autocompletedLen; impl->inputLineLength = impl->cmdSize; return; } // with multiple candidates when we already completed to common prefix // we show all candidates and print input again // we need to completely clear current line since it begins with invitation clearCurrentLine(cli); for (int i = 0; i < impl->bindingsCount; ++i) { // autocomplete flag is set for all candidates by last call to // getAutocompletedCommand if (!(impl->bindingsFlags[i] & BINDING_FLAG_AUTOCOMPLETE)) continue; const char *name = impl->bindings[i].name; writeToOutput(cli, name); writeToOutput(cli, lineBreak); } writeToOutput(cli, impl->invitation); writeToOutput(cli, impl->cmdBuffer); impl->inputLineLength = impl->cmdSize; } static void clearCurrentLine(EmbeddedCli *cli) { PREPARE_IMPL(cli) size_t len = impl->inputLineLength + strlen(impl->invitation); cli->writeChar(cli, '\r'); for (int i = 0; i < len; ++i) { cli->writeChar(cli, ' '); } cli->writeChar(cli, '\r'); impl->inputLineLength = 0; } static void writeToOutput(EmbeddedCli *cli, const char *str) { size_t len = strlen(str); for (int i = 0; i < len; ++i) { cli->writeChar(cli, str[i]); } } static bool isControlChar(char c) { return c == '\r' || c == '\n' || c == '\b' || c == '\t' || c == 0x7F; } static bool isDisplayableChar(char c) { return (c >= 32 && c <= 126); } static uint16_t fifoBufAvailable(FifoBuf *buffer) { if (buffer->back >= buffer->front) return buffer->back - buffer->front; else return buffer->size - buffer->front + buffer->back; } static char fifoBufPop(FifoBuf *buffer) { char a = '\0'; if (buffer->front != buffer->back) { a = buffer->buf[buffer->front]; buffer->front = (buffer->front + 1) % buffer->size; } return a; } static bool fifoBufPush(FifoBuf *buffer, char a) { uint32_t newBack = (buffer->back + 1) % buffer->size; if (newBack != buffer->front) { buffer->buf[buffer->back] = a; buffer->back = newBack; return true; } return false; } static bool historyPut(CliHistory *history, const char *str) { size_t len = strlen(str); // each item is ended with \0 so, need to have that much space at least if (history->bufferSize < len + 1) return false; // remove str from history (if it's present) so we don't get duplicates historyRemove(history, str); size_t usedSize; // remove old items if new one can't fit into buffer while (history->itemsCount > 0) { const char *item = historyGet(history, history->itemsCount); size_t itemLen = strlen(item); usedSize = (item - history->buf) + itemLen + 1; size_t freeSpace = history->bufferSize - usedSize; if (freeSpace >= len + 1) break; // space not enough, remove last element --history->itemsCount; } if (history->itemsCount > 0) { // when history not empty, shift elements so new item is first memmove(&history->buf[len + 1], history->buf, usedSize); } memcpy(history->buf, str, len + 1); ++history->itemsCount; return true; } static const char *historyGet(CliHistory *history, uint16_t item) { if (item == 0 || item > history->itemsCount) return NULL; // items are stored in the same way (separated by \0 and counted from 1), // so can use this call return embeddedCliGetToken(history->buf, item); } static void historyRemove(CliHistory *history, const char *str) { if (str == NULL || history->itemsCount == 0) return; const char *item = NULL; int i; for (i = 1; i <= history->itemsCount; ++i) { item = historyGet(history, i); if (strcmp(item, str) == 0) { break; } item = NULL; } if (item == NULL) return; --history->itemsCount; if (i == (history->itemsCount + 1)) { // if this is a last element, nothing is remaining to move return; } size_t len = strlen(item); size_t remaining = history->bufferSize - (item + len + 1 - history->buf); // move everything to the right of found item memmove((char *) item, &item[len + 1], remaining); }
/**************************************************************************** // Usagi Engine, Copyright © Vitei, Inc. 2013 ****************************************************************************/ #ifndef _USG_PARTICLE_SET_H_ #define _USG_PARTICLE_SET_H_ #include "Engine/Memory/MemHeap.h" namespace usg { class U8String; class ParticleEffect; class GFXDevice; class ParticleSet { public: virtual void InitPools(GFXDevice* pDevice) = 0; virtual void FreePools() = 0; virtual bool CreateCustomEffect(U8String name, ParticleEffect* pParent) = 0; protected: }; } #endif // _USG_PARTICLE_SET_H_
<reponame>trumank/DRG-Mods #pragma once #include "CoreMinimal.h" #include "AmmoDrivenWeapon.h" #include "GameplayTagContainer.h" #include "ZipLineItem.generated.h" class UDialogDataAsset; UCLASS(Abstract, Blueprintable) class AZipLineItem : public AAmmoDrivenWeapon { GENERATED_BODY() public: protected: UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float MaxDistance; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float MinDistance; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float MinAngle; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) float MaxAngle; UPROPERTY(BlueprintReadWrite, EditAnywhere, meta=(AllowPrivateAccess=true)) FGameplayTagQuery ExcludeSurfaceTags; public: AZipLineItem(); protected: UFUNCTION(BlueprintCallable, BlueprintImplementableEvent) bool CanFireWeapon(FText& FailMsg, UDialogDataAsset*& FailShout); };
#ifndef _BITS_SETJMP_H #define _BITS_SETJMP_H 1 #if !defined _SETJMP_H && !defined _PTHREAD_H # error "Never include <bits/setjmp.h> directly; use <setjmp.h> instead." #endif #ifndef _ASM typedef struct { int __regs[15]; /* callee-saved registers r11-r25 */ void *__gp; /* global pointer */ void *__fp; /* frame pointer */ void *__sp; /* stack pointer */ void *__ra; /* return address */ } __jmp_buf[1]; #endif /* Test if longjmp to JMPBUF would unwind the frame containing a local variable at ADDRESS. */ #define _JMPBUF_UNWINDS(jmpbuf, address) \ ((void *) (address) < (void *) (jmpbuf)[0].__sp) #endif
<filename>include/tiles/fixed/io/tags.h #pragma once #include "protozero/types.hpp" namespace tiles::tags { enum fixed_geometry_type : int { UNKNOWN = 0, POINT = 1, POLYLINE = 2, POLYGON = 3 }; enum class fixed_geometry : protozero::pbf_tag_type { required_fixed_geometry_type = 1, packed_sint64_geometry = 2 }; } // namespace tiles::tags
<reponame>michaelarnauts/wso-wsf-php<gh_stars>10-100 /* * 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 AXIOM_XPATH_INTERNALS_PARSER_H #define AXIOM_XPATH_INTERNALS_PARSER_H #ifdef __cplusplus extern "C" { #endif /** * @defgroup axiom_xpath_parser parser * @ingroup axiom_xpath * @{ */ /* Macros */ /** Get the current character in the expression */ #define AXIOM_XPATH_CURRENT (expr->expr_ptr < expr->expr_len ? \ expr->expr_str[expr->expr_ptr] : -1) /** Get a character after the current */ #define AXIOM_XPATH_NEXT(ind) (expr->expr_ptr + ind < expr->expr_len ? \ expr->expr_str[expr->expr_ptr + ind] : -1) /** Increment the pointer to the expression */ #define AXIOM_XPATH_READ(n) (expr->expr_ptr += n) /** Check if expression has finished parsing */ #define AXIOM_XPATH_HAS_MORE (expr->expr_ptr < expr->expr_len) /** Skip white spaces */ #define AXIOM_XPATH_SKIP_WHITESPACES \ { while(AXIOM_XPATH_CURRENT == ' ') \ AXIOM_XPATH_READ(1); \ } /** Wrape an operation in a self_or_descendent step; used to handle '//' */ #define AXIOM_XPATH_WRAP_SELF_DESCENDANT(_op2) \ axiom_xpath_add_operation(env, expr, AXIOM_XPATH_OPERATION_STEP, \ axiom_xpath_add_operation(env, expr, AXIOM_XPATH_OPERATION_NODE_TEST, \ AXIOM_XPATH_PARSE_END, AXIOM_XPATH_PARSE_END, \ axiom_xpath_create_node_test_node(env), \ axiom_xpath_create_axis(env, AXIOM_XPATH_AXIS_DESCENDANT_OR_SELF)), \ _op2, NULL, NULL) /** Adds an operation */ #define AXIOM_XPATH_PUSH(_opr, _op1, _op2) axiom_xpath_add_operation( \ env, expr, _opr, _op1, _op2, NULL, NULL) /** Adds an operation with parameters */ #define AXIOM_XPATH_PUSH_PAR(_opr, _par1, _par2, _op1) axiom_xpath_add_operation( \ env, expr, _opr, _op1, AXIOM_XPATH_PARSE_END, (void *)_par1, (void *)_par2) /* Functions */ /** * Add an operation to the operations array * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @param op_type Type of the operation * @param op1 First operand * @param op2 Second operand * @param par1 First parameter * @param par2 Second parameter * @return Index of the operation in the array */ int axiom_xpath_add_operation( const axutil_env_t *env, axiom_xpath_expression_t* expr, axiom_xpath_operation_type_t op_type, int op1, int op2, void *par1, void *par2); /** * Compile a XPath expression * * [14] Expr ::= OrExpr * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the main operation in the array */ int axiom_xpath_compile( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile an equals expression * * ***Not completed*** * [23] EqualityExpr ::= UnionExpr '=' UnionExpr * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_compile_equalexpr( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile an union * * [18] UnionExpr ::= PathExpr * | UnionExpr '|' PathExpr * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_compile_union( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile a path expression * * [19] PathExpr ::= LocationPath * | FilterExpr * | FilterExpr '/' RelativeLocationPath * | FilterExpr '//' RelativeLocationPath * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_compile_path_expression( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile a path expression with a filter * * [19] PathExpr ::= FilterExpr * | FilterExpr '/' RelativeLocationPath * | FilterExpr '//' RelativeLocationPath * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_path_compile_path_expression_filter( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile a filter expression * * 20] FilterExpr ::= PrimaryExpr * | FilterExpr Predicate * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_compile_filter( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile a location path * * [1] LocationPath ::= RelativeLocationPath * | AbsoluteLocationPath * [2] AbsoluteLocationPath ::= '/' RelativeLocationPath? * | AbbreviatedAbsoluteLocationPath * * [10] AbbreviatedAbsoluteLocationPath ::= '//' RelativeLocationPath * [11] AbbreviatedRelativeLocationPath ::= RelativeLocationPath '//' Step * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_compile_location_path( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile a relative location * * [3] RelativeLocationPath ::= Step * | RelativeLocationPath '/' Step * | AbbreviatedRelativeLocationPath * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_compile_relative_location( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile a step * * [4] Step ::= AxisSpecifier NodeTest Predicate* * | AbbreviatedStep * [5] AxisSpecifier ::= AxisName '::' * | AbbreviatedAxisSpecifier * * [12] AbbreviatedStep ::= '.' | '..' * [13] AbbreviatedAxisSpecifier ::= '@'? * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_compile_step( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compiles an OrExpr. * * [21] OrExpr ::= AndExpr * | OrExpr 'or' AndExpr * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_compile_orexpr( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compiles an AndExpr. * * [22] AndExpr ::= EqualityExpr * | AndExpr 'and' EqualityExpr * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_compile_andexpr( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compiles a FunctionCall * * [16] FunctionCall ::= FunctionName '(' ( Argument ( ',' Argument )* )? ')' * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_compile_function_call( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compiles an Argument. * * [17] Argument ::= Expr * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_compile_argument( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile a node test * * [7] NodeTest ::= NameTest * | NodeType '(' ')' * | 'processing-instruction' '(' Literal ')' * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ axiom_xpath_node_test_t* axiom_xpath_compile_node_test( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile a predicate(s) * * [8] Predicate ::= '[' PredicateExpr ']' * [9] PredicateExpr ::= Expr * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return Index of the operation in the array */ int axiom_xpath_compile_predicate( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile a literal * * [29] Literal ::= '"' [^"]* '"' * | "'" [^']* "'" * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return The literal parsed */ axis2_char_t* axiom_xpath_compile_literal( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile a number * * [30] Number ::= Digits ('.' Digits?)? * | '.' Digits * [31] Digits ::= [0-9]+ * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return The number parsed */ double* axiom_xpath_compile_number( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Compile a ncname * * @param env Environment must not be null * @param expr A pointer to the XPath expression * @return The ncname parsed */ axis2_char_t* axiom_xpath_compile_ncname( const axutil_env_t *env, axiom_xpath_expression_t* expr); /** * Get the XPath axis by axis name * * [6] AxisName ::= 'ancestor' * | 'ancestor-or-self' * | 'attribute' * | 'child' * | 'descendant' * | 'descendant-or-self' * | 'following' * | 'following-sibling' * | 'namespace' * | 'parent' * | 'preceding' * | 'preceding-sibling' * | 'self' * * @param env Environment must not be null * @param name Name of the axis * @return XPath axis; returns AXIOM_XPATH_AXIS_NONE if invalid name */ axiom_xpath_axis_t axiom_xpath_get_axis( const axutil_env_t *env, axis2_char_t* name); /** * Create a node test which matches all nodes (*) * * @param env Environment must not be null * @return Node test */ axiom_xpath_node_test_t* axiom_xpath_create_node_test_all( const axutil_env_t *env); /** * Create a node test which matches all nodes (nodes()) * * @param env Environment must not be null * @return Node test */ axiom_xpath_node_test_t* axiom_xpath_create_node_test_node( const axutil_env_t *env); /** * Create a pointer to an axis; allocate memory using the allocator * * @param env Environment must not be null * @param axis XPath axis * @return Pointer to the axis created */ axiom_xpath_axis_t *axiom_xpath_create_axis( const axutil_env_t *env, axiom_xpath_axis_t axis); /** @} */ #ifdef __cplusplus } #endif #endif
#ifndef _GRAPHICS_H #define _GRAPHICS_H // #define _QUADRIC #include "SDL.h" #include "SDL_opengl.h" #include <GL/gl.h> #include <GL/glu.h> #include "../../engine/entity/camera.h" #include "../engine.h" #include "../entity/graphicalObj.h" #include "../physics/common.h" #define FLAT_SHADED #ifndef PI # define PI (3.141592f) #endif #define HALF_PI (1.570796f) #ifndef RADS # define RADS (PI/180.0f) #endif #ifndef DEGREES #define DEGREES (180.0f/PI) #endif #ifndef ROOT_TWO # define ROOT_TWO (1.414214f) #endif #define VIEW_DISTANCE 300.0f #define VIEW_DISTANCE_SQUARED (VIEW_DISTANCE*VIEW_DISTANCE) //#define VIEW_DISTANCE 100.0f //#define VIEW_DISTANCE_SQUARED (100.0f*100.0f) //#define _IMMEDIATE_MODE //#define VBO //#define USE_GL_EXT //#define INDICES #ifdef VBO #include <GL/glext.h> extern PFNGLGENBUFFERSARBPROC glGenBuffers; // VBO Name Generation Procedure extern PFNGLBINDBUFFERARBPROC glBindBuffer; // VBO Bind Procedure extern PFNGLBUFFERDATAARBPROC glBufferData; // VBO Data Loading Procedure extern PFNGLDELETEBUFFERSARBPROC glDeleteBuffers; // VBO Deletion Procedure extern PFNGLMAPBUFFERARBPROC glMapBuffer; extern PFNGLUNMAPBUFFERARBPROC glUnmapBuffer; extern PFNGLBUFFERSUBDATAARBPROC glBufferSubData; #ifndef GL_VERSION_1_2 extern PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements; #endif extern bool gGLSupportsVBO; #endif // Graphics Options: //#define NO_FOG //#define SHOW_FPS //#define MAX_LIGHTS 2 //#define WIREFRAME_RENDERING //#define LOW_QUALITY_GEOMETRY //#define LOW_RESOLUTION_TEXTURES //#define SCR_WIDTH 1024 //#define SCR_HEIGHT 768 //#define SCR_DEPTH 16 //#define FULLSCREEN /* #ifndef _DEBUG # define FULLSCREEN #else # define SHOW_FPS #endif */ //#define FULLSCREEN #define SHOW_FPS #define PSP_QUALITY #ifdef PSP_QUALITY # define MAX_LIGHTS 4 # define LOW_QUALITY_GEOMETRY //# define LOW_RESOLUTION_TEXTURES #ifdef _PSP # define SCR_WIDTH 480 # define SCR_HEIGHT 272 #else //# define SCR_WIDTH 1280 //# define SCR_HEIGHT 725 //#define SCR_WIDTH 1024 //#define SCR_HEIGHT 580 //#define SCR_WIDTH 1920 //#define SCR_HEIGHT 1080 // RESOLUTION // #define SCR_WIDTH 600 #define SCR_HEIGHT 400 //#define SCR_WIDTH 1024 //#define SCR_HEIGHT 768 //#define SCR_WIDTH 1280 //#define SCR_HEIGHT 1024 //#define SCR_WIDTH 480 //#define SCR_HEIGHT 272 #endif # define SCR_DEPTH 32 #endif //#define HIGH_QUALITY //#ifdef HIGH_QUALITY //# define MAX_LIGHTS 8 //# define SCR_DEPTH 32 //# define SCR_WIDTH 480 //# define SCR_HEIGHT 272 //# define SCR_WIDTH 800 //# define SCR_HEIGHT 600 //#endif #ifndef FULLSCREEN #define SCR_FLAGS (SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_HWPALETTE | SDL_HWSURFACE | SDL_HWACCEL ) // SDL_HWPALETTE SDL_HWSURFACE SDL_HWACCEL SDL_FULLSCREEN #else #define SCR_FLAGS (SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_HWPALETTE | SDL_HWSURFACE | SDL_HWACCEL | SDL_FULLSCREEN) #endif int GraphicsStartup(); int GraphicsShutdown(); int GameRender(); void BindCamera( CCamera* c ); SVector3 HSV(float h, float s, float v); class CLight; extern CLinkedList<IGraphicalObj> gGraphicalObjList; extern CLinkedList<CLight> gLights; #endif
<reponame>Unidata/Garp /*********************************************************************** * * Copyright 1996, University Corporation for Atmospheric Research. * * winobj.h * * Main window header file. The big cahuna. * * History: * * 11/96 COMET Original copy * 1/97 COMET Added object type UPPERAIRPROFILEOBJECT. * 3/97 COMET Added XSECTIONGRIDFILLOBJECT macro * 4/97 COMET Added "scale" parameter to VECTORGRIDOBJECT. * 6/97 COMET Cleaned up image-related objects * 8/97 COMET Added DataTimeObject for time matching. * 9/97 COMET Added type and label to surface object, tfilter * to Upperair objects, model to grid data objects. * 10/97 COMET Added nstations to surface, upperair objects * 10/97 COMET Added LATLONGRIDOBJECT, LatLonGridObjectType, * changed contents of MapObjectType * 11/97 COMET Removed drawMapFlag, overlayMapFlag and numMaps from * pixmapObject. Removed mapIndex from MapObjectType * 11/97 COMET Redefined and enabled titleObject. Added field_label * model_label and model_name to some metObjects. * 12/97 COMET Added scale to image objects * 2/98 COMET Added ABORTtype macros * ***********************************************************************/ #ifndef _WINOBJ_H #define _WINOBJ_H #include <assert.h> #include <math.h> #include "gendef.h" #include "gui.h" #include <X11/X.h> #include <X11/Intrinsic.h> #include <Xm/Xm.h> #define ABORTNONE 0 #define ABORTCLEAR 1 #define ABORTRESET 2 #define STDSTRINGSIZE (80 + 1) #define GEMPAKSTRING (80 + 1) #define FILENAMESTRING (512 + 1) /* * MetObjectTypes */ #define ANYOBJECT 0 #define SURFACEOBJECT 1 #define RADAROBJECT 2 #define SATOBJECT 3 #define MAPOBJECT 4 #define MARKEROBJECT 5 #define RADARRINGOBJECT 6 #define SCALARGRIDOBJECT 7 #define VECTORGRIDOBJECT 8 #define NOWRADOBJECT 9 #define UPPERAIROBJECT 10 #define XSECTIONGRIDOBJECT 11 #define WINDPROFILEROBJECT 12 #define SCALARGRIDFILLOBJECT 13 #define TIMEHEIGHTOBJECT 14 #define VERTICALPROFILEOBJECT 15 #define UPPERAIRPROFILEOBJECT 16 #define XSECTIONGRIDFILLOBJECT 17 #define BACKGROUNDIMAGEOBJECT 18 #define LATLONGRIDOBJECT 19 /* * Generic descriptive terms for data types */ #define STATICOBJECT 0 /* Static object, map, overlay.. */ #define NONSTATICOBJECT 1 /* non-static (data) */ /* * View types */ #define PLAN 1 #define SPATIALCROSSSECTION 2 #define TIMEHEIGHTCROSSSECTION 3 #define TIMESERIES 4 #define VERTICALPROFILE 5 /* * Overlay class - order is important here. These define the order in * which met objects get drawn. LASTCLASS is not really a class but a value * indicating what the last class value is. If you add a class, change * LASTCLASS appropriately. */ #define UNDEFINED 0 /* nothing */ #define BACKGROUND 1 /* background image */ #define IMAGE 2 /* data image */ #define COLORFILL 3 /* color fill, duh */ #define MAP 4 /* map graphic */ #define GRAPHICS 5 /* data graphics */ #define OVERLAY 6 /* overlay graphics */ #define LASTCLASS 6 /* * Compile time storage allocation constraints */ #define MAXMETOBJS 512 #define MAXPIXMAPOBJS 128 #define MAXMAPOBJS 8 typedef struct { int viewType; char proj[GEMPAKSTRING]; char garea[GEMPAKSTRING]; char filename[FILENAMESTRING]; int prevViewType; char prevProj[GEMPAKSTRING]; char prevGarea[GEMPAKSTRING]; char prevFilename[FILENAMESTRING]; } GeoRefObjectType; /* * Structure containing information that describes a map * projection. */ typedef struct { float angle1; /* reference angles 1, 2, 3 */ float angle2; float angle3; float latll; /* lower left lat, lon */ float lonll; float latur; /* upper right lat, lon */ float lonur; } MapProjType; /* * Structure containing information that describes a * satellite projection for MCIDAS AREA files */ typedef struct { char imgnam [80]; /* image name */ int area [64]; /* area block */ int nav [640]; /* nav block */ int ilef; /* left image coord */ int itop; /* top image coord */ int irit; /* right image coord */ int ibot; /* bottom image coord */ } SatProjType; /* * Structure containing the x, y coordinates and associated latitude and * longitude of two reference points on the display used for verifying * mapping between successive pixmapObjects. */ typedef struct { float x1; float y1; float x2; float y2; float lat1; float lon1; float lat2; float lon2; } ReferencePts; typedef struct { Dimension x1; Dimension x2; Dimension y1; Dimension y2; } RectangularRegionType; /* * Animation Object definition. Created on the fly for series * pixmap objects that are loaded. Destroyed during a clear. */ typedef struct { Display *display; XtAppContext appContext; Window windowID; XtIntervalId xtIntervalID; GC gc; int command; int direction; int isAnimating; int dwellFirst; int dwellMiddle; int dwellLast; int dwellRate; int activePixmapIndex; struct WindowObjectS *windowObject; unsigned int width; unsigned int height; int numPixmaps; Pixmap *pixmaps; } AnimationObjectType; /* * Contains title string information for each pixmap object. */ typedef struct TitleObjectS { /* GC gc; int displayState; unsigned int xOrigin; unsigned int yOrigin; unsigned int width; unsigned int height; Widget dialogWidget; Widget listWidget; XmString *xmStrings; */ unsigned int numTitles; RectangularRegionType region[20]; } TitleObjectType; typedef struct { AbsTime *refTimes; AbsTime *fcstTimes; AbsTime *validTimes; int numTimes; int matchType; int forecastType; } DataTimeObjectType; typedef struct { int pad; } AnyObjectType; /* * Struct for holding image information (least common * denominator of all the image-related objects) */ typedef struct { int imftyp; /* The following items mirror the */ int imbank; /* GEMPAK image common block */ int imdoff; /* (imgdef.cmn) */ int imldat; /* ... */ int imnpix; int imnlin; int imdpth; float rmxres; float rmyres; int imleft; int imtop; int imrght; int imbot; float rmxysc; int imbswp; int imnchl; int imprsz; int imdcsz; int imclsz; int imlvsz; int imvald; int imrdfl; int immnpx; int immxpx; int imsorc; int imtype; int imradf; float rmbelv; int imdate; int imtime; int imndlv; char cmblev[256][9]; char cmbunt[9]; char cmsorc[21]; char cmtype[9]; char cmlutf[17]; char cmfile[133]; char cmcalb[9]; /* ... end of GEMPAK image common */ char colorbar[GEMPAKSTRING]; char scale[GEMPAKSTRING]; unsigned char *imageData; } ImageCommonType; /* * Specific image objects. Includes ImageCommonType and whatever * else makes them unique. */ typedef struct { ImageCommonType imgCmn; } SatObjectType; typedef struct { ImageCommonType imgCmn; } RadarObjectType; typedef struct { ImageCommonType imgCmn; } BackgroundImageObjectType; /* * This one is useful as a generic image object. */ typedef struct { ImageCommonType imgCmn; } AnyImageObjectType; typedef struct { char ftime[GEMPAKSTRING]; char vcoord[GEMPAKSTRING]; char field[GEMPAKSTRING]; char field_label[GEMPAKSTRING]; char vector[GEMPAKSTRING]; char point[GEMPAKSTRING]; char cint[GEMPAKSTRING]; char cmin[GEMPAKSTRING]; char cmax[GEMPAKSTRING]; char line_color[GEMPAKSTRING]; char line_type[GEMPAKSTRING]; char line_width[GEMPAKSTRING]; char label_freq[GEMPAKSTRING]; char text[GEMPAKSTRING]; char scale[GEMPAKSTRING]; char yaxis[GEMPAKSTRING]; char taxis[GEMPAKSTRING]; char ptype[GEMPAKSTRING]; char refvec[GEMPAKSTRING]; char wind_symbol[GEMPAKSTRING]; char symbol_size[GEMPAKSTRING]; char symbol_width[GEMPAKSTRING]; char symbol_type[GEMPAKSTRING]; char symbol_headsize[GEMPAKSTRING]; char model_name[GEMPAKSTRING]; char model_label[GEMPAKSTRING]; } TimeHeightObjectType; typedef struct { char ftime[GEMPAKSTRING]; char vcoord[GEMPAKSTRING]; char field[GEMPAKSTRING]; char field_label[GEMPAKSTRING]; char vector[GEMPAKSTRING]; char point[GEMPAKSTRING]; char cint[GEMPAKSTRING]; char cmin[GEMPAKSTRING]; char cmax[GEMPAKSTRING]; char line_color[GEMPAKSTRING]; char line_type[GEMPAKSTRING]; char line_width[GEMPAKSTRING]; char label_freq[GEMPAKSTRING]; char text[GEMPAKSTRING]; char scale[GEMPAKSTRING]; char xaxis[GEMPAKSTRING]; char yaxis[GEMPAKSTRING]; char ptype[GEMPAKSTRING]; char refvec[GEMPAKSTRING]; char thtaln[GEMPAKSTRING]; char thteln[GEMPAKSTRING]; char mixrln[GEMPAKSTRING]; char filter[GEMPAKSTRING]; char winpos[GEMPAKSTRING]; char wind_symbol[GEMPAKSTRING]; char symbol_size[GEMPAKSTRING]; char symbol_width[GEMPAKSTRING]; char symbol_type[GEMPAKSTRING]; char symbol_headsize[GEMPAKSTRING]; char model_name[GEMPAKSTRING]; char model_label[GEMPAKSTRING]; } VertProfileObjectType; typedef struct { int type; char gdatim[GEMPAKSTRING]; char gvcord[GEMPAKSTRING]; char gfunc[GEMPAKSTRING]; char field_label[GEMPAKSTRING]; char gvect[GEMPAKSTRING]; char cxstns[GEMPAKSTRING]; char cint[GEMPAKSTRING]; char cmin[GEMPAKSTRING]; char cmax[GEMPAKSTRING]; char line_color[GEMPAKSTRING]; char line_type[GEMPAKSTRING]; char line_width[GEMPAKSTRING]; char label_freq[GEMPAKSTRING]; char text[GEMPAKSTRING]; char scale[GEMPAKSTRING]; char clrbar[GEMPAKSTRING]; char contur[GEMPAKSTRING]; char skip[GEMPAKSTRING]; char fint[GEMPAKSTRING]; char fmin[GEMPAKSTRING]; char fmax[GEMPAKSTRING]; char fline[GEMPAKSTRING]; char yaxis[GEMPAKSTRING]; char ptype[GEMPAKSTRING]; char refvec[GEMPAKSTRING]; char wind_symbol[GEMPAKSTRING]; char symbol_size[GEMPAKSTRING]; char symbol_width[GEMPAKSTRING]; char symbol_type[GEMPAKSTRING]; char symbol_headsize[GEMPAKSTRING]; char model_name[GEMPAKSTRING]; char model_label[GEMPAKSTRING]; BooleanType contour; BooleanType fill; } XSectionGridObjectType; typedef struct { char gdatim[GEMPAKSTRING]; char glevel[GEMPAKSTRING]; char gvcord[GEMPAKSTRING]; char gfunc[1024]; char field_label[GEMPAKSTRING]; char cint[GEMPAKSTRING]; char cmin[GEMPAKSTRING]; char cmax[GEMPAKSTRING]; char line_color[GEMPAKSTRING]; char line_type[GEMPAKSTRING]; char line_width[GEMPAKSTRING]; char label_freq[GEMPAKSTRING]; char scale[GEMPAKSTRING]; char hilo[GEMPAKSTRING]; char hlsym[GEMPAKSTRING]; char clrbar[GEMPAKSTRING]; char contur[GEMPAKSTRING]; char skip_contour[GEMPAKSTRING]; char skip_plot_x[GEMPAKSTRING]; char skip_plot_y[GEMPAKSTRING]; char fint[GEMPAKSTRING]; char fmin[GEMPAKSTRING]; char fmax[GEMPAKSTRING]; char fline[GEMPAKSTRING]; char text[GEMPAKSTRING]; char gridtype[GEMPAKSTRING]; char model_name[GEMPAKSTRING]; char model_label[GEMPAKSTRING]; int nfunction; BooleanType contour; BooleanType value; BooleanType fill; BooleanType symbol; } ScalarGridObjectType; typedef struct { char gdatim[GEMPAKSTRING]; char glevel[GEMPAKSTRING]; char gvcord[GEMPAKSTRING]; char gvect[1024]; char field_label[GEMPAKSTRING]; char wind_symbol[GEMPAKSTRING]; char symbol_color[GEMPAKSTRING]; char symbol_size[GEMPAKSTRING]; char symbol_width[GEMPAKSTRING]; char symbol_type[GEMPAKSTRING]; char symbol_headsize[GEMPAKSTRING]; char refvec[GEMPAKSTRING]; char scale[GEMPAKSTRING]; char skip_contour[GEMPAKSTRING]; char skip_plot_x[GEMPAKSTRING]; char skip_plot_y[GEMPAKSTRING]; char text[GEMPAKSTRING]; char gridtype[GEMPAKSTRING]; char model_name[GEMPAKSTRING]; char model_label[GEMPAKSTRING]; int nfunction; } VectorGridObjectType; typedef struct { char cxstn[GEMPAKSTRING]; char snfiles[20][FILENAMESTRING]; char dattim[GEMPAKSTRING]; char yaxis[GEMPAKSTRING]; char taxis[GEMPAKSTRING]; char fint[GEMPAKSTRING]; char text[GEMPAKSTRING]; char wind_symbol[GEMPAKSTRING]; char symbol_size[GEMPAKSTRING]; char symbol_width[GEMPAKSTRING]; int nfiles; } WindProfilerObjectType; typedef struct { BooleanType plot_stn; BooleanType plot_marker; char stations[LLSTFL*GEMPAKSTRING]; char symbol_size[GEMPAKSTRING]; char symbol_width[GEMPAKSTRING]; char text[GEMPAKSTRING]; float lat[LLSTFL]; float lon[LLSTFL]; int stidlen; int color; int marker; int nstn; } MarkerObjectType; typedef struct { char stations[LLSTFL*GEMPAKSTRING]; char stid[GEMPAKSTRING]; char units[GEMPAKSTRING]; float lat[LLSTFL]; float lon[LLSTFL]; float increment; float minimum; int color; int number; int nstn; } RadarRingObjectType; typedef struct { char sfparm[FILENAMESTRING]; char dattim[GEMPAKSTRING]; char colors[GEMPAKSTRING]; char filter[GEMPAKSTRING]; char text[GEMPAKSTRING]; char type[GEMPAKSTRING]; char label[GEMPAKSTRING]; char symbol_size[GEMPAKSTRING]; char symbol_width[GEMPAKSTRING]; int marker; int pmarker; int skpmis; int nstations; } SurfaceObjectType; typedef struct { char snparm[GEMPAKSTRING]; char dattim[GEMPAKSTRING]; char levels[GEMPAKSTRING]; char vcoord[GEMPAKSTRING]; char colors[GEMPAKSTRING]; char marker[GEMPAKSTRING]; char filter[GEMPAKSTRING]; char text[GEMPAKSTRING]; int skpmis; BooleanType tfilter; int nstations; } UpperairObjectType; typedef struct { char dattim[GEMPAKSTRING]; char stndex[GEMPAKSTRING]; char stncol[GEMPAKSTRING]; char vcoord[GEMPAKSTRING]; char colors[GEMPAKSTRING]; char wind_symbol[GEMPAKSTRING]; char symbol_size[GEMPAKSTRING]; char symbol_width[GEMPAKSTRING]; char line_type[GEMPAKSTRING]; char line_width[GEMPAKSTRING]; char winpos[GEMPAKSTRING]; char ptype[GEMPAKSTRING]; char xaxis[GEMPAKSTRING]; char yaxis[GEMPAKSTRING]; char marker[GEMPAKSTRING]; char filter[GEMPAKSTRING]; char text[GEMPAKSTRING]; BooleanType tfilter; } UpaProfileObjectType; typedef struct { char line_color[GEMPAKSTRING]; char line_type[GEMPAKSTRING]; char line_width[GEMPAKSTRING]; char lat_inc[GEMPAKSTRING]; char lon_inc[GEMPAKSTRING]; char label_freq[GEMPAKSTRING]; } LatLonGridObjectType; typedef struct { char mapfile[FILENAMESTRING]; char line_color[GEMPAKSTRING]; char line_type[GEMPAKSTRING]; char line_width[GEMPAKSTRING]; } MapObjectType; typedef union { AnyObjectType anyObj; SatObjectType satObj; RadarObjectType radObj; RadarRingObjectType rringObj; SurfaceObjectType surfaceObj; MapObjectType mapObj; UpaProfileObjectType upapObj; UpperairObjectType upaObj; MarkerObjectType mrkObj; WindProfilerObjectType wproObj; VectorGridObjectType vgribObj; ScalarGridObjectType sgribObj; XSectionGridObjectType xsecObj; VertProfileObjectType vprofObj; TimeHeightObjectType thObj; BackgroundImageObjectType bgimgObj; } MetObjectContentType; /* * Enumerated type of available graphics data that can be * drawn into a pixmap. More than one of these can be * associated with a pixmaps to overlay grahics. */ typedef struct { int type; int inUse; /* in use? */ int drawnFlag; /* has been drawn? */ int toggledOn; /* clicked off by user? */ int titleIndex; AbsTime refTime; AbsTime fcstTime; AbsTime validTime; char timestamp[32]; char filename[FILENAMESTRING]; char template[FILENAMESTRING]; int (*displayFunc)(); void (*destroyFunc)(); char proj[GEMPAKSTRING]; char area[GEMPAKSTRING]; char garea[GEMPAKSTRING]; char titleString[FILENAMESTRING]; MetObjectContentType *metObjectContent; } MetObjectType; typedef struct { int inUse; /* 0 if not in use, !0 otherwise */ int inLoop; /* 1 = include this frame in a loop */ /* 0 = omit from loop */ Display *display; Dimension width; Dimension height; Pixmap pixmap; char proj [10]; MapProjType mapProjection; SatProjType satProjection; ReferencePts referenceLatLons; int numMetObjects; MetObjectType *metObjects[MAXMETOBJS]; } PixmapObjectType; /* * Per X window (or drawing area) data structure. */ typedef struct WindowObjectS { /* window background color? */ int inUse; /* 0 if in use; !0 otherwise */ char windowName[STDSTRINGSIZE]; Widget canvas; int abortFlag; int processExposeEventsFlag; BooleanType showPartialFrameFlag; XtAppContext appContext; Window windowID; Display *display; Dimension width; Dimension height; GC gc; int root; int depth; Pixmap backgroundPixmap; int numPixmapObjects; int activePixmapObjectIndex; PixmapObjectType *pixmapObjects[MAXPIXMAPOBJS]; GeoRefObjectType *geoRefObject; AnimationObjectType *animationObject; TitleObjectType *titleObject; DataTimeObjectType *dataTimeObject; } WindowObjectType; typedef struct { time_t timestamp; int metObjectType; MetObjectType *metObject; } TimestampInfoType; /* * Macro's to access "hidden" elements of the WindowObject * data structure. */ #define GetActivePixmapObjectIndex(w) ((w)->activePixmapObjectIndex) #define GetWindowObjectNumPixmapObjects(w) ((w)->numPixmapObjects) #define GetWindowObjectPixmapObjects(w) ((w)->pixmapObjects) #define SetWindowObjectCanvas(w,c) ((w)->canvas = (c)) #define GetWindowObjectCanvas(w) ((w)->canvas) #define SetWindowObjectDisplay(w,c) ((w)->display = (c)) #define GetWindowObjectDisplay(w) ((w)->display) #define GetWindowObjectAppContext(w) ((w)->appContext) #define SetWindowObjectName(w,c) (strcpy((w)->windowName, (c)) #define GetWindowObjectName(w) ((w)->windowName) #define SetWindowObjectWidth(w,c) ((w)->width = (c)) #define GetWindowObjectWidth(w) ((w)->width) #define SetWindowObjectHeight(w,c) ((w)->height = (c)) #define GetWindowObjectHeight(w) ((w)->height) #define SetWindowObjectRoot(w,c) ((w)->root = (c)) #define GetWindowObjectRoot(w) ((w)->root) #define SetWindowObjectDepth(w,c) ((w)->depth = (c)) #define GetWindowObjectDepth(w) ((w)->depth) #define SetWindowObjectGC(w,c) ((w)->gc = (c)) #define GetWindowObjectGC(w) ((w)->gc) #define SetWindowObjectWindowID(w,c) ((w)->windowID = (c)) #define GetWindowObjectWindowID(w) ((w)->windowID) #define SetWindowObjectAbortFlag(w,c) ((w)->abortFlag = (c)) /* #define GetWindowObjectAbortFlag(w) ((w)->abortFlag) */ /* * Global data */ extern WindowObjectType mainWindow[]; /* * WindowObjectType access functions. */ void SetWindowObjectXstuff( WindowObjectType *wo ); void InitWindowObjects( WindowObjectType *wo, int cnt ); Pixmap CreatePixmapFromWindowObject( WindowObjectType *wo ); Pixmap GetWindowObjectBackgroundPixmap(WindowObjectType *wo); Pixmap GetActivePixmap(WindowObjectType *wo); void SetActivePixmapObjectIndex( WindowObjectType *wo, int index ); void SetActivePixmapObject( WindowObjectType *wo, Pixmap pixmap ); Pixmap *GetWindowObjectPixmapList( WindowObjectType *wo ); WindowObjectType *CreateWindowObject( char *windowName ); WindowObjectType *GetActiveWindowObject(); WindowObjectType *GetWindowObjectByName( char *windowName ); WindowObjectType *SetActiveWindowObject( WindowObjectType *wo ); WindowObjectType *SetActiveWindowObjectByName( char *windowName ); WindowObjectType *GetWindowObjectByWidget( Widget w ); void WindowObjectResize( WindowObjectType *wo, Dimension width, Dimension height ); /* * PixmapObjectType access functions * */ PixmapObjectType *GetNextPot( WindowObjectType *wo ); PixmapObjectType *GetActivePixmapObject( WindowObjectType *wo ); void PixmapObjectResize( WindowObjectType *wo, PixmapObjectType *pot, Dimension width, Dimension height); #define GetPixmapObjectPixmaps(p) ((p)->pixmap) /* * MetObjectType access functions * */ MetObjectType *GetNextMot( PixmapObjectType *pot ); void FreeMot( MetObjectType *m); void ReleaseMot( MetObjectType *m); MetObjectType *AllocateMot(); MetObjectType *CloneMot(); int GetMetObjectClass( int metObjectType ); #define GetMetObjectType(x) ((x)->type) #define GetMetObjectDrawnFlag(x) ((x)->drawnFlag) #define SetMetObjectDrawnFlag(x,c) ((x)->drawnFlag = (c)) /* * * MetObject functions. */ void DestroySurfaceObject( MetObjectType *mot ); void DestroyUpperairObject( MetObjectType *mot ); void DestroyUpaProfileObject( MetObjectType *mot ); void DestroyMapObject( MetObjectType *mot ); void DestroyLatLonGridObject( MetObjectType *mot ); void DestroyTimeHeight ( MetObjectType *mot ); void DestroyVerticalProfile ( MetObjectType *mot ); void DestroySatObject ( MetObjectType *mot ); void DestroyRadarObject ( MetObjectType *mot ); void DestroyBackgroundImageObject ( MetObjectType *mot ); void DoImageObjects( int metObjectType, char *path, int cnt, char **filev ); MetObjectType *MakeSatObject( int, char *, char *, char *, int, char *); MetObjectType *MakeRadarObject( int, char *, char *, char *, int, char *); MetObjectType *MakeBackgroundImageObject( int, char *, char *, char *, int, char *); MetObjectType *MakeBackgroundMapObject( int, char * ); MetObjectType **MakeImageObjectList( int, int, char **, char ** ); MetObjectType *MakeMapObject( char *, char *, char *, char *, char * ); MetObjectType *MakeLatLonGridObject( char *, char *, char *, char *, char *, char * ); MetObjectType *MakeRadarRingObject ( int, int, float, float, char*, char *, int, int * ); MetObjectType *MakeSurfaceObject ( char *, char *, char *, char *, char *, char *, char *,char *, int, int, int, int ); MetObjectType *MakeUpperairObject ( char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, int, int, BooleanType ); MetObjectType *MakeUpaProfileObject ( char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, int , BooleanType ); MetObjectType * MakeHorizontalScalarGridObject( char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, int , int , BooleanType, BooleanType, BooleanType, BooleanType ); MetObjectType * MakeTimeHeightObject ( char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, int ); MetObjectType * MakeVerticalProfileObject ( char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, int ); MetObjectType * MakeXSectionGridObject (char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, int , BooleanType, BooleanType ); MetObjectType * MakeHorizontalVectorGridObject ( char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, char *, int , int ); MetObjectType * MakeWindProfilerObject (char *, char **,int , char *, char *, char *, char *, char *, char *, char *, char *, int ); /* * * Object Management routines * */ void AddTimeMatchedObjects( WindowObjectType *wo, int cnt, TimestampInfoType *tsi); void AddObjectListToDisplay( int cnt, MetObjectType **mlist ); PixmapObjectType *GetTimeMatchedPot( WindowObjectType *wo, time_t timestamp ); GeoRefObjectType *GetGeoRefObject( WindowObjectType *wo ); GeoRefObjectType *CreateGeoRefObject(); void UpdateTitleObject( WindowObjectType *wo ); void GetMetObjectTitles( PixmapObjectType *pot, int *cnt, char ***titlev); /* * Callbacks that interface with GEMPAK libraries. * */ int DisplaySurface( WindowObjectType *mw, MetObjectType *mot ); int DisplayUpperair( WindowObjectType *mw, MetObjectType *mot ); int DisplayUpaProfile( WindowObjectType *mw, MetObjectType *mot ); int DisplayScalarGrid ( WindowObjectType *mw, MetObjectType *mot ); int DisplayVectorGrid ( WindowObjectType *mw, MetObjectType *mot ); int DisplayWindProfiler ( WindowObjectType *mw, MetObjectType *mot ); int DisplayTimeHeight ( WindowObjectType *mw, MetObjectType *mot ); int DisplayVerticalProfile ( WindowObjectType *mw, MetObjectType *mot ); int DisplayXSection ( WindowObjectType *mw, MetObjectType *mot ); int DisplayBackgroundImage( WindowObjectType *mw, MetObjectType *mot ); int DisplayRadar( WindowObjectType *mw, MetObjectType *mot ); int DisplaySat( WindowObjectType *mw, MetObjectType *mot ); int DisplayBackgroundObject( WindowObjectType *mw, MetObjectType *mot ); int DisplayMarker( WindowObjectType *mw, MetObjectType *mot ); int DisplayRadarRing( WindowObjectType *mw, MetObjectType *mot ); /* * Animation control functions */ void AnimateCB( Widget w, XtPointer client, XtPointer calldata ); void AnimationObjectStop( WindowObjectType *wo ); void AnimationObjectPlayFwd( WindowObjectType *wo ); void AnimationObjectPlayBack( WindowObjectType *wo ); void AnimationObjectStepFwd( WindowObjectType *wo ); void AnimationObjectStepBack( WindowObjectType *wo ); AnimationObjectType *AnimationObjectCreate( WindowObjectType *wo ); /* * External Macro's for animation control */ #define AnimationRunning(x) ( ( (x)->animationObject) && \ ( (x)->animationObject->isAnimating) ) #define GetAnimationCommand(x) ( ( (x)->animationObject) ? \ ( (x)->animationObject->command ) : \ NOLOOP ) XmString *CreateMotifStringTable( int cnt, char *argv[], char *fontTag ); void FreeMotifStringTable( int cnt, XmString *xmstrs ); TitleObjectType *TitleObjectAllocate(); DataTimeObjectType *GetDataTimeObject(); #endif /* _WINOBJ_H */
#ifndef CCO_NODE_H #define CCO_NODE_H #include <stddef.h> struct cco_node { struct cco_node *next; }; #define CCO_NODE_INIT() \ { NULL } static inline void cco_node_add_next(struct cco_node *where, struct cco_node *novel) { novel->next = where->next; where->next = novel; } static inline void cco_node_del(struct cco_node *prev, struct cco_node *node) { prev->next = node->next; node->next = NULL; } static inline void cco_node_init(struct cco_node *node) { node->next = NULL; } #endif
#pragma once #include "modules/bio_base/dna_sequence.h" #include "modules/bio_base/kmer.h" #include "modules/build_seqset/repo_seq.h" namespace build_seqset { class part_repo { public: part_repo(unsigned partition_depth, const std::string& ref_path_prefix, const std::string& repo_path); struct partition_ref { kmer_t part_id; // Prefix of entries in this partition, e.g. "ACTG" dna_sequence prefix; // The repository containing all entries in this partition, // e.g. for "ACTG". std::shared_ptr<const seq_repository> main; // Repositories containing all entries for front pushes of entries // in this partition. E.g. "AACT", "CACT", "GACT", "TACT". dna_base_array< std::pair<seq_repository::iterator, seq_repository::iterator>> pushed; dna_base_array<std::shared_ptr<const seq_repository>> pushed_repositories; // First sequence of next partition. dna_sequence next_entry; // Frees up references to this partition. void reset() { main.reset(); for (dna_base b : dna_bases()) { pushed_repositories[b].reset(); } } }; class write_entry_buffer; void open_write_pass(const std::string& pass_name); std::unique_ptr<seq_repository::ref_builder> open_ref_builder( kmer_t part_id, const std::string& pass_name); void add_initial_repo(const dna_slice& reference_data); void write(const dna_slice& seq, unsigned fwd_suffixes, unsigned rc_suffixes); void write_using_repo(const dna_slice& seq, unsigned fwd_suffixes, unsigned rc_suffixes, size_t repo_offset); void write(const seq_repository::entry_base& e); size_t write_with_expansions(const seq_repository::entry_base& e, unsigned stride, unsigned count); void flush(); std::unique_ptr<part_counts> release_part_counts(const std::string& pass_name); void reset_part_counts(const std::string& pass_name, std::unique_ptr<part_counts> counts); void for_each_partition(const std::string& pass_name, const std::function<void(const partition_ref&)>& f, progress_handler_t progress = null_progress_handler); // If "do_expand" is true, also populates pushed_repositories. std::vector<partition_ref> partitions(const std::string& pass_name, bool do_pushed = true, bool delete_on_close = false) const; const dna_slice& repo_slice() const { return m_repo_slice; } size_t partition_count() const { return 1 << (2 * m_depth); } size_t partition_depth() const { return m_depth; } private: // Keep statistics on 4^k_part_counts_depth chunks for each partition static constexpr unsigned k_part_counts_depth = 3; void dump_part_counts_if_needed() const; dna_sequence prefix_for_partition(kmer_t part_num) const; kmer_t partition_for_sequence(const dna_slice& seq) const; std::string ref_filename(kmer_t part_num, const std::string& pass_name) const; seq_repository::repo_builder* get_repo_builder(); std::shared_ptr<seq_repository> open_part_repo( kmer_t part_num, const std::string& pass_name) const; void write_raw(const seq_repository::entry_data& e); std::tuple<std::shared_ptr<const seq_repository>, seq_repository::iterator, seq_repository::iterator> range_including_prefix(const std::vector<partition_ref>& parts, const dna_slice& seq) const; unsigned m_depth; std::string m_ref_prefix; std::string m_repo_path; membuf m_repo; dna_slice m_repo_slice; std::mutex m_mu; std::vector<std::unique_ptr<seq_repository::ref_builder>> m_ref_builders; std::unique_ptr<seq_repository::repo_builder> m_repo_builder; std::unique_ptr<part_counts> m_part_counts; std::string m_part_counts_pass_name; }; } // namespace build_seqset
//===- AffineExpressions.h - Expression Analysis Utils ----------*- C++ -*--=// // // The SAFECode Compiler // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a package of expression analysis utilties. // //===----------------------------------------------------------------------===// #ifndef LLVM_C_EXPRESSIONS_H #define LLVM_C_EXPRESSIONS_H #include <assert.h> #include <map> #include <list> #include <string> #include <strstream> #include "llvm/Instruction.h" #include "llvm/Instructions.h" #include "llvm/InstrTypes.h" #include "llvm/Constants.h" #include "llvm/Analysis/PostDominators.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Target/Mangler.h" #include "llvm/DerivedTypes.h" using namespace std; namespace llvm { namespace cfg { class LoopInfo; } typedef std::map<const PHINode *, Value *> IndVarMap; typedef std::map<const Function *,BasicBlock *> ExitNodeMap; typedef std::map<const Function *, PostDominanceFrontier *> PostDominanceFrontierMap; typedef std::map<const Value*,int> CoefficientMap; typedef std::map<const Value*,string> ValStringMap; typedef std::list<const Value*> VarList; typedef std::list<const Value*>::const_iterator VarListIt; typedef std::list<const CallInst*> CallInstList; typedef std::list<const CallInst*>::const_iterator CallInstListIt; typedef std::map<Instruction*, bool> MemAccessInstListType; typedef std::map<Instruction*, bool>::const_iterator MemAccessInstListIt; // // Function: makeNameProper() // // Description: // This function transforms a name to meet two requirements: // o) There are no invalid symbols. // o) The string length is 18 characters or less. // To do this, we replace symbols such as period, underscore, minus, etc. // with a letter followed by an underscore. // // Notes: // FIXME: This function always converts "in" to "in__1." I am not sure why // this is. // static inline string makeNameProper (string x) { string tmp; int len = 0; for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++) { if (len > 18) return tmp; //have to do something more meaningful len++; switch (*sI) { case '.': tmp += "d_"; len++;break; case ' ': tmp += "s_"; len++;break; case '-': tmp += "D_"; len++;break; case '_': tmp += "l_"; len++;break; default: tmp += *sI; } } if (tmp == "in") return "in__1"; return tmp; } // // Class: OmegaMangler // // Description: // This class can be used in place of the LLVM Mangler for mangling LLVM value // names into strings that can be used as variable names in the Omega // calculator. // // Notes: // Having a single method that properly converts an LLVM Value's name into an // Omega calculator name is less error-prone than having the code call // makeNameProper() directly. // // TODO: // This mangler class needs to be expanded to include functionality that was // present in the LLVM 2.6 Mangler class. This class has been removed in // LLVM 2.7, and this code is currently unused, so it's modified just enough // to keep compilation working. Eventually, we should either get this code // working or remove it entirely. // class OmegaMangler { public: OmegaMangler (Module & M) { } std::string getValueName (const Value *V) { // Counter for making unique value names for unnamed values static unsigned id_counter = 0; // // The LLVM name mangler doesn't work on regular LLVM values any more, // so we must replicate the functionality here. // if (V->hasName()) { return (makeNameProper ((V->getName()))); } std::ostrstream intstr; intstr << "noname" << (++id_counter); return (makeNameProper ((intstr.str()))); } }; // // Class: LinearExpr // // Description: // Represent an expression of the form CONST*VAR1 + CONST*VAR2 + ... // class LinearExpr { int offSet; VarList* vList; CoefficientMap* cMap; ValStringMap* vsMap; public: enum ExpressionType { Linear, // Expression is linear Unknown // Expression is some unknown type of expression } exprTy; inline int getOffSet() { return offSet; }; inline void setOffSet(int offset) { offSet = offset; }; inline ExpressionType getExprType() { return exprTy; }; inline VarList* getVarList() { return vList; }; inline CoefficientMap* getCMap() { return cMap; }; inline ValStringMap* getVSMap() { return vsMap; }; // Create a linear expression LinearExpr(const Value *Val, OmegaMangler *Mang); void negate(); void addLinearExpr(LinearExpr *); LinearExpr * mulLinearExpr(LinearExpr *); void mulByConstant(int); void print(ostream &out); void printOmegaSymbols(ostream &out); }; // // Class: Constraint // // Description: // This class represents a constaint of the form <var> <rel> <expr> where: // <var> : is a variable // <rel> : is one of the following relations: <, >, <=, >= // <expr> : is a linear expression // class Constraint { string var; LinearExpr *le; // The relation: can be < , >, <=, >= for now string rel; // Flags whether the left-hand value is constant bool leConstant_; public : Constraint(string v, LinearExpr *l, string r, bool leConstant = false ) { assert(l != 0 && "the rhs for this constraint is null"); var = v; le = l; rel = r; leConstant_ = leConstant; } void print(ostream &out); void printOmegaSymbols(ostream &out); }; // // Class: ABCExprTree // // Description: // This class represents a set of relations that are connected together with // boolean AND and OR. It represents the entire expression as a tree. Each // node has a left and right subtree and either an AND or OR relation that // specified the relationship between the two subtrees. // class ABCExprTree { Constraint *constraint; ABCExprTree *right; ABCExprTree *left; string logOp; // can be && or || or public: ABCExprTree(Constraint *c) { constraint = c; left = 0; right = 0; logOp = "&&"; }; ABCExprTree(ABCExprTree *l, ABCExprTree *r, string op) { constraint = 0; assert( l && " l is null \n"); assert( r && " r is null \n"); left = l; right = r; logOp = op; } void dump(); void print(ostream &out); void printOmegaSymbols(ostream &out); }; typedef std::map<const Value *, ABCExprTree *> InstConstraintMapType; // // Class: FuncLocalInfo // // Description: // This class retains constraint information collected for a function. // class FuncLocalInfo { // Local cache for constraints InstConstraintMapType FuncLocalConstraints; // Storing all constraints which need proving InstConstraintMapType FuncSafetyConstraints; // All array accesses in a function MemAccessInstListType maiList; // This stores the Or of the arguments at // various call sites, so that can be computed only once for // different array accesses. ABCExprTree *argConstraints; public : FuncLocalInfo() { argConstraints = 0; } inline void addMemAccessInst(Instruction *MAI, bool reqArg) { maiList[MAI] = reqArg; } inline void addLocalConstraint(const Value *v, ABCExprTree *aet) { FuncLocalConstraints[v] = aet; } inline bool inLocalConstraints(const Value *v) { return (FuncLocalConstraints.count(v) > 0); } inline ABCExprTree * getLocalConstraint(const Value *v) { if (FuncLocalConstraints.count(v)) return FuncLocalConstraints[v]; else return 0; } inline void addSafetyConstraint(const Value *v, ABCExprTree *aet) { FuncSafetyConstraints[v] = aet; } inline ABCExprTree* getSafetyConstraint(const Value *v) { return (FuncSafetyConstraints[v]); } inline MemAccessInstListType getMemAccessInstList() { return maiList; } inline void addArgumentConstraints(ABCExprTree *aet) { argConstraints = aet; } inline ABCExprTree * getArgumentConstraints() { return argConstraints; } }; #if 0 static string getValueNames(const Value *V, Mangler *Mang) { if (const Constant *CPI = dyn_cast<Constant>(V)) { if (const ConstantSInt *CPI = dyn_cast<ConstantSInt>(V)) { return itostr(CPI->getValue()); } else if (const ConstantUInt *CPI = dyn_cast<ConstantUInt>(V)) { return utostr(CPI->getValue()); } } if (V->hasName()) { return makeNameProper(V->getName()); } else { return Mang->getValueName(V); } }; #endif } #endif
#ifndef _HAPFRAGMENT_H #define _HAPFRAGMENT_H #include<stdio.h> #include<stdlib.h> #include<time.h> #include<math.h> #include<string.h> #include "readvariant.h" extern int SINGLEREADS; extern int DATA_TYPE; extern int NEW_FORMAT; extern int PRINT_COMPACT; // default = 1 typedef struct { char allele; char qv; int varid; // allele is 0/1 varid is index to varlist[varid] gives all information about the variant } allele; typedef struct { char* id; int variants; allele* alist; int blocks; int paired; int matepos; int absIS; char* barcode; char strand; // added 01/26/2018 } FRAGMENT; int compare_fragments(const void *a, const void *b); int compare_alleles(const void *a, const void *b); int print_fragment(FRAGMENT* fragment, VARIANT* varlist, FILE* outfile); // make sure they are in the correct order, i+1 could be < i int print_matepair(FRAGMENT* f1, FRAGMENT* f2, VARIANT* varlist, FILE* outfile); void clean_fragmentlist(FRAGMENT* flist, int* fragments, VARIANT* varlist, int currchrom, int currpos, int prevchrom); #endif
<gh_stars>1-10 // // CSScrollZoomView.h // 03-zoomPhoto // // Created by <NAME> on 2017/8/8. // Copyright © 2017年 Joslyn. All rights reserved. // #import <UIKit/UIKit.h> @interface CSScrollZoomView : UIView - (void)reloadData; @property (nonatomic, copy) void(^itemDidClick)(NSUInteger index); @property (nonatomic, strong) NSArray<NSString *> *imageNames; @property (nonatomic, strong) NSArray<NSString *> *titles; /** 放大比例,默认0.6 */ @property (nonatomic, assign) CGFloat enlargeScale; @property (nonatomic, assign) CGSize itemSize; @property (nonatomic, assign) CGFloat distanceOfItem; @property (nonatomic, strong) UIColor *itemBackgroundColor; /** 只有图片时,imgSize = itemSize。 */ @property (nonatomic, assign) CGSize imgSize; @property (nonatomic, assign) UIOffset imgOffset; /** 不只有图片时有效,默认为0.0。 */ @property (nonatomic, assign) CGFloat distanceOfImgAndTitle; /** 自由滚动速率的快慢,默认YES */ @property (nonatomic, assign) BOOL isScrollFast; @property (nonatomic, strong) NSString *placeholderImageName; @property (nonatomic, strong) UIFont *titleFont; @property (nonatomic, strong) UIColor *titleColor; @property (nonatomic, assign) NSTextAlignment textAlignment; @property (nonatomic, strong) UIColor *titleLabelBGColor; @end
/* Copyright 2016 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "dcrypto.h" #include "internal.h" #include "registers.h" #include "cryptoc/sha512.h" #ifdef CRYPTO_TEST_SETUP /* test and benchmark */ #include "common.h" #include "console.h" #include "hooks.h" #include "task.h" #define cyclecounter() GREG32(M3, DWT_CYCCNT) #define START_PROFILE(x) \ { \ x -= cyclecounter(); \ } #define END_PROFILE(x) \ { \ x += cyclecounter(); \ } static uint32_t t_sw; static uint32_t t_hw; static uint32_t t_transform; static uint32_t t_dcrypto; #else /* CRYPTO_TEST_SETUP */ #define START_PROFILE(x) #define END_PROFILE(x) #endif /* CRYPTO_TEST_SETUP */ /* auto-generated from go test haven -test.run=TestSha512 -test.v */ /* clang-format off */ static const uint32_t IMEM_dcrypto[] = { /* @0x0: function tag[1] { */ #define CF_tag_adr 0 0xf8000003, /* sigini #3 */ /* } */ /* @0x1: function expandw[84] { */ #define CF_expandw_adr 1 0x4c3def00, /* xor r15, r15, r15 */ 0x803c0013, /* movi r15.0l, #19 */ 0x80bc0016, /* movi r15.1l, #22 */ 0x97800f00, /* ldrfp r15 */ 0x05004003, /* loop #4 ( */ 0x8c001800, /* ld *0, *0++ */ 0x906c0800, /* st *0++, *3++ */ 0xfc000000, /* nop */ /* ) */ 0x0501004a, /* loop #16 ( */ 0x684a6080, /* rshi r18, r0, r19 >> 128 */ 0x68443340, /* rshi r17, r19, r1 >> 64 */ 0x683e3201, /* rshi r15, r18, r17 >> 1 */ 0x68423208, /* rshi r16, r18, r17 >> 8 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x6843f207, /* rshi r16, r18, r31 >> 7 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x505df398, /* add r23, r19, r15 >> 192 */ 0x505eb788, /* add r23, r23, r21 >> 64 */ 0x684ac0c0, /* rshi r18, r0, r22 >> 192 */ 0x68443680, /* rshi r17, r22, r1 >> 128 */ 0x683e3213, /* rshi r15, r18, r17 >> 19 */ 0x6842323d, /* rshi r16, r18, r17 >> 61 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x6843f206, /* rshi r16, r18, r31 >> 6 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x505df798, /* add r23, r23, r15 >> 192 */ 0x684a60c0, /* rshi r18, r0, r19 >> 192 */ 0x68443380, /* rshi r17, r19, r1 >> 128 */ 0x683e3201, /* rshi r15, r18, r17 >> 1 */ 0x68423208, /* rshi r16, r18, r17 >> 8 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x6843f207, /* rshi r16, r18, r31 >> 7 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x50627f88, /* add r24, r31, r19 >> 64 */ 0x5061f898, /* add r24, r24, r15 >> 192 */ 0x5062b890, /* add r24, r24, r21 >> 128 */ 0x684416c0, /* rshi r17, r22, r0 >> 192 */ 0x683e3613, /* rshi r15, r22, r17 >> 19 */ 0x6842363d, /* rshi r16, r22, r17 >> 61 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x6843f606, /* rshi r16, r22, r31 >> 6 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x5061f898, /* add r24, r24, r15 >> 192 */ 0x684433c0, /* rshi r17, r19, r1 >> 192 */ 0x683e3301, /* rshi r15, r19, r17 >> 1 */ 0x68423308, /* rshi r16, r19, r17 >> 8 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x6843f307, /* rshi r16, r19, r31 >> 7 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x50667f90, /* add r25, r31, r19 >> 128 */ 0x5065f998, /* add r25, r25, r15 >> 192 */ 0x5066b998, /* add r25, r25, r21 >> 192 */ 0x684ae040, /* rshi r18, r0, r23 >> 64 */ 0x683ef213, /* rshi r15, r18, r23 >> 19 */ 0x6842f23d, /* rshi r16, r18, r23 >> 61 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x6843f206, /* rshi r16, r18, r31 >> 6 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x5065f998, /* add r25, r25, r15 >> 192 */ 0x684a8040, /* rshi r18, r0, r20 >> 64 */ 0x683e9201, /* rshi r15, r18, r20 >> 1 */ 0x68429208, /* rshi r16, r18, r20 >> 8 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x6843f207, /* rshi r16, r18, r31 >> 7 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x506a7f98, /* add r26, r31, r19 >> 192 */ 0x5069fa98, /* add r26, r26, r15 >> 192 */ 0x506ada00, /* add r26, r26, r22 */ 0x684b0040, /* rshi r18, r0, r24 >> 64 */ 0x683f1213, /* rshi r15, r18, r24 >> 19 */ 0x6843123d, /* rshi r16, r18, r24 >> 61 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x6843f206, /* rshi r16, r18, r31 >> 6 */ 0x4c3e0f00, /* xor r15, r15, r16 */ 0x5069fa98, /* add r26, r26, r15 >> 192 */ 0x7c4c1400, /* mov r19, r20 */ 0x7c501500, /* mov r20, r21 */ 0x7c541600, /* mov r21, r22 */ 0x685af640, /* rshi r22, r22, r23 >> 64 */ 0x685b1640, /* rshi r22, r22, r24 >> 64 */ 0x685b3640, /* rshi r22, r22, r25 >> 64 */ 0x685b5640, /* rshi r22, r22, r26 >> 64 */ 0x906c0100, /* st *1, *3++ */ /* ) */ 0x0c000000, /* ret */ /* } */ /* @0x55: function Sha512_a[125] { */ #define CF_Sha512_a_adr 85 0x68580c40, /* rshi r22, r12, r0 >> 64 */ 0x683c161c, /* rshi r15, r22, r0 >> 28 */ 0x68541622, /* rshi r21, r22, r0 >> 34 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x68541627, /* rshi r21, r22, r0 >> 39 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x40402000, /* and r16, r0, r1 */ 0x40544000, /* and r21, r0, r2 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x40544100, /* and r21, r1, r2 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x68458fc0, /* rshi r17, r15, r12 >> 192 */ 0x50461100, /* add r17, r17, r16 */ 0x68588d40, /* rshi r22, r13, r4 >> 64 */ 0x6848960e, /* rshi r18, r22, r4 >> 14 */ 0x68549612, /* rshi r21, r22, r4 >> 18 */ 0x4c4ab200, /* xor r18, r18, r21 */ 0x684c9629, /* rshi r19, r22, r4 >> 41 */ 0x4c4a7200, /* xor r18, r18, r19 */ 0x404ca400, /* and r19, r4, r5 */ 0x48548000, /* not r21, r4 */ 0x4054d500, /* and r21, r21, r6 */ 0x4c4eb300, /* xor r19, r19, r21 */ 0x6851b2c0, /* rshi r20, r18, r13 >> 192 */ 0x5050f400, /* add r20, r20, r7 */ 0x50515480, /* add r20, r20, r10 >> 0 */ 0x68558b00, /* rshi r21, r11, r12 >> 0 */ 0x50567500, /* add r21, r21, r19 */ 0x5052b400, /* add r20, r20, r21 */ 0x500e8300, /* add r3, r3, r20 */ 0x501e3400, /* add r7, r20, r17 */ 0x6858ec40, /* rshi r22, r12, r7 >> 64 */ 0x683cf61c, /* rshi r15, r22, r7 >> 28 */ 0x6854f622, /* rshi r21, r22, r7 >> 34 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x6854f627, /* rshi r21, r22, r7 >> 39 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x40400700, /* and r16, r7, r0 */ 0x40542700, /* and r21, r7, r1 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x40542000, /* and r21, r0, r1 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x68458fc0, /* rshi r17, r15, r12 >> 192 */ 0x50461100, /* add r17, r17, r16 */ 0x68586d40, /* rshi r22, r13, r3 >> 64 */ 0x6848760e, /* rshi r18, r22, r3 >> 14 */ 0x68547612, /* rshi r21, r22, r3 >> 18 */ 0x4c4ab200, /* xor r18, r18, r21 */ 0x684c7629, /* rshi r19, r22, r3 >> 41 */ 0x4c4a7200, /* xor r18, r18, r19 */ 0x404c8300, /* and r19, r3, r4 */ 0x48546000, /* not r21, r3 */ 0x4054b500, /* and r21, r21, r5 */ 0x4c4eb300, /* xor r19, r19, r21 */ 0x6851b2c0, /* rshi r20, r18, r13 >> 192 */ 0x5050d400, /* add r20, r20, r6 */ 0x50515488, /* add r20, r20, r10 >> 64 */ 0x68558b40, /* rshi r21, r11, r12 >> 64 */ 0x50567500, /* add r21, r21, r19 */ 0x5052b400, /* add r20, r20, r21 */ 0x500a8200, /* add r2, r2, r20 */ 0x501a3400, /* add r6, r20, r17 */ 0x6858cc40, /* rshi r22, r12, r6 >> 64 */ 0x683cd61c, /* rshi r15, r22, r6 >> 28 */ 0x6854d622, /* rshi r21, r22, r6 >> 34 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x6854d627, /* rshi r21, r22, r6 >> 39 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x4040e600, /* and r16, r6, r7 */ 0x40540600, /* and r21, r6, r0 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x40540700, /* and r21, r7, r0 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x68458fc0, /* rshi r17, r15, r12 >> 192 */ 0x50461100, /* add r17, r17, r16 */ 0x68584d40, /* rshi r22, r13, r2 >> 64 */ 0x6848560e, /* rshi r18, r22, r2 >> 14 */ 0x68545612, /* rshi r21, r22, r2 >> 18 */ 0x4c4ab200, /* xor r18, r18, r21 */ 0x684c5629, /* rshi r19, r22, r2 >> 41 */ 0x4c4a7200, /* xor r18, r18, r19 */ 0x404c6200, /* and r19, r2, r3 */ 0x48544000, /* not r21, r2 */ 0x40549500, /* and r21, r21, r4 */ 0x4c4eb300, /* xor r19, r19, r21 */ 0x6851b2c0, /* rshi r20, r18, r13 >> 192 */ 0x5050b400, /* add r20, r20, r5 */ 0x50515490, /* add r20, r20, r10 >> 128 */ 0x68558b80, /* rshi r21, r11, r12 >> 128 */ 0x50567500, /* add r21, r21, r19 */ 0x5052b400, /* add r20, r20, r21 */ 0x50068100, /* add r1, r1, r20 */ 0x50163400, /* add r5, r20, r17 */ 0x6858ac40, /* rshi r22, r12, r5 >> 64 */ 0x683cb61c, /* rshi r15, r22, r5 >> 28 */ 0x6854b622, /* rshi r21, r22, r5 >> 34 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x6854b627, /* rshi r21, r22, r5 >> 39 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x4040c500, /* and r16, r5, r6 */ 0x4054e500, /* and r21, r5, r7 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x4054e600, /* and r21, r6, r7 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x68458fc0, /* rshi r17, r15, r12 >> 192 */ 0x50461100, /* add r17, r17, r16 */ 0x68582d40, /* rshi r22, r13, r1 >> 64 */ 0x6848360e, /* rshi r18, r22, r1 >> 14 */ 0x68543612, /* rshi r21, r22, r1 >> 18 */ 0x4c4ab200, /* xor r18, r18, r21 */ 0x684c3629, /* rshi r19, r22, r1 >> 41 */ 0x4c4a7200, /* xor r18, r18, r19 */ 0x404c4100, /* and r19, r1, r2 */ 0x48542000, /* not r21, r1 */ 0x40547500, /* and r21, r21, r3 */ 0x4c4eb300, /* xor r19, r19, r21 */ 0x6851b2c0, /* rshi r20, r18, r13 >> 192 */ 0x50509400, /* add r20, r20, r4 */ 0x50515498, /* add r20, r20, r10 >> 192 */ 0x68558bc0, /* rshi r21, r11, r12 >> 192 */ 0x50567500, /* add r21, r21, r19 */ 0x5052b400, /* add r20, r20, r21 */ 0x50028000, /* add r0, r0, r20 */ 0x50123400, /* add r4, r20, r17 */ 0x0c000000, /* ret */ /* } */ /* @0xd2: function Sha512_b[125] { */ #define CF_Sha512_b_adr 210 0x68588d40, /* rshi r22, r13, r4 >> 64 */ 0x683c961c, /* rshi r15, r22, r4 >> 28 */ 0x68549622, /* rshi r21, r22, r4 >> 34 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x68549627, /* rshi r21, r22, r4 >> 39 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x4040a400, /* and r16, r4, r5 */ 0x4054c400, /* and r21, r4, r6 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x4054c500, /* and r21, r5, r6 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x6845afc0, /* rshi r17, r15, r13 >> 192 */ 0x50461100, /* add r17, r17, r16 */ 0x68580c40, /* rshi r22, r12, r0 >> 64 */ 0x6848160e, /* rshi r18, r22, r0 >> 14 */ 0x68541612, /* rshi r21, r22, r0 >> 18 */ 0x4c4ab200, /* xor r18, r18, r21 */ 0x684c1629, /* rshi r19, r22, r0 >> 41 */ 0x4c4a7200, /* xor r18, r18, r19 */ 0x404c2000, /* and r19, r0, r1 */ 0x48540000, /* not r21, r0 */ 0x40545500, /* and r21, r21, r2 */ 0x4c4eb300, /* xor r19, r19, r21 */ 0x685192c0, /* rshi r20, r18, r12 >> 192 */ 0x50507400, /* add r20, r20, r3 */ 0x50515480, /* add r20, r20, r10 >> 0 */ 0x6855ab00, /* rshi r21, r11, r13 >> 0 */ 0x50567500, /* add r21, r21, r19 */ 0x5052b400, /* add r20, r20, r21 */ 0x501e8700, /* add r7, r7, r20 */ 0x500e3400, /* add r3, r20, r17 */ 0x68586d40, /* rshi r22, r13, r3 >> 64 */ 0x683c761c, /* rshi r15, r22, r3 >> 28 */ 0x68547622, /* rshi r21, r22, r3 >> 34 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x68547627, /* rshi r21, r22, r3 >> 39 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x40408300, /* and r16, r3, r4 */ 0x4054a300, /* and r21, r3, r5 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x4054a400, /* and r21, r4, r5 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x6845afc0, /* rshi r17, r15, r13 >> 192 */ 0x50461100, /* add r17, r17, r16 */ 0x6858ec40, /* rshi r22, r12, r7 >> 64 */ 0x6848f60e, /* rshi r18, r22, r7 >> 14 */ 0x6854f612, /* rshi r21, r22, r7 >> 18 */ 0x4c4ab200, /* xor r18, r18, r21 */ 0x684cf629, /* rshi r19, r22, r7 >> 41 */ 0x4c4a7200, /* xor r18, r18, r19 */ 0x404c0700, /* and r19, r7, r0 */ 0x4854e000, /* not r21, r7 */ 0x40543500, /* and r21, r21, r1 */ 0x4c4eb300, /* xor r19, r19, r21 */ 0x685192c0, /* rshi r20, r18, r12 >> 192 */ 0x50505400, /* add r20, r20, r2 */ 0x50515488, /* add r20, r20, r10 >> 64 */ 0x6855ab40, /* rshi r21, r11, r13 >> 64 */ 0x50567500, /* add r21, r21, r19 */ 0x5052b400, /* add r20, r20, r21 */ 0x501a8600, /* add r6, r6, r20 */ 0x500a3400, /* add r2, r20, r17 */ 0x68584d40, /* rshi r22, r13, r2 >> 64 */ 0x683c561c, /* rshi r15, r22, r2 >> 28 */ 0x68545622, /* rshi r21, r22, r2 >> 34 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x68545627, /* rshi r21, r22, r2 >> 39 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x40406200, /* and r16, r2, r3 */ 0x40548200, /* and r21, r2, r4 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x40548300, /* and r21, r3, r4 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x6845afc0, /* rshi r17, r15, r13 >> 192 */ 0x50461100, /* add r17, r17, r16 */ 0x6858cc40, /* rshi r22, r12, r6 >> 64 */ 0x6848d60e, /* rshi r18, r22, r6 >> 14 */ 0x6854d612, /* rshi r21, r22, r6 >> 18 */ 0x4c4ab200, /* xor r18, r18, r21 */ 0x684cd629, /* rshi r19, r22, r6 >> 41 */ 0x4c4a7200, /* xor r18, r18, r19 */ 0x404ce600, /* and r19, r6, r7 */ 0x4854c000, /* not r21, r6 */ 0x40541500, /* and r21, r21, r0 */ 0x4c4eb300, /* xor r19, r19, r21 */ 0x685192c0, /* rshi r20, r18, r12 >> 192 */ 0x50503400, /* add r20, r20, r1 */ 0x50515490, /* add r20, r20, r10 >> 128 */ 0x6855ab80, /* rshi r21, r11, r13 >> 128 */ 0x50567500, /* add r21, r21, r19 */ 0x5052b400, /* add r20, r20, r21 */ 0x50168500, /* add r5, r5, r20 */ 0x50063400, /* add r1, r20, r17 */ 0x68582d40, /* rshi r22, r13, r1 >> 64 */ 0x683c361c, /* rshi r15, r22, r1 >> 28 */ 0x68543622, /* rshi r21, r22, r1 >> 34 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x68543627, /* rshi r21, r22, r1 >> 39 */ 0x4c3eaf00, /* xor r15, r15, r21 */ 0x40404100, /* and r16, r1, r2 */ 0x40546100, /* and r21, r1, r3 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x40546200, /* and r21, r2, r3 */ 0x4c42b000, /* xor r16, r16, r21 */ 0x6845afc0, /* rshi r17, r15, r13 >> 192 */ 0x50461100, /* add r17, r17, r16 */ 0x6858ac40, /* rshi r22, r12, r5 >> 64 */ 0x6848b60e, /* rshi r18, r22, r5 >> 14 */ 0x6854b612, /* rshi r21, r22, r5 >> 18 */ 0x4c4ab200, /* xor r18, r18, r21 */ 0x684cb629, /* rshi r19, r22, r5 >> 41 */ 0x4c4a7200, /* xor r18, r18, r19 */ 0x404cc500, /* and r19, r5, r6 */ 0x4854a000, /* not r21, r5 */ 0x4054f500, /* and r21, r21, r7 */ 0x4c4eb300, /* xor r19, r19, r21 */ 0x685192c0, /* rshi r20, r18, r12 >> 192 */ 0x50501400, /* add r20, r20, r0 */ 0x50515498, /* add r20, r20, r10 >> 192 */ 0x6855abc0, /* rshi r21, r11, r13 >> 192 */ 0x50567500, /* add r21, r21, r19 */ 0x5052b400, /* add r20, r20, r21 */ 0x50128400, /* add r4, r4, r20 */ 0x50023400, /* add r0, r20, r17 */ 0x0c000000, /* ret */ /* } */ /* @0x14f: function compress[70] { */ #define CF_compress_adr 335 0xfc000000, /* nop */ 0x4c7fff00, /* xor r31, r31, r31 */ 0x4c000000, /* xor r0, r0, r0 */ 0x4c042100, /* xor r1, r1, r1 */ 0x55000001, /* subi r0, r0, #1 */ 0x55040101, /* subi r1, r1, #1 */ 0x84204100, /* ldi r8, [#8] */ 0x94800800, /* ldlc r8 */ 0x4c3def00, /* xor r15, r15, r15 */ 0x803c000a, /* movi r15.0l, #10 */ 0x95800f00, /* lddmp r15 */ 0x06000039, /* loop *0 ( */ 0x953c0000, /* stdmp r15 */ 0x81bc002a, /* movi r15.3l, #42 */ 0x95800f00, /* lddmp r15 */ 0x08000001, /* call &expandw */ 0x84004000, /* ldi r0, [#0] */ 0x84044020, /* ldi r1, [#1] */ 0x84084040, /* ldi r2, [#2] */ 0x840c4060, /* ldi r3, [#3] */ 0x84104080, /* ldi r4, [#4] */ 0x841440a0, /* ldi r5, [#5] */ 0x841840c0, /* ldi r6, [#6] */ 0x841c40e0, /* ldi r7, [#7] */ 0x4c3def00, /* xor r15, r15, r15 */ 0x803c0060, /* movi r15.0l, #96 */ 0x80bc000a, /* movi r15.1l, #10 */ 0x813c000b, /* movi r15.2l, #11 */ 0x96800f00, /* lddrp r15 */ 0x97800f00, /* ldrfp r15 */ 0x953c0000, /* stdmp r15 */ 0x81bc002a, /* movi r15.3l, #42 */ 0x95800f00, /* lddmp r15 */ 0x4c318c00, /* xor r12, r12, r12 */ 0x4c35ad00, /* xor r13, r13, r13 */ 0x55300c01, /* subi r12, r12, #1 */ 0x55340d01, /* subi r13, r13, #1 */ 0x0500a007, /* loop #10 ( */ 0x8c440800, /* ldc *1, *0++ */ 0x8c081b00, /* ld *2, *3++ */ 0x08000055, /* call &Sha512_a */ 0x8c440800, /* ldc *1, *0++ */ 0x8c081b00, /* ld *2, *3++ */ 0x080000d2, /* call &Sha512_b */ 0xfc000000, /* nop */ /* ) */ 0x843c4000, /* ldi r15, [#0] */ 0x5001e000, /* add r0, r0, r15 */ 0x843c4020, /* ldi r15, [#1] */ 0x5005e100, /* add r1, r1, r15 */ 0x843c4040, /* ldi r15, [#2] */ 0x5009e200, /* add r2, r2, r15 */ 0x843c4060, /* ldi r15, [#3] */ 0x500de300, /* add r3, r3, r15 */ 0x843c4080, /* ldi r15, [#4] */ 0x5011e400, /* add r4, r4, r15 */ 0x843c40a0, /* ldi r15, [#5] */ 0x5015e500, /* add r5, r5, r15 */ 0x843c40c0, /* ldi r15, [#6] */ 0x5019e600, /* add r6, r6, r15 */ 0x843c40e0, /* ldi r15, [#7] */ 0x501de700, /* add r7, r7, r15 */ 0x88004000, /* sti r0, [#0] */ 0x88044020, /* sti r1, [#1] */ 0x88084040, /* sti r2, [#2] */ 0x880c4060, /* sti r3, [#3] */ 0x88104080, /* sti r4, [#4] */ 0x881440a0, /* sti r5, [#5] */ 0x881840c0, /* sti r6, [#6] */ 0x881c40e0, /* sti r7, [#7] */ /* ) */ 0x0c000000, /* ret */ /* } */ }; /* clang-format on */ struct DMEM_sha512 { uint64_t H0[4]; uint64_t H1[4]; uint64_t H2[4]; uint64_t H3[4]; uint64_t H4[4]; uint64_t H5[4]; uint64_t H6[4]; uint64_t H7[4]; uint32_t nblocks; uint32_t unused[2 * 8 - 1]; uint32_t input[4 * 8 * 8]; // dmem[10..41] }; static void copy_words(const void *in, uint32_t *dst, size_t nwords) { const uint32_t *src = (const uint32_t *) in; do { uint32_t w1 = __builtin_bswap32(*src++); uint32_t w2 = __builtin_bswap32(*src++); *dst++ = w2; *dst++ = w1; } while (nwords -= 2); } static void dcrypto_SHA512_setup(void) { dcrypto_imem_load(0, IMEM_dcrypto, ARRAY_SIZE(IMEM_dcrypto)); } static void dcrypto_SHA512_Transform(LITE_SHA512_CTX *ctx, const uint32_t *buf, size_t nwords) { int result = 0; struct DMEM_sha512 *p512 = (struct DMEM_sha512 *) GREG32_ADDR(CRYPTO, DMEM_DUMMY); START_PROFILE(t_transform) /* Pass in H[] */ p512->H0[0] = ctx->state[0]; p512->H1[0] = ctx->state[1]; p512->H2[0] = ctx->state[2]; p512->H3[0] = ctx->state[3]; p512->H4[0] = ctx->state[4]; p512->H5[0] = ctx->state[5]; p512->H6[0] = ctx->state[6]; p512->H7[0] = ctx->state[7]; p512->nblocks = nwords / 32; /* Pass in buf[] */ copy_words(buf, p512->input, nwords); START_PROFILE(t_dcrypto) result |= dcrypto_call(CF_compress_adr); END_PROFILE(t_dcrypto) /* Retrieve new H[] */ ctx->state[0] = p512->H0[0]; ctx->state[1] = p512->H1[0]; ctx->state[2] = p512->H2[0]; ctx->state[3] = p512->H3[0]; ctx->state[4] = p512->H4[0]; ctx->state[5] = p512->H5[0]; ctx->state[6] = p512->H6[0]; ctx->state[7] = p512->H7[0]; /* TODO: errno or such to capture errors */ (void) (result == 0); END_PROFILE(t_transform) } static void dcrypto_SHA512_update(LITE_SHA512_CTX *ctx, const void *data, size_t len) { int i = (int) (ctx->count & (sizeof(ctx->buf) - 1)); const uint8_t *p = (const uint8_t *) data; uint8_t *d = &ctx->buf[i]; ctx->count += len; dcrypto_init_and_lock(); dcrypto_SHA512_setup(); /* Take fast path for 32-bit aligned 1KB inputs */ if (i == 0 && len == 1024 && (((intptr_t) data) & 3) == 0) { dcrypto_SHA512_Transform(ctx, (const uint32_t *) data, 8 * 32); } else { if (len <= sizeof(ctx->buf) - i) { memcpy(d, p, len); if (len == sizeof(ctx->buf) - i) { dcrypto_SHA512_Transform( ctx, (uint32_t *) (ctx->buf), 32); } } else { memcpy(d, p, sizeof(ctx->buf) - i); dcrypto_SHA512_Transform(ctx, (uint32_t *) (ctx->buf), 32); d = ctx->buf; len -= (sizeof(ctx->buf) - i); p += (sizeof(ctx->buf) - i); while (len >= sizeof(ctx->buf)) { memcpy(d, p, sizeof(ctx->buf)); p += sizeof(ctx->buf); len -= sizeof(ctx->buf); dcrypto_SHA512_Transform( ctx, (uint32_t *) (ctx->buf), 32); } /* Leave remainder in ctx->buf */ memcpy(d, p, len); } } dcrypto_unlock(); } static const uint8_t *dcrypto_SHA512_final(LITE_SHA512_CTX *ctx) { uint64_t cnt = ctx->count * 8; int i = (int) (ctx->count & (sizeof(ctx->buf) - 1)); uint8_t *p = &ctx->buf[i]; *p++ = 0x80; i++; dcrypto_init_and_lock(); dcrypto_SHA512_setup(); if (i > sizeof(ctx->buf) - 16) { memset(p, 0, sizeof(ctx->buf) - i); dcrypto_SHA512_Transform(ctx, (uint32_t *) (ctx->buf), 32); i = 0; p = ctx->buf; } memset(p, 0, sizeof(ctx->buf) - 8 - i); p += sizeof(ctx->buf) - 8 - i; for (i = 0; i < 8; ++i) { uint8_t tmp = (uint8_t)(cnt >> 56); cnt <<= 8; *p++ = tmp; } dcrypto_SHA512_Transform(ctx, (uint32_t *) (ctx->buf), 32); p = ctx->buf; for (i = 0; i < 8; i++) { uint64_t tmp = ctx->state[i]; *p++ = (uint8_t)(tmp >> 56); *p++ = (uint8_t)(tmp >> 48); *p++ = (uint8_t)(tmp >> 40); *p++ = (uint8_t)(tmp >> 32); *p++ = (uint8_t)(tmp >> 24); *p++ = (uint8_t)(tmp >> 16); *p++ = (uint8_t)(tmp >> 8); *p++ = (uint8_t)(tmp >> 0); } dcrypto_unlock(); return ctx->buf; } const uint8_t *DCRYPTO_SHA512_hash(const void *data, size_t len, uint8_t *digest) { LITE_SHA512_CTX ctx; DCRYPTO_SHA512_init(&ctx); dcrypto_SHA512_update(&ctx, data, len); memcpy(digest, dcrypto_SHA512_final(&ctx), SHA512_DIGEST_SIZE); return digest; } static const HASH_VTAB dcrypto_SHA512_VTAB = { DCRYPTO_SHA512_init, dcrypto_SHA512_update, dcrypto_SHA512_final, DCRYPTO_SHA512_hash, SHA512_DIGEST_SIZE}; void DCRYPTO_SHA512_init(LITE_SHA512_CTX *ctx) { SHA512_init(ctx); ctx->f = &dcrypto_SHA512_VTAB; } #ifdef CRYPTO_TEST_SETUP static uint32_t msg[256]; // 1KB static int msg_len; static int msg_loops; static LITE_SHA512_CTX sw; static LITE_SHA512_CTX hw; static const uint8_t *sw_digest; static const uint8_t *hw_digest; static uint32_t t_sw; static uint32_t t_hw; static void run_sha512_cmd(void) { int i; t_transform = 0; t_dcrypto = 0; t_sw = 0; t_hw = 0; START_PROFILE(t_sw) SHA512_init(&sw); for (i = 0; i < msg_loops; ++i) { HASH_update(&sw, msg, msg_len); } sw_digest = HASH_final(&sw); END_PROFILE(t_sw) START_PROFILE(t_hw) DCRYPTO_SHA512_init(&hw); for (i = 0; i < msg_loops; ++i) { HASH_update(&hw, msg, msg_len); } hw_digest = HASH_final(&hw); END_PROFILE(t_hw) ccprintf("sw(%u):\n", t_sw); for (i = 0; i < 64; ++i) ccprintf("%02x", sw_digest[i]); ccprintf("\n"); ccprintf("hw(%u/%u/%u):\n", t_hw, t_transform, t_dcrypto); for (i = 0; i < 64; ++i) ccprintf("%02x", hw_digest[i]); ccprintf("\n"); task_set_event(TASK_ID_CONSOLE, TASK_EVENT_CUSTOM_BIT(0), 0); } DECLARE_DEFERRED(run_sha512_cmd); static int cmd_sha512_bench(int argc, char *argv[]) { const int max_time = 1000000; uint32_t events; memset(msg, '!', sizeof(msg)); if (argc > 1) { msg_loops = 1; msg_len = strlen(argv[1]); memcpy(msg, argv[1], msg_len); } else { msg_loops = 64; // benchmark 64K msg_len = sizeof(msg); } hook_call_deferred(&run_sha512_cmd_data, 0); ccprintf("Will wait up to %d ms\n", (max_time + 500) / 1000); events = task_wait_event_mask(TASK_EVENT_CUSTOM_BIT(0), max_time); if (!(events & TASK_EVENT_CUSTOM_BIT(0))) { ccprintf("Timed out, you might want to reboot...\n"); return EC_ERROR_TIMEOUT; } return EC_SUCCESS; } DECLARE_SAFE_CONSOLE_COMMAND(sha512_bench, cmd_sha512_bench, NULL, NULL); static void run_sha512_test(void) { int i; for (i = 0; i < 129; ++i) { memset(msg, i, i); SHA512_init(&sw); HASH_update(&sw, msg, i); sw_digest = HASH_final(&sw); DCRYPTO_SHA512_init(&hw); HASH_update(&hw, msg, i); hw_digest = HASH_final(&hw); if (memcmp(sw_digest, hw_digest, SHA512_DIGEST_SIZE) != 0) { ccprintf("sha512 self-test fail at %d!\n", i); cflush(); } } ccprintf("sha512 self-test PASS!\n"); task_set_event(TASK_ID_CONSOLE, TASK_EVENT_CUSTOM_BIT(0), 0); } DECLARE_DEFERRED(run_sha512_test); static int cmd_sha512_test(int argc, char *argv[]) { hook_call_deferred(&run_sha512_test_data, 0); task_wait_event_mask(TASK_EVENT_CUSTOM_BIT(0), 1000000); return EC_SUCCESS; } DECLARE_SAFE_CONSOLE_COMMAND(sha512_test, cmd_sha512_test, NULL, NULL); #endif /* CRYPTO_TEST_SETUP */
//---------------------------------------------------- // file: D3DUtils.h //---------------------------------------------------- #ifndef D3DUtilsH #define D3DUtilsH #include "..\..\Include\xrRender\DrawUtils.h" //---------------------------------------------------- #ifdef _EDITOR # define DU_DRAW_DIP Device.DIP # define DU_DRAW_DP Device.DP #else # define DU_DRAW_DIP RCache.dbg_DIP # define DU_DRAW_DP RCache.dbg_DP #endif struct SPrimitiveBuffer{ ref_geom pGeom; u32 v_cnt; u32 i_cnt; D3DPRIMITIVETYPE p_type; u32 p_cnt; typedef fastdelegate::FastDelegate0<> TOnRender; TOnRender OnRender; void xr_stdcall RenderDIP() {DU_DRAW_DIP(p_type,pGeom,0,0,v_cnt,0,p_cnt);} void xr_stdcall RenderDP() {DU_DRAW_DP (p_type,pGeom,0,p_cnt);} public: SPrimitiveBuffer():OnRender(0),pGeom(0){;} void CreateFromData(D3DPRIMITIVETYPE _pt, u32 _p_cnt, u32 FVF, LPVOID vertices, u32 _v_cnt, u16* indices=0, u32 _i_cnt=0); void Destroy(); void Render(){OnRender();} }; //---------------------------------------------------- // Utilities //---------------------------------------------------- class ECORE_API CDrawUtilities: public CDUInterface, public pureRender{ SPrimitiveBuffer m_SolidCone; SPrimitiveBuffer m_WireCone; SPrimitiveBuffer m_SolidSphere; SPrimitiveBuffer m_WireSphere; SPrimitiveBuffer m_SolidSpherePart; SPrimitiveBuffer m_WireSpherePart; SPrimitiveBuffer m_SolidCylinder; SPrimitiveBuffer m_WireCylinder; SPrimitiveBuffer m_SolidBox; SPrimitiveBuffer m_WireBox; CGameFont* m_Font; public: ref_geom vs_L; ref_geom vs_TL; ref_geom vs_LIT; protected: FVF::L* m_DD_pv; FVF::L* m_DD_pv_start; u32 m_DD_base; BOOL m_DD_wire; void DD_DrawFace_flush (BOOL try_again); public: void DD_DrawFace_begin (BOOL bWire); void DD_DrawFace_push (const Fvector& p0, const Fvector& p1, const Fvector& p2, u32 clr); void DD_DrawFace_end (); public: CDrawUtilities() { vs_L = 0; vs_TL = 0; vs_LIT = 0; m_DD_pv = 0; m_DD_pv_start = 0; m_DD_base = 0; m_Font = 0; } void OnDeviceCreate (); virtual void __stdcall OnDeviceDestroy(); void UpdateGrid(int number_of_cell, float square_size, int subdiv=10); //---------------------------------------------------- virtual void __stdcall DrawCross(const Fvector& p, float szx1, float szy1, float szz1, float szx2, float szy2, float szz2, u32 clr, BOOL bRot45=false); virtual void __stdcall DrawCross(const Fvector& p, float sz, u32 clr, BOOL bRot45=false){ DrawCross(p, sz,sz,sz, sz,sz,sz, clr, bRot45); } virtual void __stdcall DrawEntity(u32 clr, ref_shader s); virtual void __stdcall DrawFlag(const Fvector& p, float heading, float height, float sz, float sz_fl, u32 clr, BOOL bDrawEntity); virtual void __stdcall DrawRomboid(const Fvector& p, float radius, u32 clr); virtual void __stdcall DrawJoint(const Fvector& p, float radius, u32 clr); virtual void __stdcall DrawSpotLight(const Fvector& p, const Fvector& d, float range, float phi, u32 clr); virtual void __stdcall DrawDirectionalLight(const Fvector& p, const Fvector& d, float radius, float range, u32 clr); virtual void __stdcall DrawPointLight(const Fvector& p, float radius, u32 clr); virtual void __stdcall DrawSound(const Fvector& p, float radius, u32 clr); virtual void __stdcall DrawLineSphere(const Fvector& p, float radius, u32 clr, BOOL bCross); virtual void __stdcall dbgDrawPlacement(const Fvector& p, int sz, u32 clr, LPCSTR caption=0, u32 clr_font=0xffffffff); virtual void __stdcall dbgDrawVert(const Fvector& p0, u32 clr, LPCSTR caption=0); virtual void __stdcall dbgDrawEdge(const Fvector& p0, const Fvector& p1, u32 clr, LPCSTR caption=0); virtual void __stdcall dbgDrawFace(const Fvector& p0, const Fvector& p1, const Fvector& p2, u32 clr, LPCSTR caption=0); virtual void __stdcall DrawFace(const Fvector& p0, const Fvector& p1, const Fvector& p2, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); virtual void __stdcall DrawLine(const Fvector& p0, const Fvector& p1, u32 clr); virtual void __stdcall DrawLink(const Fvector& p0, const Fvector& p1, float sz, u32 clr); IC virtual void __stdcall DrawFaceNormal(const Fvector& p0, const Fvector& p1, const Fvector& p2, float size, u32 clr){ Fvector N,C,P; N.mknormal(p0,p1,p2); C.set(p0);C.add(p1);C.add(p2);C.div(3); P.mad(C,N,size); DrawLine(C,P,clr);} IC virtual void __stdcall DrawFaceNormal(const Fvector* p, float size, u32 clr){DrawFaceNormal(p[0],p[1],p[2],size,clr);} IC virtual void __stdcall DrawFaceNormal(const Fvector& C, const Fvector& N, float size, u32 clr){ Fvector P; P.mad(C,N,size);DrawLine(C,P,clr);} virtual void __stdcall DrawSelectionBox(const Fvector& center, const Fvector& size, u32* c=0); IC virtual void __stdcall DrawSelectionBox(const Fbox& box, u32* c=0){ Fvector S,C; box.getsize(S); box.getcenter(C); DrawSelectionBox(C,S,c); } virtual void __stdcall DrawIdentSphere (BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w); virtual void __stdcall DrawIdentSpherePart(BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w); virtual void __stdcall DrawIdentCone (BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w); virtual void __stdcall DrawIdentCylinder (BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w); virtual void __stdcall DrawIdentBox (BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w); virtual void __stdcall DrawBox (const Fvector& offs, const Fvector& Size, BOOL bSolid, BOOL bWire, u32 clr_s, u32 clr_w); virtual void __stdcall DrawAABB (const Fvector& p0, const Fvector& p1, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); virtual void __stdcall DrawAABB (const Fmatrix& parent, const Fvector& center, const Fvector& size, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); virtual void __stdcall DrawOBB (const Fmatrix& parent, const Fobb& box, u32 clr_s, u32 clr_w); virtual void __stdcall DrawSphere (const Fmatrix& parent, const Fvector& center, float radius, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); virtual void __stdcall DrawSphere (const Fmatrix& parent, const Fsphere& S, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire){DrawSphere(parent,S.P,S.R,clr_s,clr_w,bSolid,bWire);} virtual void __stdcall DrawCylinder(const Fmatrix& parent, const Fvector& center, const Fvector& dir, float height, float radius, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); virtual void __stdcall DrawCone (const Fmatrix& parent, const Fvector& apex, const Fvector& dir, float height, float radius, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); virtual void __stdcall DrawPlane (const Fvector& center, const Fvector2& scale, const Fvector& rotate, u32 clr_s, u32 clr_w, BOOL bCull, BOOL bSolid, BOOL bWire); virtual void __stdcall DrawPlane (const Fvector& p, const Fvector& n, const Fvector2& scale, u32 clr_s, u32 clr_w, BOOL bCull, BOOL bSolid, BOOL bWire); virtual void __stdcall DrawRectangle(const Fvector& o, const Fvector& u, const Fvector& v, u32 clr_s, u32 clr_w, BOOL bSolid, BOOL bWire); virtual void __stdcall DrawGrid (); virtual void __stdcall DrawPivot (const Fvector& pos, float sz=5.f); virtual void __stdcall DrawAxis (const Fmatrix& T); virtual void __stdcall DrawObjectAxis(const Fmatrix& T, float sz, BOOL sel); virtual void __stdcall DrawSelectionRect(const Ivector2& m_SelStart, const Ivector2& m_SelEnd); virtual void __stdcall DrawPrimitiveL(D3DPRIMITIVETYPE pt, u32 pc, Fvector* vertices, int vc, u32 color, BOOL bCull, BOOL bCycle); virtual void __stdcall DrawPrimitiveTL(D3DPRIMITIVETYPE pt, u32 pc, FVF::TL* vertices, int vc, BOOL bCull, BOOL bCycle); virtual void __stdcall DrawPrimitiveLIT(D3DPRIMITIVETYPE pt, u32 pc, FVF::LIT* vertices, int vc, BOOL bCull, BOOL bCycle); virtual void __stdcall OutText (const Fvector& pos, LPCSTR text, u32 color=0xFF000000, u32 shadow_color=0xFF909090); virtual void OnRender (); }; extern ECORE_API CDrawUtilities DUImpl; //---------------------------------------------------- #endif /*_INCDEF_D3DUtils_H_*/
<reponame>wphicks/night-adder #include <stdlib.h> #include "vector.h" #include "particle.h" void init_Particle(Particle * part, double mass, double radius, double restitution) { double zero[VECDIM]; int i; for (i=0; i < VECDIM; ++i) { zero[i] = 0; } if(mass > 0) { part->inv_mass = 1/mass; } else { part->inv_mass = 0; } part->radius = radius; part->restitution = restitution; init_Vec(&part->position, zero); init_Vec(&part->prev_position, zero); init_Vec(&part->velocity, zero); } void update_Particle_position(Particle * cur_part, double dt) { copy_Vec(&(cur_part->position), &(cur_part->prev_position)); Vec update_vec = cur_part->velocity; multiply_Vec(&update_vec, dt, &update_vec); sum_Vec(&(cur_part->position), &update_vec, &(cur_part->position)); } void interpolate_Particle_position( Particle * part, double alpha, Vec * result) { Vec tmp1; Vec tmp2; multiply_Vec(&(part->prev_position), alpha, &tmp1); multiply_Vec(&(part->position), 1.0 - alpha, &tmp2); sum_Vec(&tmp1, &tmp2, result); }
#ifndef _DEVICE_H_ #define _DEVICE_H_ #ifdef __cplusplus extern "C" { #endif #include "structures.h" static struct ext2_super_block es; static struct ext2_group_desc gd; static int size_of_block; static int size_of_fragment; int device_open(const char *path); void device_close(); void device_flush(); #ifdef __cplusplus } #endif #endif
#if __has_include(<GPUImage/GPUImageFramework.h>) #import <GPUImage/GPUImageFilter.h> #else #import "GPUImageFilter.h" #endif @interface GPUImageLuminanceRangeFilter : GPUImageFilter { GLint rangeReductionUniform; } /** The degree to reduce the luminance range, from 0.0 to 1.0. Default is 0.6. */ @property(readwrite, nonatomic) CGFloat rangeReductionFactor; @end
<filename>groups/bsl/bsls/bsls_systemclocktype.h // bsls_systemclocktype.h -*-C++-*- #ifndef INCLUDED_BSLS_SYSTEMCLOCKTYPE #define INCLUDED_BSLS_SYSTEMCLOCKTYPE #ifndef INCLUDED_BSLS_IDENT #include <bsls_ident.h> #endif BSLS_IDENT("$Id: $") //@PURPOSE: Enumerate the set of system clock types. // //@CLASSES: // bsls::SystemClockType: namespace for a clock type 'enum' // //@DESCRIPTION: This component provides a namespace for the 'enum' type // 'bsls::SystemClockType::Enum', which enumerates the set of system clock // types. A 'bsls::SystemClockType' is particularly important when providing // time-out values to synchronization methods where those time-outs must be // consistent in environments where the system clocks may be changed. // ///Enumerators ///----------- //.. // Name Description // ----------- ------------------------------------------------------------- // e_REALTIME System clock that returns the current wall time maintained by // the system, and which is affected by adjustments to the // system's clock (i.e., time values returned may jump // "forwards" and "backwards" as the current time-of-day is // changed on the system). // // e_MONOTONIC System clock that returns the elapsed time since some // unspecified starting point in the past. The returned values // are monotonically non-decreasing, and are generally not // affected by changes to the system time. //.. // ///USAGE ///----- // This section illustrates intended use of this component. // ///Example 1: Basic Syntax ///- - - - - - - - - - - - // The following snippets of code provide a simple illustration of using // 'bsls::SystemClockType'. // // First, we create a variable 'value' of type 'bsls::SystemClockType::Enum' // and initialize it with the enumerator value // 'bsls::SystemClockType::e_MONOTONIC': //.. // bsls::SystemClockType::Enum value = bsls::SystemClockType::e_MONOTONIC; //.. // Now, we store the address of its ASCII representation in a pointer variable, // 'asciiValue', of type 'const char *': //.. // const char *asciiValue = bsls::SystemClockType::toAscii(value); //.. // Finally, we verify the value of 'asciiValue': //.. // assert(0 == strcmp(asciiValue, "MONOTONIC")); //.. namespace BloombergLP { namespace bsls { // ====================== // struct SystemClockType // ====================== struct SystemClockType { // This 'struct' provides a namespace for enumerating the set of system // clock type for use in distinguishing which system clock to use for // measuring time. See 'Enum' in the TYPES sub-section for details. public: // TYPES enum Enum { // Enumeration clock type values. e_REALTIME, // System clock that returns the current wall time // maintained by the system, and which is affected by // adjustments to the system's clock (i.e., time values // returned may jump "forwards" and "backwards" as the // current time-of-day is changed on the system). e_MONOTONIC // System clock that returns the elapsed time since some // unspecified starting point in the past. The returned // values are monotonically non-decreasing, and are // generally not affected by changes to the system time. }; public: static const char *toAscii(SystemClockType::Enum value); // Return the non-modifiable string representation corresponding to the // specified enumeration 'value', if it exists, and a unique (error) // string otherwise. The string representation of 'value' matches its // corresponding enumerator name with the "e_" prefix elided. For // example: //.. // bsl::cout << SystemClockType::toAscii(SystemClockType::e_REALTIME); //.. // will print the following on standard output: //.. // REALTIME //.. // Note that specifying a 'value' that does not match any of the // enumerators will result in a string representation that is distinct // from any of those corresponding to the enumerators, but is otherwise // unspecified. }; } // close package namespace } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright 2014 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
// Copyright (C) 2008-2011 JWmicro. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the JWmicro 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 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. /// @defgroup geWizES_data_avltree egwAVLTree /// @ingroup geWizES_data /// Height-Balanced AVL Tree. /// @{ /// @file egwAVLTree.h /// Height-Balanced AVL Tree Interface. #import "egwDataTypes.h" // !!!: ***** Initialization ***** /// AVL Tree Initialization Routine. /// Initializes AVL tree with provided parameters. /// @note Elements are tightly packed without padding after the link pointer data section. /// @param [out] tree_out AVL tree output of initialization. /// @param [in] funcs_in Data routine functions (contents copy-over, may be NULL for default routines). /// @param [in] elmSize_in Element size (bytes). /// @param [in] flags_in Tree attribute flags (EGW_TREE_FLG_*). /// @return @a tree_out (for nesting), otherwise NULL if failure initializing. egwAVLTree* egwAVLTreeInit(egwAVLTree* tree_out, egwDataFuncs* funcs_in, EGWuint elmSize_in, EGWuint flags_in); /// AVL Tree Copy Routine. /// Initializes AVL tree from deep copy of another. /// @param [in] tree_in AVL tree input structure. /// @param [out] tree_out AVL tree output of copy. /// @return @a tree_out (for nesting), otherwise NULL if failure copying. egwAVLTree* egwAVLTreeCopy(const egwAVLTree* tree_in, egwAVLTree* tree_out); /// AVL Tree Free Routine. /// Frees the contents of the AVL tree. /// @param [in,out] tree_inout AVL tree input/output structure. /// @return @a tree_inout (for nesting), otherwise NULL if failure free'ing. egwAVLTree* egwAVLTreeFree(egwAVLTree* tree_inout); // !!!: ***** Addition ***** /// AVL Tree Add Routine. /// Adds an element into the tree at its sorted postion at O(log n) insertion cost. /// @param [in,out] tree_inout AVL tree input/output structure. /// @param [in] data_in Element data input buffer (contents copy-over, may be NULL for zero'ed data segment). /// @return 1 if element was successfully added, otherwise 0. EGWint egwAVLTreeAdd(egwAVLTree* tree_inout, const EGWbyte* data_in); // !!!: ***** Removal ***** /// AVL Tree Remove Routine. /// Removes an element node from the AVL tree at O(log n) deletion cost. /// @param [in,out] tree_inout AVL tree input/output structure. /// @param [in,out] node_inout Tree node element that should be removed. /// @return 1 if element was successfully removed, otherwise 0. EGWint egwAVLTreeRemove(egwAVLTree* tree_inout, egwAVLTreeNode* node_inout); /// AVL Tree Remove Any Routine. /// Removes any matching element from the AVL tree at O(n log n) transversal cost and O(log n) deletion cost. /// @param [in,out] tree_inout AVL tree input/output structure. /// @param [in] data_in Element data input buffer to match against. /// @return Number of elements removed. EGWuint egwAVLTreeRemoveAny(egwAVLTree* tree_inout, const EGWbyte* data_in); /// AVL Tree Remove All Routine. /// Removes all elements from the AVL tree at O(n) transversal cost (if needed) and O(1) deletion cost. /// @param [in,out] tree_inout AVL tree input/output structure. /// @return 1 if all elements were successfully removed, otherwise 0. EGWint egwAVLTreeRemoveAll(egwAVLTree* tree_inout); // !!!: ***** Fetching ***** /// AVL Tree Get Element Routine. /// Copies the element contents from the AVL tree at the specified node into the output buffer at O(1) copy cost. /// @note This routine does a simple memory copy-over - ownership issues fall to the responsibility of the code using this routine. /// @param [in] tree_in AVL tree input structure. /// @param [in] node_in Tree node to which element data should be copied from. /// @param [out] data_out Element data output buffer (contents copy-over). void egwAVLTreeGetElement(const egwAVLTree* tree_in, const egwAVLTreeNode* node_in, EGWbyte* data_out); /// AVL Tree Element Pointer Routine. /// Returns the element data buffer pointer from the AVL tree at the specified tree node. /// @param [in] node_in Tree node to which element data pointer should be given from. /// @return Element data buffer pointer. EGWbyte* egwAVLTreeElementPtr(const egwAVLTreeNode* node_in); /// AVL Tree Node Pointer Routine. /// Returns the tree node pointer from the AVL tree given the specified element data buffer pointer. /// @param [in] data_in Element data input buffer to which tree node pointer should be given from. /// @return Tree node pointer. egwAVLTreeNode* egwAVLTreeNodePtr(const EGWbyte* data_in); // !!!: ***** Searching ***** /// AVL Tree Find Routine. /// Attempts to find the tree node pointer of an element in the AVL tree given the provided parameters at O(log n) transversal cost. /// @param [in] tree_in AVL tree input structure. /// @param [in] data_in Element data input buffer to match against. /// @return Element index if search successful, -1 otherwise. egwAVLTreeNode* egwAVLTreeFind(const egwAVLTree* tree_in, const EGWbyte* data_in); /// AVL Tree Contains Routine. /// Attempts to find the existence of an element in the AVL tree given the provided parameters at O(log n) transversal cost. /// @param [in] tree_in AVL tree input structure. /// @param [in] data_in Element data input buffer to match against. /// @return 1 if search successful, otherwise 0. EGWint egwAVLTreeContains(const egwAVLTree* tree_in, const EGWbyte* data_in); /// AVL Tree Occurances Routine. /// Attempts to find the number of occurances of an element in the AVL tree given the provided parameters at O(log n) transversal cost. /// @param [in] tree_in AVL tree input structure. /// @param [in] data_in Element data input buffer to match against. /// @return Number of element occurances. EGWuint egwAVLTreeOccurances(const egwAVLTree* tree_in, const EGWbyte* data_in); // !!!: ***** Sorting ***** /// AVL Tree Resort Routine. /// Attempts to resort the element of the AVL tree at the specified tree node at O(n) time cost. /// @param [in,out] tree_inout AVL tree input/output structure. /// @param [in,out] node_inout Tree node to which to resort at. /// @return 1 if any swaps were performed, otherwise 0. EGWint egwAVLTreeResortElement(egwAVLTree* tree_inout, egwAVLTreeNode* node_inout); // !!!: ***** Enumerating ***** /// AVL Tree Enumerate Start Routine. /// Attempts to start an enumeration of the AVL tree given the provided iteration mode. /// @note No mechanism is provided to ensure the data contents are not modified while being enumerated - it is left up to the user to determine what effects should result, if any. /// @note Level-order iteration mode allocates a temporary storage array in the iterator structure that must be manually free'd if iteration is not allowed to finished. /// @param [in] tree_in AVL tree input structure. /// @param [in] iterMode_in Iteration mode (EGW_ITERATE_MODE_*). /// @param [out] iter_out Iterator output structure. /// @return 1 if enumeration start successful, otherwise 0 if empty or invalid iteration mode. EGWint egwAVLTreeEnumerateStart(const egwAVLTree* tree_in, EGWuint iterMode_in, egwAVLTreeIter* iter_out); /// AVL Tree Enumeration Get Next Routine. /// Copies the next enumerated element's contents from the AVL tree into the output buffer at O(1) transversal cost and O(1) copy cost. /// @note This routine does a simple memory copy-over - ownership issues fall to the responsibility of the code using this routine. /// @param [in,out] iter_inout Iterator input/output structure. /// @param [out] data_out Element data output buffer (contents copy-over). /// @return 1 if enumeration of next element successful, otherwise 0 if at end of enumeration. EGWint egwAVLTreeEnumerateGetNext(egwAVLTreeIter* iter_inout, EGWbyte* data_out); /// AVL Tree Enumeration Next Pointer Routine. /// Returns the next enumerated element's data buffer pointer from the AVL tree at O(1) transversal cost. /// @param [in,out] iter_inout Iterator input/output structure. /// @return Element data buffer pointer to the next enumerated element, otherwise NULL if at end of enumeration. EGWbyte* egwAVLTreeEnumerateNextPtr(egwAVLTreeIter* iter_inout); /// @}
<gh_stars>0 // // PerkScene.h // PixelSnipe // // Created by <NAME> on 1/12/11. // Copyright 2011 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> #import "cocos2d.h" #import "AppDelegate.h" @class Perk,JDMenuItem; @interface PerkScene : CCScene {} @end @interface PerkLayer : CCLayer { CCLabelTTF *gold,*name,*description,*instructions,*pButton,*slot1Text,*slot2Text,*slot3Text; CCSprite *preview,*slot1,*slot2,*slot3; int selected,currentPage,glowInt; CCLabelTTF *pageLabel; Perk *pk1; JDMenuItem *moreButton; } -(void)showInfo: (int) i; -(void)loadPerks; @end
/** * Напишите программу для сложения и вычитания целочисленных векторов. Программа считывает знак операции + или -. Затем считывает количество элементов в векторах, затем элементы первого и второго векторов. Программа выводит элементы результирующего вектора через пробел. Если операцию провести невозможно, выведите error. */ #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> void input_array( long long* buffer,int n){ for (int i=0;i<n;i++){ long long u; int check_u = scanf("%lld",&u); if ( check_u == 1) { buffer[i] = u; }else{ printf("error"); exit(0); } } } void print(long long* buffer,int n){ for (int i=0;i<n;i++){ printf("%lld ",buffer[i]); } } void operation(int znak,int n, long long* vec1 , long long* vec2){ long long* out = calloc(n, sizeof(long long)); int plus = 1; int minus = 0; if( znak == plus){ for (int i=0;i<n;i++){ out[i] = vec1[i]+vec2[i]; } print(out,n); return; }else if (znak == minus){ for (int i=0;i<n;i++){ out[i] = vec1[i]-vec2[i]; } print(out,n); return; } printf("error"); exit(0); } int main(){ char znak; scanf("%s",&znak); int n; scanf("%d",&n); long long buff1[n],buff2[n]; input_array(buff1,n); input_array(buff2,n); int g; if (znak == '+'){ g = 1; }else if (znak =='-'){ g = 0; }else{ printf("error"); exit(0); } operation(g, n, buff1, buff2); return 0; }
<reponame>sspony/oop244<filename>milestones/milestone5/WPlanner.h<gh_stars>0 #ifndef ICT_WPlanner_H__ #define ICT_WPlanner_H__ #include "Good.h" namespace ict { class WPlanner { private: char filename_[256]; // holds the name of the text file that stores the Goods' information Good* items_[MAX_NO_RECS]; // an array of pointers to Good objects std::fstream datafile_; // an instance of an fstream class that refers to a file int noOfItems_; // holds the number of Goods pointed to by the items_ array int menu(); void loadRecs(); void saveRecs(); void listItems()const; int SearchItems(const char* sku)const; void updateQty(); void addItem(bool isCustomMade); void deleteItem(); void getSku(char* sku); public: WPlanner(const char* filename); int run(); //Copy and assignment prevention goes here: WPlanner(const WPlanner& WP) = delete; WPlanner& operator=(const WPlanner& WP) = delete; }; } #endif
#include "modular_sim.h" // http://serbanology.com/show_article.php?art=A%20Bitwise%20Convolution%20Tutorial // https://csacademy.com/blog/fast-fourier-transform-and-variations-of-it // SNIPPETS_START fwht template <typename T=mint> struct Boly : vector<T> { using vector<T>::vector; Boly() {} Boly(initializer_list<T> list) : vector<T>(list) {} }; template <typename T=mint> inline Boly<T>& fwht(Boly<T>& a, bool is_inv=false) { int n = a.size(); assert((n&(n-1)) == 0); if (is_inv) { T i_n = T(1)/n; for (int i = 0; i < n; i++) { a[i] *= i_n; } } for (int m = 1; m < n; m<<=1) { int l = m<<1; for (int i = 0; i < n; i+=l) { for (int j = 0; j < m; j++) { T x = a[i+j]; T y = a[i+j+m]; a[i+j] = x + y; a[i+j+m] = x - y; } } } return a; } // 0 1 // 1 1 // verified by zeta. check /transform/fast_superset_convolution_join template <typename T> inline Boly<T>& and_fwht(Boly<T>& a, bool is_inv=false) { int n = a.size(); assert((n&(n-1)) == 0); for (int m = 1; m < n; m<<=1) { int l = m<<1; for (int i = 0; i < n; i+=l) { for (int j = 0; j < m; j++) { T x = a[i+j]; T y = a[i+j+m]; if (!is_inv) { a[i+j] = y; a[i+j+m] = x + y; } else { a[i+j] = -x + y; a[i+j+m] = x; } } } } return a; } // 1 1 // 1 0 // verified by zeta. check /transform/fast_subset_convolution_union template <typename T> inline Boly<T>& or_fwht(Boly<T>& a, bool is_inv=false) { int n = a.size(); assert((n&(n-1)) == 0); for (int m = 1; m < n; m<<=1) { int l = m<<1; for (int i = 0; i < n; i+=l) { for (int j = 0; j < m; j++) { T x = a[i+j]; T y = a[i+j+m]; if (!is_inv) { a[i+j] = x + y; a[i+j+m] = x; } else { a[i+j] = y; a[i+j+m] = x - y; } } } } return a; } template <typename T=mint> Boly<T>& operator*=(Boly<T>& a, const Boly<T>& _b) { int n = max(a.size(), _b.size()); int _n = 1 << (31 - __builtin_clz(n)); if (_n < n) n = _n<<1; auto b = _b; a.resize(n); b.resize(n); fwht(a); fwht(b); for (int i = 0; i < n; i++) { a[i] *= b[i]; } return fwht(a, true); } // note solution could many, (1,1,...,1) * b = 0, if \sum b = 0 template <typename T=mint> Boly<T>& operator/=(Boly<T>& a, const Boly<T>& _b) { int n = max(a.size(), _b.size()); int _n = 1 << (31 - __builtin_clz(n)); if (_n < n) n = _n<<1; auto b = _b; a.resize(n); b.resize(n); fwht(a); fwht(b); for (int i = 0; i < n; i++) { a[i] /= b[i]; } return fwht(a, true); } template <typename T=mint> inline Boly<T> operator*(const Boly<T>& a, const Boly<T>& _b) { Boly<T> res(a); return res *= _b; } template <typename T=mint> inline Boly<T> operator/(const Boly<T>& a, const Boly<T>& _b) { Boly<T> res(a); return res /= _b; } using boly=Boly<mint>; // when pow note H(A*....k) = HA....k // when convo multi, H(ABCD...) = HA HB HC HD... // SNIPPETS_END
/* * Copyright (C) 2017 XRADIO TECHNOLOGY CO., LTD. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * 3. Neither the name of XRADIO TECHNOLOGY CO., LTD. nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/unistd.h> #include "hal/soc/soc.h" #include "hal/soc/sd.h" #include "driver/chip/hal_def.h" #include "driver/chip/sdmmc/hal_sdhost.h" #include "driver/chip/sdmmc/sdmmc.h" static struct mmc_card card; static hal_sd_info_t sd_info; static int sd_initialize = 0; /**@brief Initialises a sd interface * * @param sd : the interface which should be initialised * @param config : sd configuration structure * * @return 0 : on success. * @return EIO : if an error occurred with any step */ int32_t hal_sd_init(sd_dev_t *sd) { int32_t ret; SDC_InitTypeDef sdc_param = {0}; if (!sd_initialize) { memset(&card, 0, sizeof(struct mmc_card)); memset(&sd_info, 0, sizeof(hal_sd_info_t)); sd->port = 0; HAL_SDC_Init(sd->port, &sdc_param); ret = mmc_rescan(&card, sd->port); if (ret != 0) { printf("[hal_sd]: init sd failed\n"); return -1; } sd_initialize = 1; } sd->config.bus_wide = card.bus_width; if (card.state & MMC_STATE_HIGHSPEED) sd->config.freq = 50000000; else sd->config.freq = 25000000; sd->priv = (void*)&card; sd_info.blk_size = 512; sd_info.blk_nums = card.csd.capacity/512; return 0; } /**@brief read sd blocks * * @param sd : the interface which should be initialised * @param data : pointer to the buffer which will store incoming data * @param blk_addr : sd blk addr * @param blks : sd blks * @param timeout : timeout in milisecond * @return 0 : on success. * @return EIO : if an error occurred with any step */ int32_t hal_sd_blks_read(sd_dev_t *sd, uint8_t *data, uint32_t blk_addr, uint32_t blks, uint32_t timeout) { int32_t ret; ret = mmc_block_read(sd->priv, data, blk_addr, blks); return ret; } /**@brief write sd blocks * * @param sd : the interface which should be initialised * @param data : pointer to the buffer which will store incoming data * @param blk_addr : sd blk addr * @param blks : sd blks * @param timeout : timeout in milisecond * @return 0 : on success. * @return EIO : if an error occurred with any step */ int32_t hal_sd_blks_write(sd_dev_t *sd, uint8_t *data, uint32_t blk_addr, uint32_t blks, uint32_t timeout) { int32_t ret; ret = mmc_block_write(sd->priv, data, blk_addr, blks); return ret; } /**@brief erase sd blocks * * @param sd : the interface which should be initialised * @param blk_start_addr : sd blocks start addr * @param blk_end_addr : sd blocks end addr * @return 0 : on success. * @return EIO : if an error occurred with any step */ int32_t hal_sd_erase(sd_dev_t *sd, uint32_t blk_start_addr, uint32_t blk_end_addr) { //TODO: return 0; } /**@brief get sd state * * @param sd : the interface which should be initialised * @param stat : pointer to the buffer which will store incoming data * @return 0 : on success. * @return EIO : if an error occurred with any step */ int32_t hal_sd_stat_get(sd_dev_t *sd, hal_sd_stat *stat) { *stat = SD_STAT_TRANSFER; return 0; } /**@brief get sd info * * @param sd : the interface which should be initialised * @param stat : pointer to the buffer which will store incoming data * @return 0 : on success. * @return EIO : if an error occurred with any step */ int32_t hal_sd_info_get(sd_dev_t *sd, hal_sd_info_t *info) { info->blk_size = sd_info.blk_size; info->blk_nums = sd_info.blk_nums; return 0; } /**@brief Deinitialises a sd interface * * @param sd : the interface which should be initialised * @return 0 : on success. * @return EIO : if an error occurred with any step */ int32_t hal_sd_finalize(sd_dev_t *sd) { sd_initialize = 0; if (!card.host) return 0; mmc_card_deinit(&card); HAL_SDC_Deinit(0); return 0; }
<reponame>lask/esp-iot-solution /* * This file is subject to the terms of the GFX License. If a copy of * the license was not distributed with this file, you can obtain one at: * * http://ugfx.org/license.html */ #ifndef GAUDIO_PLAY_CONFIG_H #define GAUDIO_PLAY_CONFIG_H #if GFX_USE_GAUDIO && GAUDIO_NEED_PLAY /*===========================================================================*/ /* Driver hardware support. */ /*===========================================================================*/ /* These may need to change for your hardware. */ #define GAUDIO_PLAY_MAX_SAMPLE_FREQUENCY 22000 #define GAUDIO_PLAY_NUM_FORMATS 2 #define GAUDIO_PLAY_FORMAT1 ARRAY_DATA_8BITUNSIGNED #define GAUDIO_PLAY_FORMAT2 ARRAY_DATA_16BITUNSIGNED #define GAUDIO_PLAY_NUM_CHANNELS 1 #define GAUDIO_PLAY_CHANNEL0_IS_STEREO GFXOFF #define GAUDIO_PLAY_MONO 0 #endif /* GFX_USE_GAUDIO && GAUDIO_NEED_PLAY */ #endif /* GAUDIO_PLAY_CONFIG_H */
<filename>drivers/clk/samsung/clk-s3c64xx.c // SPDX-License-Identifier: GPL-2.0-only /* * Copyright (c) 2013 <NAME> <<EMAIL>> * * Common Clock Framework support for all S3C64xx SoCs. */ #include <linux/slab.h> #include <linux/clk-provider.h> #include <linux/clk/samsung.h> #include <linux/of.h> #include <linux/of_address.h> #include <dt-bindings/clock/samsung,s3c64xx-clock.h> #include "clk.h" #include "clk-pll.h" /* S3C64xx clock controller register offsets. */ #define APLL_LOCK 0x000 #define MPLL_LOCK 0x004 #define EPLL_LOCK 0x008 #define APLL_CON 0x00c #define MPLL_CON 0x010 #define EPLL_CON0 0x014 #define EPLL_CON1 0x018 #define CLK_SRC 0x01c #define CLK_DIV0 0x020 #define CLK_DIV1 0x024 #define CLK_DIV2 0x028 #define HCLK_GATE 0x030 #define PCLK_GATE 0x034 #define SCLK_GATE 0x038 #define MEM0_GATE 0x03c #define CLK_SRC2 0x10c #define OTHERS 0x900 /* Helper macros to define clock arrays. */ #define FIXED_RATE_CLOCKS(name) \ static struct samsung_fixed_rate_clock name[] #define MUX_CLOCKS(name) \ static struct samsung_mux_clock name[] #define DIV_CLOCKS(name) \ static struct samsung_div_clock name[] #define GATE_CLOCKS(name) \ static struct samsung_gate_clock name[] /* Helper macros for gate types present on S3C64xx. */ #define GATE_BUS(_id, cname, pname, o, b) \ GATE(_id, cname, pname, o, b, 0, 0) #define GATE_SCLK(_id, cname, pname, o, b) \ GATE(_id, cname, pname, o, b, CLK_SET_RATE_PARENT, 0) #define GATE_ON(_id, cname, pname, o, b) \ GATE(_id, cname, pname, o, b, CLK_IGNORE_UNUSED, 0) static void __iomem *reg_base; static bool is_s3c6400; /* * List of controller registers to be saved and restored during * a suspend/resume cycle. */ static unsigned long s3c64xx_clk_regs[] __initdata = { APLL_LOCK, MPLL_LOCK, EPLL_LOCK, APLL_CON, MPLL_CON, EPLL_CON0, EPLL_CON1, CLK_SRC, CLK_DIV0, CLK_DIV1, CLK_DIV2, HCLK_GATE, PCLK_GATE, SCLK_GATE, }; static unsigned long s3c6410_clk_regs[] __initdata = { CLK_SRC2, MEM0_GATE, }; /* List of parent clocks common for all S3C64xx SoCs. */ PNAME(spi_mmc_p) = { "mout_epll", "dout_mpll", "fin_pll", "clk27m" }; PNAME(uart_p) = { "mout_epll", "dout_mpll" }; PNAME(audio0_p) = { "mout_epll", "dout_mpll", "fin_pll", "iiscdclk0", "pcmcdclk0", "none", "none", "none" }; PNAME(audio1_p) = { "mout_epll", "dout_mpll", "fin_pll", "iiscdclk1", "pcmcdclk0", "none", "none", "none" }; PNAME(mfc_p) = { "hclkx2", "mout_epll" }; PNAME(apll_p) = { "fin_pll", "fout_apll" }; PNAME(mpll_p) = { "fin_pll", "fout_mpll" }; PNAME(epll_p) = { "fin_pll", "fout_epll" }; PNAME(hclkx2_p) = { "mout_mpll", "mout_apll" }; /* S3C6400-specific parent clocks. */ PNAME(scaler_lcd_p6400) = { "mout_epll", "dout_mpll", "none", "none" }; PNAME(irda_p6400) = { "mout_epll", "dout_mpll", "none", "clk48m" }; PNAME(uhost_p6400) = { "clk48m", "mout_epll", "dout_mpll", "none" }; /* S3C6410-specific parent clocks. */ PNAME(clk27_p6410) = { "clk27m", "fin_pll" }; PNAME(scaler_lcd_p6410) = { "mout_epll", "dout_mpll", "fin_pll", "none" }; PNAME(irda_p6410) = { "mout_epll", "dout_mpll", "fin_pll", "clk48m" }; PNAME(uhost_p6410) = { "clk48m", "mout_epll", "dout_mpll", "fin_pll" }; PNAME(audio2_p6410) = { "mout_epll", "dout_mpll", "fin_pll", "iiscdclk2", "pcmcdclk1", "none", "none", "none" }; /* Fixed rate clocks generated outside the SoC. */ FIXED_RATE_CLOCKS(s3c64xx_fixed_rate_ext_clks) __initdata = { FRATE(0, "fin_pll", NULL, 0, 0), FRATE(0, "xusbxti", NULL, 0, 0), }; /* Fixed rate clocks generated inside the SoC. */ FIXED_RATE_CLOCKS(s3c64xx_fixed_rate_clks) __initdata = { FRATE(CLK27M, "clk27m", NULL, 0, 27000000), FRATE(CLK48M, "clk48m", NULL, 0, 48000000), }; /* List of clock muxes present on all S3C64xx SoCs. */ MUX_CLOCKS(s3c64xx_mux_clks) __initdata = { MUX_F(0, "mout_syncmux", hclkx2_p, OTHERS, 6, 1, 0, CLK_MUX_READ_ONLY), MUX(MOUT_APLL, "mout_apll", apll_p, CLK_SRC, 0, 1), MUX(MOUT_MPLL, "mout_mpll", mpll_p, CLK_SRC, 1, 1), MUX(MOUT_EPLL, "mout_epll", epll_p, CLK_SRC, 2, 1), MUX(MOUT_MFC, "mout_mfc", mfc_p, CLK_SRC, 4, 1), MUX(MOUT_AUDIO0, "mout_audio0", audio0_p, CLK_SRC, 7, 3), MUX(MOUT_AUDIO1, "mout_audio1", audio1_p, CLK_SRC, 10, 3), MUX(MOUT_UART, "mout_uart", uart_p, CLK_SRC, 13, 1), MUX(MOUT_SPI0, "mout_spi0", spi_mmc_p, CLK_SRC, 14, 2), MUX(MOUT_SPI1, "mout_spi1", spi_mmc_p, CLK_SRC, 16, 2), MUX(MOUT_MMC0, "mout_mmc0", spi_mmc_p, CLK_SRC, 18, 2), MUX(MOUT_MMC1, "mout_mmc1", spi_mmc_p, CLK_SRC, 20, 2), MUX(MOUT_MMC2, "mout_mmc2", spi_mmc_p, CLK_SRC, 22, 2), }; /* List of clock muxes present on S3C6400. */ MUX_CLOCKS(s3c6400_mux_clks) __initdata = { MUX(MOUT_UHOST, "mout_uhost", uhost_p6400, CLK_SRC, 5, 2), MUX(MOUT_IRDA, "mout_irda", irda_p6400, CLK_SRC, 24, 2), MUX(MOUT_LCD, "mout_lcd", scaler_lcd_p6400, CLK_SRC, 26, 2), MUX(MOUT_SCALER, "mout_scaler", scaler_lcd_p6400, CLK_SRC, 28, 2), }; /* List of clock muxes present on S3C6410. */ MUX_CLOCKS(s3c6410_mux_clks) __initdata = { MUX(MOUT_UHOST, "mout_uhost", uhost_p6410, CLK_SRC, 5, 2), MUX(MOUT_IRDA, "mout_irda", irda_p6410, CLK_SRC, 24, 2), MUX(MOUT_LCD, "mout_lcd", scaler_lcd_p6410, CLK_SRC, 26, 2), MUX(MOUT_SCALER, "mout_scaler", scaler_lcd_p6410, CLK_SRC, 28, 2), MUX(MOUT_DAC27, "mout_dac27", clk27_p6410, CLK_SRC, 30, 1), MUX(MOUT_TV27, "mout_tv27", clk27_p6410, CLK_SRC, 31, 1), MUX(MOUT_AUDIO2, "mout_audio2", audio2_p6410, CLK_SRC2, 0, 3), }; /* List of clock dividers present on all S3C64xx SoCs. */ DIV_CLOCKS(s3c64xx_div_clks) __initdata = { DIV(DOUT_MPLL, "dout_mpll", "mout_mpll", CLK_DIV0, 4, 1), DIV(HCLKX2, "hclkx2", "mout_syncmux", CLK_DIV0, 9, 3), DIV(HCLK, "hclk", "hclkx2", CLK_DIV0, 8, 1), DIV(PCLK, "pclk", "hclkx2", CLK_DIV0, 12, 4), DIV(DOUT_SECUR, "dout_secur", "hclkx2", CLK_DIV0, 18, 2), DIV(DOUT_CAM, "dout_cam", "hclkx2", CLK_DIV0, 20, 4), DIV(DOUT_JPEG, "dout_jpeg", "hclkx2", CLK_DIV0, 24, 4), DIV(DOUT_MFC, "dout_mfc", "mout_mfc", CLK_DIV0, 28, 4), DIV(DOUT_MMC0, "dout_mmc0", "mout_mmc0", CLK_DIV1, 0, 4), DIV(DOUT_MMC1, "dout_mmc1", "mout_mmc1", CLK_DIV1, 4, 4), DIV(DOUT_MMC2, "dout_mmc2", "mout_mmc2", CLK_DIV1, 8, 4), DIV(DOUT_LCD, "dout_lcd", "mout_lcd", CLK_DIV1, 12, 4), DIV(DOUT_SCALER, "dout_scaler", "mout_scaler", CLK_DIV1, 16, 4), DIV(DOUT_UHOST, "dout_uhost", "mout_uhost", CLK_DIV1, 20, 4), DIV(DOUT_SPI0, "dout_spi0", "mout_spi0", CLK_DIV2, 0, 4), DIV(DOUT_SPI1, "dout_spi1", "mout_spi1", CLK_DIV2, 4, 4), DIV(DOUT_AUDIO0, "dout_audio0", "mout_audio0", CLK_DIV2, 8, 4), DIV(DOUT_AUDIO1, "dout_audio1", "mout_audio1", CLK_DIV2, 12, 4), DIV(DOUT_UART, "dout_uart", "mout_uart", CLK_DIV2, 16, 4), DIV(DOUT_IRDA, "dout_irda", "mout_irda", CLK_DIV2, 20, 4), }; /* List of clock dividers present on S3C6400. */ DIV_CLOCKS(s3c6400_div_clks) __initdata = { DIV(ARMCLK, "armclk", "mout_apll", CLK_DIV0, 0, 3), }; /* List of clock dividers present on S3C6410. */ DIV_CLOCKS(s3c6410_div_clks) __initdata = { DIV(ARMCLK, "armclk", "mout_apll", CLK_DIV0, 0, 4), DIV(DOUT_FIMC, "dout_fimc", "hclk", CLK_DIV1, 24, 4), DIV(DOUT_AUDIO2, "dout_audio2", "mout_audio2", CLK_DIV2, 24, 4), }; /* List of clock gates present on all S3C64xx SoCs. */ GATE_CLOCKS(s3c64xx_gate_clks) __initdata = { GATE_BUS(HCLK_UHOST, "hclk_uhost", "hclk", HCLK_GATE, 29), GATE_BUS(HCLK_SECUR, "hclk_secur", "hclk", HCLK_GATE, 28), GATE_BUS(HCLK_SDMA1, "hclk_sdma1", "hclk", HCLK_GATE, 27), GATE_BUS(HCLK_SDMA0, "hclk_sdma0", "hclk", HCLK_GATE, 26), GATE_ON(HCLK_DDR1, "hclk_ddr1", "hclk", HCLK_GATE, 24), GATE_BUS(HCLK_USB, "hclk_usb", "hclk", HCLK_GATE, 20), GATE_BUS(HCLK_HSMMC2, "hclk_hsmmc2", "hclk", HCLK_GATE, 19), GATE_BUS(HCLK_HSMMC1, "hclk_hsmmc1", "hclk", HCLK_GATE, 18), GATE_BUS(HCLK_HSMMC0, "hclk_hsmmc0", "hclk", HCLK_GATE, 17), GATE_BUS(HCLK_MDP, "hclk_mdp", "hclk", HCLK_GATE, 16), GATE_BUS(HCLK_DHOST, "hclk_dhost", "hclk", HCLK_GATE, 15), GATE_BUS(HCLK_IHOST, "hclk_ihost", "hclk", HCLK_GATE, 14), GATE_BUS(HCLK_DMA1, "hclk_dma1", "hclk", HCLK_GATE, 13), GATE_BUS(HCLK_DMA0, "hclk_dma0", "hclk", HCLK_GATE, 12), GATE_BUS(HCLK_JPEG, "hclk_jpeg", "hclk", HCLK_GATE, 11), GATE_BUS(HCLK_CAMIF, "hclk_camif", "hclk", HCLK_GATE, 10), GATE_BUS(HCLK_SCALER, "hclk_scaler", "hclk", HCLK_GATE, 9), GATE_BUS(HCLK_2D, "hclk_2d", "hclk", HCLK_GATE, 8), GATE_BUS(HCLK_TV, "hclk_tv", "hclk", HCLK_GATE, 7), GATE_BUS(HCLK_POST0, "hclk_post0", "hclk", HCLK_GATE, 5), GATE_BUS(HCLK_ROT, "hclk_rot", "hclk", HCLK_GATE, 4), GATE_BUS(HCLK_LCD, "hclk_lcd", "hclk", HCLK_GATE, 3), GATE_BUS(HCLK_TZIC, "hclk_tzic", "hclk", HCLK_GATE, 2), GATE_ON(HCLK_INTC, "hclk_intc", "hclk", HCLK_GATE, 1), GATE_ON(PCLK_SKEY, "pclk_skey", "pclk", PCLK_GATE, 24), GATE_ON(PCLK_CHIPID, "pclk_chipid", "pclk", PCLK_GATE, 23), GATE_BUS(PCLK_SPI1, "pclk_spi1", "pclk", PCLK_GATE, 22), GATE_BUS(PCLK_SPI0, "pclk_spi0", "pclk", PCLK_GATE, 21), GATE_BUS(PCLK_HSIRX, "pclk_hsirx", "pclk", PCLK_GATE, 20), GATE_BUS(PCLK_HSITX, "pclk_hsitx", "pclk", PCLK_GATE, 19), GATE_ON(PCLK_GPIO, "pclk_gpio", "pclk", PCLK_GATE, 18), GATE_BUS(PCLK_IIC0, "pclk_iic0", "pclk", PCLK_GATE, 17), GATE_BUS(PCLK_IIS1, "pclk_iis1", "pclk", PCLK_GATE, 16), GATE_BUS(PCLK_IIS0, "pclk_iis0", "pclk", PCLK_GATE, 15), GATE_BUS(PCLK_AC97, "pclk_ac97", "pclk", PCLK_GATE, 14), GATE_BUS(PCLK_TZPC, "pclk_tzpc", "pclk", PCLK_GATE, 13), GATE_BUS(PCLK_TSADC, "pclk_tsadc", "pclk", PCLK_GATE, 12), GATE_BUS(PCLK_KEYPAD, "pclk_keypad", "pclk", PCLK_GATE, 11), GATE_BUS(PCLK_IRDA, "pclk_irda", "pclk", PCLK_GATE, 10), GATE_BUS(PCLK_PCM1, "pclk_pcm1", "pclk", PCLK_GATE, 9), GATE_BUS(PCLK_PCM0, "pclk_pcm0", "pclk", PCLK_GATE, 8), GATE_BUS(PCLK_PWM, "pclk_pwm", "pclk", PCLK_GATE, 7), GATE_BUS(PCLK_RTC, "pclk_rtc", "pclk", PCLK_GATE, 6), GATE_BUS(PCLK_WDT, "pclk_wdt", "pclk", PCLK_GATE, 5), GATE_BUS(PCLK_UART3, "pclk_uart3", "pclk", PCLK_GATE, 4), GATE_BUS(PCLK_UART2, "pclk_uart2", "pclk", PCLK_GATE, 3), GATE_BUS(PCLK_UART1, "pclk_uart1", "pclk", PCLK_GATE, 2), GATE_BUS(PCLK_UART0, "pclk_uart0", "pclk", PCLK_GATE, 1), GATE_BUS(PCLK_MFC, "pclk_mfc", "pclk", PCLK_GATE, 0), GATE_SCLK(SCLK_UHOST, "sclk_uhost", "dout_uhost", SCLK_GATE, 30), GATE_SCLK(SCLK_MMC2_48, "sclk_mmc2_48", "clk48m", SCLK_GATE, 29), GATE_SCLK(SCLK_MMC1_48, "sclk_mmc1_48", "clk48m", SCLK_GATE, 28), GATE_SCLK(SCLK_MMC0_48, "sclk_mmc0_48", "clk48m", SCLK_GATE, 27), GATE_SCLK(SCLK_MMC2, "sclk_mmc2", "dout_mmc2", SCLK_GATE, 26), GATE_SCLK(SCLK_MMC1, "sclk_mmc1", "dout_mmc1", SCLK_GATE, 25), GATE_SCLK(SCLK_MMC0, "sclk_mmc0", "dout_mmc0", SCLK_GATE, 24), GATE_SCLK(SCLK_SPI1_48, "sclk_spi1_48", "clk48m", SCLK_GATE, 23), GATE_SCLK(SCLK_SPI0_48, "sclk_spi0_48", "clk48m", SCLK_GATE, 22), GATE_SCLK(SCLK_SPI1, "sclk_spi1", "dout_spi1", SCLK_GATE, 21), GATE_SCLK(SCLK_SPI0, "sclk_spi0", "dout_spi0", SCLK_GATE, 20), GATE_SCLK(SCLK_DAC27, "sclk_dac27", "mout_dac27", SCLK_GATE, 19), GATE_SCLK(SCLK_TV27, "sclk_tv27", "mout_tv27", SCLK_GATE, 18), GATE_SCLK(SCLK_SCALER27, "sclk_scaler27", "clk27m", SCLK_GATE, 17), GATE_SCLK(SCLK_SCALER, "sclk_scaler", "dout_scaler", SCLK_GATE, 16), GATE_SCLK(SCLK_LCD27, "sclk_lcd27", "clk27m", SCLK_GATE, 15), GATE_SCLK(SCLK_LCD, "sclk_lcd", "dout_lcd", SCLK_GATE, 14), GATE_SCLK(SCLK_POST0_27, "sclk_post0_27", "clk27m", SCLK_GATE, 12), GATE_SCLK(SCLK_POST0, "sclk_post0", "dout_lcd", SCLK_GATE, 10), GATE_SCLK(SCLK_AUDIO1, "sclk_audio1", "dout_audio1", SCLK_GATE, 9), GATE_SCLK(SCLK_AUDIO0, "sclk_audio0", "dout_audio0", SCLK_GATE, 8), GATE_SCLK(SCLK_SECUR, "sclk_secur", "dout_secur", SCLK_GATE, 7), GATE_SCLK(SCLK_IRDA, "sclk_irda", "dout_irda", SCLK_GATE, 6), GATE_SCLK(SCLK_UART, "sclk_uart", "dout_uart", SCLK_GATE, 5), GATE_SCLK(SCLK_MFC, "sclk_mfc", "dout_mfc", SCLK_GATE, 3), GATE_SCLK(SCLK_CAM, "sclk_cam", "dout_cam", SCLK_GATE, 2), GATE_SCLK(SCLK_JPEG, "sclk_jpeg", "dout_jpeg", SCLK_GATE, 1), }; /* List of clock gates present on S3C6400. */ GATE_CLOCKS(s3c6400_gate_clks) __initdata = { GATE_ON(HCLK_DDR0, "hclk_ddr0", "hclk", HCLK_GATE, 23), GATE_SCLK(SCLK_ONENAND, "sclk_onenand", "parent", SCLK_GATE, 4), }; /* List of clock gates present on S3C6410. */ GATE_CLOCKS(s3c6410_gate_clks) __initdata = { GATE_BUS(HCLK_3DSE, "hclk_3dse", "hclk", HCLK_GATE, 31), GATE_ON(HCLK_IROM, "hclk_irom", "hclk", HCLK_GATE, 25), GATE_ON(HCLK_MEM1, "hclk_mem1", "hclk", HCLK_GATE, 22), GATE_ON(HCLK_MEM0, "hclk_mem0", "hclk", HCLK_GATE, 21), GATE_BUS(HCLK_MFC, "hclk_mfc", "hclk", HCLK_GATE, 0), GATE_BUS(PCLK_IIC1, "pclk_iic1", "pclk", PCLK_GATE, 27), GATE_BUS(PCLK_IIS2, "pclk_iis2", "pclk", PCLK_GATE, 26), GATE_SCLK(SCLK_FIMC, "sclk_fimc", "dout_fimc", SCLK_GATE, 13), GATE_SCLK(SCLK_AUDIO2, "sclk_audio2", "dout_audio2", SCLK_GATE, 11), GATE_BUS(MEM0_CFCON, "mem0_cfcon", "hclk_mem0", MEM0_GATE, 5), GATE_BUS(MEM0_ONENAND1, "mem0_onenand1", "hclk_mem0", MEM0_GATE, 4), GATE_BUS(MEM0_ONENAND0, "mem0_onenand0", "hclk_mem0", MEM0_GATE, 3), GATE_BUS(MEM0_NFCON, "mem0_nfcon", "hclk_mem0", MEM0_GATE, 2), GATE_ON(MEM0_SROM, "mem0_srom", "hclk_mem0", MEM0_GATE, 1), }; /* List of PLL clocks. */ static struct samsung_pll_clock s3c64xx_pll_clks[] __initdata = { PLL(pll_6552, FOUT_APLL, "fout_apll", "fin_pll", APLL_LOCK, APLL_CON, NULL), PLL(pll_6552, FOUT_MPLL, "fout_mpll", "fin_pll", MPLL_LOCK, MPLL_CON, NULL), PLL(pll_6553, FOUT_EPLL, "fout_epll", "fin_pll", EPLL_LOCK, EPLL_CON0, NULL), }; /* Aliases for common s3c64xx clocks. */ static struct samsung_clock_alias s3c64xx_clock_aliases[] = { ALIAS(FOUT_APLL, NULL, "fout_apll"), ALIAS(FOUT_MPLL, NULL, "fout_mpll"), ALIAS(FOUT_EPLL, NULL, "fout_epll"), ALIAS(MOUT_EPLL, NULL, "mout_epll"), ALIAS(DOUT_MPLL, NULL, "dout_mpll"), ALIAS(HCLKX2, NULL, "hclk2"), ALIAS(HCLK, NULL, "hclk"), ALIAS(PCLK, NULL, "pclk"), ALIAS(PCLK, NULL, "clk_uart_baud2"), ALIAS(ARMCLK, NULL, "armclk"), ALIAS(HCLK_UHOST, "s3c2410-ohci", "usb-host"), ALIAS(HCLK_USB, "s3c-hsotg", "otg"), ALIAS(HCLK_HSMMC2, "s3c-sdhci.2", "hsmmc"), ALIAS(HCLK_HSMMC2, "s3c-sdhci.2", "mmc_busclk.0"), ALIAS(HCLK_HSMMC1, "s3c-sdhci.1", "hsmmc"), ALIAS(HCLK_HSMMC1, "s3c-sdhci.1", "mmc_busclk.0"), ALIAS(HCLK_HSMMC0, "s3c-sdhci.0", "hsmmc"), ALIAS(HCLK_HSMMC0, "s3c-sdhci.0", "mmc_busclk.0"), ALIAS(HCLK_DMA1, "dma-pl080s.1", "apb_pclk"), ALIAS(HCLK_DMA0, "dma-pl080s.0", "apb_pclk"), ALIAS(HCLK_CAMIF, "s3c-camif", "camif"), ALIAS(HCLK_LCD, "s3c-fb", "lcd"), ALIAS(PCLK_SPI1, "s3c6410-spi.1", "spi"), ALIAS(PCLK_SPI0, "s3c6410-spi.0", "spi"), ALIAS(PCLK_IIC0, "s3c2440-i2c.0", "i2c"), ALIAS(PCLK_IIS1, "samsung-i2s.1", "iis"), ALIAS(PCLK_IIS0, "samsung-i2s.0", "iis"), ALIAS(PCLK_AC97, "samsung-ac97", "ac97"), ALIAS(PCLK_TSADC, "s3c64xx-adc", "adc"), ALIAS(PCLK_KEYPAD, "samsung-keypad", "keypad"), ALIAS(PCLK_PCM1, "samsung-pcm.1", "pcm"), ALIAS(PCLK_PCM0, "samsung-pcm.0", "pcm"), ALIAS(PCLK_PWM, NULL, "timers"), ALIAS(PCLK_RTC, "s3c64xx-rtc", "rtc"), ALIAS(PCLK_WDT, NULL, "watchdog"), ALIAS(PCLK_UART3, "s3c6400-uart.3", "uart"), ALIAS(PCLK_UART2, "s3c6400-uart.2", "uart"), ALIAS(PCLK_UART1, "s3c6400-uart.1", "uart"), ALIAS(PCLK_UART0, "s3c6400-uart.0", "uart"), ALIAS(SCLK_UHOST, "s3c2410-ohci", "usb-bus-host"), ALIAS(SCLK_MMC2, "s3c-sdhci.2", "mmc_busclk.2"), ALIAS(SCLK_MMC1, "s3c-sdhci.1", "mmc_busclk.2"), ALIAS(SCLK_MMC0, "s3c-sdhci.0", "mmc_busclk.2"), ALIAS(PCLK_SPI1, "s3c6410-spi.1", "spi_busclk0"), ALIAS(SCLK_SPI1, "s3c6410-spi.1", "spi_busclk2"), ALIAS(PCLK_SPI0, "s3c6410-spi.0", "spi_busclk0"), ALIAS(SCLK_SPI0, "s3c6410-spi.0", "spi_busclk2"), ALIAS(SCLK_AUDIO1, "samsung-pcm.1", "audio-bus"), ALIAS(SCLK_AUDIO1, "samsung-i2s.1", "audio-bus"), ALIAS(SCLK_AUDIO0, "samsung-pcm.0", "audio-bus"), ALIAS(SCLK_AUDIO0, "samsung-i2s.0", "audio-bus"), ALIAS(SCLK_UART, NULL, "clk_uart_baud3"), ALIAS(SCLK_CAM, "s3c-camif", "camera"), }; /* Aliases for s3c6400-specific clocks. */ static struct samsung_clock_alias s3c6400_clock_aliases[] = { /* Nothing to place here yet. */ }; /* Aliases for s3c6410-specific clocks. */ static struct samsung_clock_alias s3c6410_clock_aliases[] = { ALIAS(PCLK_IIC1, "s3c2440-i2c.1", "i2c"), ALIAS(PCLK_IIS2, "samsung-i2s.2", "iis"), ALIAS(SCLK_FIMC, "s3c-camif", "fimc"), ALIAS(SCLK_AUDIO2, "samsung-i2s.2", "audio-bus"), ALIAS(MEM0_SROM, NULL, "srom"), }; static void __init s3c64xx_clk_register_fixed_ext( struct samsung_clk_provider *ctx, unsigned long fin_pll_f, unsigned long xusbxti_f) { s3c64xx_fixed_rate_ext_clks[0].fixed_rate = fin_pll_f; s3c64xx_fixed_rate_ext_clks[1].fixed_rate = xusbxti_f; samsung_clk_register_fixed_rate(ctx, s3c64xx_fixed_rate_ext_clks, ARRAY_SIZE(s3c64xx_fixed_rate_ext_clks)); } /* Register s3c64xx clocks. */ void __init s3c64xx_clk_init(struct device_node *np, unsigned long xtal_f, unsigned long xusbxti_f, bool s3c6400, void __iomem *base) { struct samsung_clk_provider *ctx; struct clk_hw **hws; reg_base = base; is_s3c6400 = s3c6400; if (np) { reg_base = of_iomap(np, 0); if (!reg_base) panic("%s: failed to map registers\n", __func__); } ctx = samsung_clk_init(np, reg_base, NR_CLKS); hws = ctx->clk_data.hws; /* Register external clocks. */ if (!np) s3c64xx_clk_register_fixed_ext(ctx, xtal_f, xusbxti_f); /* Register PLLs. */ samsung_clk_register_pll(ctx, s3c64xx_pll_clks, ARRAY_SIZE(s3c64xx_pll_clks), reg_base); /* Register common internal clocks. */ samsung_clk_register_fixed_rate(ctx, s3c64xx_fixed_rate_clks, ARRAY_SIZE(s3c64xx_fixed_rate_clks)); samsung_clk_register_mux(ctx, s3c64xx_mux_clks, ARRAY_SIZE(s3c64xx_mux_clks)); samsung_clk_register_div(ctx, s3c64xx_div_clks, ARRAY_SIZE(s3c64xx_div_clks)); samsung_clk_register_gate(ctx, s3c64xx_gate_clks, ARRAY_SIZE(s3c64xx_gate_clks)); /* Register SoC-specific clocks. */ if (is_s3c6400) { samsung_clk_register_mux(ctx, s3c6400_mux_clks, ARRAY_SIZE(s3c6400_mux_clks)); samsung_clk_register_div(ctx, s3c6400_div_clks, ARRAY_SIZE(s3c6400_div_clks)); samsung_clk_register_gate(ctx, s3c6400_gate_clks, ARRAY_SIZE(s3c6400_gate_clks)); samsung_clk_register_alias(ctx, s3c6400_clock_aliases, ARRAY_SIZE(s3c6400_clock_aliases)); } else { samsung_clk_register_mux(ctx, s3c6410_mux_clks, ARRAY_SIZE(s3c6410_mux_clks)); samsung_clk_register_div(ctx, s3c6410_div_clks, ARRAY_SIZE(s3c6410_div_clks)); samsung_clk_register_gate(ctx, s3c6410_gate_clks, ARRAY_SIZE(s3c6410_gate_clks)); samsung_clk_register_alias(ctx, s3c6410_clock_aliases, ARRAY_SIZE(s3c6410_clock_aliases)); } samsung_clk_register_alias(ctx, s3c64xx_clock_aliases, ARRAY_SIZE(s3c64xx_clock_aliases)); samsung_clk_sleep_init(reg_base, s3c64xx_clk_regs, ARRAY_SIZE(s3c64xx_clk_regs)); if (!is_s3c6400) samsung_clk_sleep_init(reg_base, s3c6410_clk_regs, ARRAY_SIZE(s3c6410_clk_regs)); samsung_clk_of_add_provider(np, ctx); pr_info("%s clocks: apll = %lu, mpll = %lu\n" "\tepll = %lu, arm_clk = %lu\n", is_s3c6400 ? "S3C6400" : "S3C6410", clk_hw_get_rate(hws[MOUT_APLL]), clk_hw_get_rate(hws[MOUT_MPLL]), clk_hw_get_rate(hws[MOUT_EPLL]), clk_hw_get_rate(hws[ARMCLK])); } static void __init s3c6400_clk_init(struct device_node *np) { s3c64xx_clk_init(np, 0, 0, true, NULL); } CLK_OF_DECLARE(s3c6400_clk, "samsung,s3c6400-clock", s3c6400_clk_init); static void __init s3c6410_clk_init(struct device_node *np) { s3c64xx_clk_init(np, 0, 0, false, NULL); } CLK_OF_DECLARE(s3c6410_clk, "samsung,s3c6410-clock", s3c6410_clk_init);
<reponame>UpsilonKoan/wireless-communication-simulation-with-IT-- //----- VectorChannel.h ----- // Programmed by LTE Simulation Group of IMC, SWJTU #include "itpp/itcomm.h" using namespace itpp; //************************************* Class CTranceiver Declaration ************************************************************* class CVectorChannel //-----------MIMO channel { /***** Data Members *****/ public: int mModelCase; // Modified Pedestrian A, Vehicular A, Pedestrian B, Single Path{00,01,10,11} int mNumOfPath; // Number of Paths int NumOfSample; // Number of Sampled int mNumOfMSAntenna; // MS antenna Number int mNumOfBSAntenna; // BS antenna Number double mFrequencyOfCarrier; // Frequency of Carrier double mDoppler; // Maximum of Doppler shift float mAntennaSpacingBS; // float mAntennaSpacingMS; // double AOAPerPathMS; // 22.5 or 67.5or-67.5 double AODPerPathBS; // 50 20 vec mAngleSpreadPerPathMS; // ChannelCoefficient is calculated by path vec mAngleSpreadPerPathBS; // ChannelCoefficient is calculated by path cvec mVelocityOfMS; // The velocity of MS //----- Hold In Abeyance ----- //vec mPathDelays(6); //Complex *mChannelCoefficients; /***** Function Members *****/ /***** Constructors *****/ public: CVectorChannel(); /*------------------------------------------------------------------------ Construct a VectorChannel object. Precondition: None. Postcondition: An empty VectorChannel object has been constructed ------------------------------------------------------------------------*/ virtual ~CVectorChannel(); /*----------------------------------------------------------------------- Class destructor Precondition: None Postcondition: The VectorChannel object has been destructed. ------------------------------------------------------------------------*/ void SetCVectorChannelParameter(); /*----------------------------------------------------------------------- Set up the parameters of Function Member of Vector Channel //----- Hold In Abeyance ----- Precondition: None Postcondition: None ------------------------------------------------------------------------*/ mat ChannelCorrelation(double AngleSpread,double Angle,double RatioDistance,int NumOfAntenna); /*----------------------------------------------------------------------- Caculate the Correlation of the Channel Precondition: AngleSpread, Angle, RatioDistance and NumOfAntenna are given Postcondition: Correlation of the Channel is returned ------------------------------------------------------------------------*/ cvec ScalarChannel(cvec velocity, double fre, double doppler); /*----------------------------------------------------------------------- Caculate the scalar coeffiencts of the channel Precondition: velocity, frequency, maximum of doppler shift are given Postcondition: Channel coefficiencts are returned ------------------------------------------------------------------------*/ cmat RunScalarChannel(); /*----------------------------------------------------------------------- All channel coefficiencts are caculated and stored to variable scalarch Precondition: ScalarChannel() works properly, total number of MS and BS antenna are given Postcondition: Final channel coefficiencts are returned ------------------------------------------------------------------------*/ cmat TransmissionCoefficientPerPath(int path); /*----------------------------------------------------------------------- Caculate the Transmission Coefficient of every path Precondition: None Postcondition: coefficientp is returned which is for RunCVectorChannel() ------------------------------------------------------------------------*/ cmat RunCVectorChannel(); /*----------------------------------------------------------------------- Run all the functions of CVectorChannel Precondition: Every function member works properly Postcondition: Return neccessary information of MIMO channel coefficient ------------------------------------------------------------------------*/ //----- Hold In Abeyance ----- //cmat TotalTransmissionCoefficient(); //SetVectorParameter(); //RunCVectorChannel(); };