hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
ec12aa83221a94d8440547ffc834a4dabe3b283f
753
h
C
include/SpringBoard/SBBlockWorkspaceQueueTestRecipe.h
ItHertzSoGood/DragonBuild
1aaf6133ab386ba3a5165a4b29c080ca8d814b52
[ "MIT" ]
3
2020-06-20T02:53:25.000Z
2020-11-07T08:39:13.000Z
include/SpringBoard/SBBlockWorkspaceQueueTestRecipe.h
elihwyma/DragonBuild
0891eb72d33d59fc05f8455a8a30ce6eebebddec
[ "MIT" ]
null
null
null
include/SpringBoard/SBBlockWorkspaceQueueTestRecipe.h
elihwyma/DragonBuild
0891eb72d33d59fc05f8455a8a30ce6eebebddec
[ "MIT" ]
1
2020-07-26T02:16:06.000Z
2020-07-26T02:16:06.000Z
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 22 2020 01:47:48). // // Copyright (C) 1997-2019 Steve Nygard. // #import <objc/NSObject.h> #import <SpringBoard/SBTestRecipe-Protocol.h> @class FBWorkspaceEventQueueLock, NSTimer; @interface SBBlockWorkspaceQueueTestRecipe : NSObject <SBTestRecipe> { NSTimer *_blockTimer; FBWorkspaceEventQueueLock *_queueLock; } + (void)load; @property(retain, nonatomic) FBWorkspaceEventQueueLock *queueLock; // @synthesize queueLock=_queueLock; @property(retain, nonatomic) NSTimer *blockTimer; // @synthesize blockTimer=_blockTimer; // - (void).cxx_destruct; - (void)handleVolumeDecrease; - (void)blockTimerDidFire:(id)arg1; - (void)handleVolumeIncrease; - (id)title; @end
25.1
103
0.749004
578286ec430e48038b3a964974058809d9337701
231
c
C
src/map/free_map.c
Nilexplr/my_rpg_2017
f4ef26df6265c16f7a22afd6ecb9045c43959c63
[ "MIT" ]
3
2020-03-08T01:22:50.000Z
2020-05-01T09:03:58.000Z
src/map/free_map.c
Nilexplr/my_world
536dfde00bc624fc4826de985c555ad8b30b7d2a
[ "MIT" ]
null
null
null
src/map/free_map.c
Nilexplr/my_world
536dfde00bc624fc4826de985c555ad8b30b7d2a
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2018 ** create_map.c ** File description: ** julien.ollivier@epitech.eu */ #include <stdlib.h> void free_map(float **map) { if (!map) return; for (int i = 0; map[i] ; i++) free(map[i]); free(map); }
12.833333
30
0.606061
f35fecefa4c2cf2b6a06d538a0a3d384e82dada0
533
h
C
rift.h
OhioIon/riftDriverWin
7be84f57141f86b49e6fc7406ea1ed7781c0afa9
[ "MIT" ]
2
2021-03-27T04:45:58.000Z
2021-04-24T04:07:38.000Z
rift.h
OhioIon/riftDriverWin
7be84f57141f86b49e6fc7406ea1ed7781c0afa9
[ "MIT" ]
null
null
null
rift.h
OhioIon/riftDriverWin
7be84f57141f86b49e6fc7406ea1ed7781c0afa9
[ "MIT" ]
null
null
null
#ifndef _RIFT_H #define _RIFT_H // ********************* Includes ********************* // #include <stdint.h> #include <stdio.h> #include <windows.h> // ********************* Defines ********************* // // ********************* Types ********************* // // ********************* Data ********************* // // ********************* Interface ********************* // bool rift_send_keep_alive(HANDLE handle); bool rift_send_enable_components(HANDLE handle, bool on_l); #endif
25.380952
64
0.362101
b3d7d08053c13071ca763b42a99638c5b9b3c885
9,436
c
C
nitan/cmds/adm/setcoor.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/cmds/adm/setcoor.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/cmds/adm/setcoor.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
// This program is a part of NT MudLIB // Written by Lonely@nitan.org // setcoor.c inherit F_CLEAN_UP; #define SYNTAX "syntax: setcoor x,y,z\n" #define VALUE query("env/setcoor", this_player(1)) //#define VALUE 10 mapping map_dirs = ([ "enter" : ([ "x" : -1, "y" : -1, "z": -1 ]), "out" : ([ "x" : 1, "y" : 1, "z": 1 ]), "east" : ([ "x" : VALUE, "y" : 0, "z": 0 ]), "west" : ([ "x" :-VALUE, "y" : 0, "z": 0 ]), "south" : ([ "x" : 0, "y" :-VALUE, "z": 0 ]), "north" : ([ "x" : 0, "y" : VALUE, "z": 0 ]), "up" : ([ "x" : 0, "y" : 0, "z": VALUE ]), "down" : ([ "x" : 0, "y" : 0, "z":-VALUE ]), "eastup" : ([ "x" : VALUE, "y" : 0, "z": VALUE ]), "westup" : ([ "x" :-VALUE, "y" : 0, "z": VALUE ]), "southup" : ([ "x" : 0, "y" :-VALUE, "z": VALUE ]), "northup" : ([ "x" : 0, "y" : VALUE, "z": VALUE ]), "eastdown" : ([ "x" : VALUE, "y" : 0, "z":-VALUE ]), "westdown" : ([ "x" :-VALUE, "y" : 0, "z":-VALUE ]), "southdown" : ([ "x" : 0, "y" :-VALUE, "z":-VALUE ]), "northdown" : ([ "x" : 0, "y" : VALUE, "z":-VALUE ]), "southeast" : ([ "x" : VALUE, "y" :-VALUE, "z": 0 ]), "northeast" : ([ "x" : VALUE, "y" : VALUE, "z": 0 ]), "southwest" : ([ "x" :-VALUE, "y" :-VALUE, "z": 0 ]), "northwest" : ([ "x" :-VALUE, "y" : VALUE, "z": 0 ]), ]); int non_recur_do(object room, int x, int y, int z, string prefix); void clear_old_coor(object room); int help(object me); int main(object me, string arg) { int x, y, z; int the_same_dir = 0, all = 0; object env = environment(me); string prefix, file; seteuid(getuid()); if( !SECURITY_D->valid_grant(me, "(admin)") ) return 0; if( !query("env/setcoor", me) ) return notify_fail("危險指令,慎用!慎用!\n"); set_eval_limit(900000000); reset_eval_cost(); if( !arg ) { if( query("border", env)){ write("房間 " + base_name(env) + " 已非邊界。\n"); delete("border", env); return 1; } else return notify_fail("這裏本來就不是邊界。\n"); } if( member_array(arg, keys(map_dirs)) != -1 ) { if( query("border/"+arg, env) ) { write("房間 " + base_name(env) + " 的" + arg + "方向已非邊界。\n"); delete("border/"+arg, env); if( !sizeof(query("border", env)) ) delete("border", env); return 1; } else { set("border/"+arg, 1, env); write("房間 " + base_name(env) + " 的" + arg + "方向已設為邊界。\n"); return 1; } } if( sscanf(arg, "-s %s", arg) ) the_same_dir = 1; else if( sscanf(arg, "-a %s", arg) ) all = 1; if( sscanf(arg, "%d,%d,%d", x, y, z) != 3 ) return notify_fail(SYNTAX); prefix = ""; if( !all ) prefix = base_dir(env); if( the_same_dir || all ) { non_recur_do(env, x, y, z, prefix); } else { if( query("coor", env) ) clear_old_coor(env); if( query("coor", env) != 0 ) write("房間 " + base_name(env) + " 座標重新設定成功。\n"); else write("房間 " + base_name(env) + " 座標設定成功。\n"); set("coor/x", x, env); set("coor/y", y, env); set("coor/z", z, env); file = read_file(base_name(env) + ".c"); file = replace_string(file, "setup()", sprintf("set(\"coor/x\", %d);\n\tset(\"coor/y\", %d);\n\tset(\"coor/z\", %d);\n\tsetup()", x, y, z)); write_file(base_name(env) + ".c", file, 1); } write("ok\n"); return 1; } int non_recur_do(object room, int x, int y, int z, string prefix) { mapping roomlist, all; mapping border; mapping exits; string *directions; string *dirs; string dir, file; object curr_room, next_room; int i; int file_count = 0; int x1, y1, z1; if( query("coor", room) ) clear_old_coor(room); all = ([]); roomlist = ([]); set("coor/x", x, room); set("coor/y", y, room); set("coor/z", z, room); file = read_file(base_name(room) + ".c"); file = replace_string(file, "setup()", sprintf("set(\"coor/x\", %d);\n\tset(\"coor/y\", %d);\n\tset(\"coor/z\", %d);\n\tsetup()", x, y, z)); write_file(base_name(room) + ".c", file, 1); file_count ++; write("房間 " + base_name(room) + " 座標設定成功。\n"); all += ([base_name(room) : room]); roomlist += ([base_name(room) : room]); x1 = y1 = z1 = 0; while( sizeof(roomlist) ) { reset_eval_cost(); dirs = ({}); curr_room = values(roomlist)[0]; map_delete(roomlist, keys(roomlist)[0]); if( mapp(border=query("border", curr_room)) ) dirs = keys(border); exits=query("exits", curr_room); if( !mapp(exits) || !sizeof(exits)) return 1; directions = keys(exits); directions -= dirs; x=query("coor/x", curr_room); y=query("coor/y", curr_room); z=query("coor/z", curr_room); for( i = 0; i < sizeof(directions); i ++ ) { reset_eval_cost(); dir = directions[i]; if( !objectp(next_room = get_object(exits[dir])) ) continue; if( undefinedp(all[base_name(next_room)]) && (strsrch(base_name(next_room), prefix) != -1 || prefix == "") ) { if( query("coor", next_room) ) clear_old_coor(next_room); if( map_dirs[dir] ) { x1 = x + map_dirs[dir]["x"]; y1 = y + map_dirs[dir]["y"]; z1 = z + map_dirs[dir]["z"]; } else { x1 = x + 1; y1 = y + 1; x1 = z + 1; } set("coor/x", x1, next_room); set("coor/y", y1, next_room); set("coor/z", z1, next_room); file = read_file(base_name(next_room) + ".c"); file = replace_string(file, "setup()", sprintf("set(\"coor/x\", %d);\n\tset(\"coor/y\", %d);\n\tset(\"coor/z\", %d);\n\tsetup()", x1, y1, z1)); write_file(base_name(next_room) + ".c", file, 1); file_count ++; write("房間 " + base_name(next_room) + " 座標設定成功。\n"); all += ([base_name(next_room) : next_room]); roomlist += ([base_name(next_room) : next_room]); } } } write("共定位 " + sprintf("%d", file_count) + " 個房間。\n"); return 1; } void clear_old_coor(object room) { int x, y, z, i; string *file; string result = ""; x=query("coor/x", room); y=query("coor/y", room); z=query("coor/z", room); file = explode(read_file(base_name(room) + ".c"), "\n"); for (i = 0; i < sizeof(file); i++) { if( strsrch(file[i], "set(\"coor/") != -1) { file[i] = 0; continue; } // file[i] = replace_string(file[i], // sprintf("set(\"coor/y\", %d);\n", y), ""); } file -= ({ 0 }); result += implode(file, "\n"); rm(base_name(room) + ".c"); write_file(base_name(room) + ".c", result, 1); } int help(object me) { write(@HELP 指令格式 : setcoor <參數> x,y,z 用法: setcoor 清除當前房間所有方向的邊界屬性。 setcoor <方向> 若該當前房間的該方向已為邊界,則清除之,否則 設置該方向為邊界。 setcoor x,y,z 無論當前房間是否已定位,重新並單獨處理該房間。 setcoor -s x,y,z 無論當前房間是否已定位,重新定位當前房間的坐 標,並連鎖處理,直到同一目錄下所有房間都被處 理過為止。 setcoor -a x,y,z 同上,但無同一目錄限制。 HELP ); return 1; }
35.473684
130
0.373145
b3e0c6d84acc528ab7c8de042f728d43af684ace
216
h
C
UICategory/YMUIKit/YMCategory/YMRichTextPattern/YMEmojPattern.h
acekiller/UICategory
b8d956d40b12e317cec3dff67f99b1900c58525e
[ "MIT" ]
null
null
null
UICategory/YMUIKit/YMCategory/YMRichTextPattern/YMEmojPattern.h
acekiller/UICategory
b8d956d40b12e317cec3dff67f99b1900c58525e
[ "MIT" ]
null
null
null
UICategory/YMUIKit/YMCategory/YMRichTextPattern/YMEmojPattern.h
acekiller/UICategory
b8d956d40b12e317cec3dff67f99b1900c58525e
[ "MIT" ]
null
null
null
// // YMEmojPattern.h // UICategory // // Created by fengxijun on 5/10/16. // Copyright © 2016 goappbox. All rights reserved. // #import "YMRichTextPattern.h" @interface YMEmojPattern : YMRichTextPattern @end
15.428571
51
0.708333
7e7cc58452678156a3710bb4927024f6e05824e6
244
h
C
KRProduct/KRProduct/Classes/Store/StoreDetail/Controller/KRStoreDetailController.h
KinRainModulization/KRProduct
c9469a9493e62a045e134a320c1c8741180ebee3
[ "MIT" ]
null
null
null
KRProduct/KRProduct/Classes/Store/StoreDetail/Controller/KRStoreDetailController.h
KinRainModulization/KRProduct
c9469a9493e62a045e134a320c1c8741180ebee3
[ "MIT" ]
null
null
null
KRProduct/KRProduct/Classes/Store/StoreDetail/Controller/KRStoreDetailController.h
KinRainModulization/KRProduct
c9469a9493e62a045e134a320c1c8741180ebee3
[ "MIT" ]
null
null
null
// // KRStoreDetailController.h // KRProduct // // Created by LX on 2018/1/5. // Copyright © 2018年 Ace. All rights reserved. // #import <KRPublishLibrary/BaseViewController.h> @interface KRStoreDetailController : BaseViewController @end
17.428571
55
0.737705
47a7b0f24a50259859b32fc2a722aba40cc7d5af
2,575
h
C
src/main/third_party/lock/shared_lock.h
tinro/RedGiant
01cd9d8d13d5b5db581af771a51e32e5e96dba85
[ "MIT" ]
17
2016-05-30T07:20:45.000Z
2021-08-16T07:40:42.000Z
src/main/third_party/lock/shared_lock.h
tinro/RedGiant
01cd9d8d13d5b5db581af771a51e32e5e96dba85
[ "MIT" ]
13
2016-04-21T03:30:18.000Z
2016-06-02T03:48:50.000Z
src/main/third_party/lock/shared_lock.h
tinro/RedGiant
01cd9d8d13d5b5db581af771a51e32e5e96dba85
[ "MIT" ]
5
2016-05-24T11:49:13.000Z
2016-06-06T09:22:17.000Z
#ifndef SRC_MAIN_CORE_LOCK_SHARED_LOCK_H_ #define SRC_MAIN_CORE_LOCK_SHARED_LOCK_H_ #include <mutex> #include <system_error> #include <utility> namespace redgiant { /* * A simple version of c++14 shared_lock without timed features */ /// shared_lock template<typename _Mutex> class shared_lock { public: typedef _Mutex mutex_type; // Shared locking shared_lock() noexcept : _M_pm(nullptr), _M_owns(false) {} explicit shared_lock(mutex_type& __m) : _M_pm(&__m), _M_owns(true) { __m.lock_shared(); } shared_lock(mutex_type& __m, std::defer_lock_t) noexcept : _M_pm(&__m), _M_owns(false) {} shared_lock(mutex_type& __m, std::try_to_lock_t) : _M_pm(&__m), _M_owns(__m.try_lock_shared()) {} shared_lock(mutex_type& __m, std::adopt_lock_t) : _M_pm(&__m), _M_owns(true) {} ~shared_lock() { if (_M_owns) _M_pm->unlock_shared(); } shared_lock(shared_lock const&) = delete; shared_lock& operator=(shared_lock const&) = delete; shared_lock(shared_lock&& __sl) noexcept : shared_lock() { swap(__sl); } shared_lock& operator=(shared_lock&& __sl) noexcept { shared_lock(std::move(__sl)).swap(*this); return *this; } void lock() { _M_lockable(); _M_pm->lock_shared(); _M_owns = true; } bool try_lock() { _M_lockable(); return _M_owns = _M_pm->try_lock_shared(); } void unlock() { if (!_M_owns) throw std::system_error( std::make_error_code(std::errc::resource_deadlock_would_occur)); _M_pm->unlock_shared(); _M_owns = false; } // Setters void swap(shared_lock& __u) noexcept { std::swap(_M_pm, __u._M_pm); std::swap(_M_owns, __u._M_owns); } mutex_type* release() noexcept { mutex_type* __ret = _M_pm; _M_pm = nullptr; _M_owns = false; return __ret; } // Getters bool owns_lock() const noexcept { return _M_owns; } explicit operator bool() const noexcept { return _M_owns; } mutex_type* mutex() const noexcept { return _M_pm; } private: void _M_lockable() const { if (_M_pm == nullptr) throw std::system_error( std::make_error_code(std::errc::operation_not_permitted)); if (_M_owns) throw std::system_error( std::make_error_code(std::errc::resource_deadlock_would_occur)); } mutex_type* _M_pm; bool _M_owns; }; /// Swap specialization for shared_lock template<typename _Mutex> void swap(shared_lock<_Mutex>& __x, shared_lock<_Mutex>& __y) noexcept { __x.swap(__y); } } /* namespace redgiant */ #endif /* SRC_MAIN_CORE_LOCK_SHARED_LOCK_H_ */
21.106557
74
0.677282
24f1ff8ebbeb87ab8c360e161cbab88919b739e3
1,541
c
C
conpad.c
ThymoNL/conpad
e9907091f6c03f0fe8464e71402d74a349848eb7
[ "MIT" ]
null
null
null
conpad.c
ThymoNL/conpad
e9907091f6c03f0fe8464e71402d74a349848eb7
[ "MIT" ]
null
null
null
conpad.c
ThymoNL/conpad
e9907091f6c03f0fe8464e71402d74a349848eb7
[ "MIT" ]
null
null
null
// SPDX-License-Identifier: MIT #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> void usage() { puts("Concatenate contents from all arguments and print to stdout."); } int main(int argc, char *argv[]) { const int padding = 1; if (argc < 2) { usage(); return 1; } for (int i = 1; i < argc; i++) { if (access(argv[i], R_OK) == -1) { if (errno == ENOENT) { fprintf(stderr, "%s: File does not exist.", argv[i]); return 1; } else if (errno == EACCES) { fprintf(stderr, "%s: Access denied.", argv[i]); return 1; } else { fprintf(stderr, "%s: Unknown error: %d", argv[i], errno); return 1; } } } FILE *f; char *buf = 0; long len = 0; long pos = 0; for (int i = 1; i < argc; i++) { int fn_len = strlen(argv[i]); f = fopen(argv[i], "r"); if (f) { fseek(f, 0, SEEK_END); int f_len = ftell(f); if (i < argc - 1) len += f_len + padding + fn_len + 5; // Prev. size + file size + padding + \n + file name + header else len += f_len + fn_len + 5; // Prev. size + file size + \n + file name + header fseek(f, 0, SEEK_SET); buf = realloc(buf, len); if (buf) { strcpy(buf + pos, "### "); pos += 4; strcpy(buf + pos, argv[i]); pos += fn_len; buf[pos++] = '\n'; fread(buf + pos, 1, f_len, f); pos += f_len; if (i < argc - 1) { for (int j = 0; j < padding; j++) buf[pos++] = '\n'; } } fclose(f); } } fputs(buf, stdout); free(buf); return 0; }
19.2625
102
0.523037
2a86ae53f1f4f138b74ef9b0cb36ae674f8d157c
385
h
C
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/FMLModelConfigLoader.h
ceekay1991/AliPayForDebug
5795e5db31e5b649d4758469b752585e63e84d94
[ "MIT" ]
5
2020-03-29T12:08:37.000Z
2021-05-26T05:20:11.000Z
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/FMLModelConfigLoader.h
ceekay1991/AliPayForDebug
5795e5db31e5b649d4758469b752585e63e84d94
[ "MIT" ]
null
null
null
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/FMLModelConfigLoader.h
ceekay1991/AliPayForDebug
5795e5db31e5b649d4758469b752585e63e84d94
[ "MIT" ]
5
2020-04-17T03:24:04.000Z
2022-03-30T05:42:17.000Z
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <objc/NSObject.h> @interface FMLModelConfigLoader : NSObject { } + (id)configFilesWithFolder:(id)arg1; + (id)loadConfigsWithConfigFile:(id)arg1; + (id)loadConfigsWithFolder:(id)arg1; @end
20.263158
90
0.701299
631b09393eb20ca344bc957afd9fc645c8e18a3f
2,420
h
C
Sources/CryGame C++/Solution1/CryCommon/CRETerrainSector.h
fromasmtodisasm/CryENGINE_MOD_SDK
0b242ffcf615cdc0177f6c96b03b4d60a4338321
[ "FSFAP" ]
null
null
null
Sources/CryGame C++/Solution1/CryCommon/CRETerrainSector.h
fromasmtodisasm/CryENGINE_MOD_SDK
0b242ffcf615cdc0177f6c96b03b4d60a4338321
[ "FSFAP" ]
null
null
null
Sources/CryGame C++/Solution1/CryCommon/CRETerrainSector.h
fromasmtodisasm/CryENGINE_MOD_SDK
0b242ffcf615cdc0177f6c96b03b4d60a4338321
[ "FSFAP" ]
1
2021-04-13T22:35:28.000Z
2021-04-13T22:35:28.000Z
////////////////////////////////////////////////////////////////////// // // Crytek Source code // Copyright (c) Crytek 2001-2004 // // File: CRETerrainSector.h // Description: Misc Renderer element interface. // // History: // - File created by Khonich Andrey // - February 2005: Modified by Marco Corbetta for SDK release // ////////////////////////////////////////////////////////////////////// #ifndef __CRECommon_H__ #define __CRECommon_H__ ////////////////////////////////////////////////////////////////////// class CRECommon : public CRendElement { friend class CRender3D; public: CRECommon() { mfSetType(eDATA_TerrainSector); mfUpdateFlags(FCEF_TRANSFORM); } virtual ~CRECommon() { } virtual void mfPrepare(); virtual bool mfDraw(SShader *ef, SShaderPass *sfm) { return true; } }; ////////////////////////////////////////////////////////////////////// class CREFarTreeSprites : public CRECommon { public: CREFarTreeSprites() { mfSetType(eDATA_FarTreeSprites); mfUpdateFlags(FCEF_TRANSFORM); } virtual bool mfDraw(SShader *ef, SShaderPass *sfm); }; ////////////////////////////////////////////////////////////////////// class CRETerrainDetailTextureLayers: public CRECommon { public: CRETerrainDetailTextureLayers() { mfSetType(eDATA_TerrainDetailTextureLayers); mfUpdateFlags(FCEF_TRANSFORM); } virtual bool mfDraw(SShader *ef, SShaderPass *sfm); }; ////////////////////////////////////////////////////////////////////// class CRETerrainParticles: public CRECommon { public: CRETerrainParticles() { mfSetType(eDATA_TerrainParticles); mfUpdateFlags(FCEF_TRANSFORM); } virtual bool mfDraw(SShader *ef, SShaderPass *sfm); }; ////////////////////////////////////////////////////////////////////// class CREClearStencil : public CRECommon { public: CREClearStencil() { mfSetType(eDATA_ClearStencil); mfUpdateFlags(FCEF_TRANSFORM); } virtual bool mfDraw(SShader *ef, SShaderPass *sfm); }; ////////////////////////////////////////////////////////////////////// class CREShadowMapGen: public CRECommon { public: CREShadowMapGen() { mfSetType(eDATA_ShadowMapGen); mfUpdateFlags(FCEF_TRANSFORM); } virtual bool mfDraw(SShader *ef, SShaderPass *sfm) { return true; } }; #endif // __CRECommon_H__
23.269231
71
0.525207
f24a77b3942cc03573cff9bd94f087f4be938918
439
h
C
Pods/YelpAPI/Classes/Client/YLPClient+Business.h
Armandocarrillo/YetiDate
f02583cd3dc29fac83c4dd38ca59ff70c357dd95
[ "MIT" ]
66
2016-04-14T17:53:20.000Z
2022-02-17T03:00:25.000Z
Pods/YelpAPI/Classes/Client/YLPClient+Business.h
Armandocarrillo/YetiDate
f02583cd3dc29fac83c4dd38ca59ff70c357dd95
[ "MIT" ]
61
2016-04-13T19:03:05.000Z
2020-08-26T04:33:22.000Z
Pods/YelpAPI/Classes/Client/YLPClient+Business.h
Armandocarrillo/YetiDate
f02583cd3dc29fac83c4dd38ca59ff70c357dd95
[ "MIT" ]
66
2016-04-27T16:03:33.000Z
2020-03-15T19:51:01.000Z
// // YLPClient+Business.h // Pods // // Created by David Chen on 1/4/16. // // #import "YLPClient.h" @class YLPBusiness; NS_ASSUME_NONNULL_BEGIN typedef void(^YLPBusinessCompletionHandler)(YLPBusiness * _Nullable business, NSError * _Nullable error); @interface YLPClient (Business) - (void)businessWithId:(NSString *)businessId completionHandler:(YLPBusinessCompletionHandler)completionHandler; @end NS_ASSUME_NONNULL_END
18.291667
105
0.767654
0bd535752d3a54ff97b2dfd1639c9009a9413b4a
653
h
C
tdd_game1/tdd_game1.h
nathhB/raylib-webrtc_bomberman
4d43e9d5856107e14371339c5d93af25f1cb58d8
[ "Zlib" ]
21
2020-04-27T17:45:13.000Z
2022-03-17T07:42:11.000Z
tdd_game1/tdd_game1.h
nathhB/raylib-webrtc_bomberman
4d43e9d5856107e14371339c5d93af25f1cb58d8
[ "Zlib" ]
null
null
null
tdd_game1/tdd_game1.h
nathhB/raylib-webrtc_bomberman
4d43e9d5856107e14371339c5d93af25f1cb58d8
[ "Zlib" ]
2
2020-05-16T17:22:03.000Z
2022-01-23T20:55:30.000Z
#ifndef TDD_GAME1_H_INCLUDED #define TDD_GAME1_H_INCLUDED #include <stdio.h> #include <raylib.h> #include <raymath.h> #include <tdd_ecs.h> #include <tdd_network.h> #define MAX_PLAYERS 4 #define PLAYER_NICKNAME_MAX_LENGTH 12 #define NEXT_ROUND_DELAY_MS 5000 #define ROUND_TIME_SEC 120 #define MAX_REQUIRED_ROUNDS 5 typedef struct game_settings { unsigned int players_count; unsigned int round_time; // in seconds unsigned int required_rounds_to_win; } game_settings_t; #include "src/map.h" #include "src/network/net_messages.h" #include "src/network/net_messages_factory.h" #include "src/network.h" #endif //TDD_GAME1_H_INCLUDED
23.321429
45
0.782542
921f51372bee8e3858f7ce4bb8bf6bd1df0710b1
131
h
C
ui/HUImageView.h
rsms/hunch-cocoa
43d56bad1bb8b8df39f3135ff139cf9e0af41c02
[ "Unlicense" ]
2
2015-03-23T19:12:15.000Z
2016-05-16T04:33:24.000Z
ui/HUImageView.h
rsms/hunch-cocoa
43d56bad1bb8b8df39f3135ff139cf9e0af41c02
[ "Unlicense" ]
null
null
null
ui/HUImageView.h
rsms/hunch-cocoa
43d56bad1bb8b8df39f3135ff139cf9e0af41c02
[ "Unlicense" ]
null
null
null
@interface HUImageView : NSImageView { NSArray *paths; } @property(assign) NSArray *paths; @property(assign) NSString *path; @end
18.714286
38
0.748092
d8b787bd46b00eba8470b905bba36e0149321046
955
h
C
skypath_lib.h
agabrown/astrometric-sky-path
a72e4dc2db09038191f2fc03969228d91b4f39ee
[ "MIT" ]
3
2019-07-16T16:59:20.000Z
2022-02-17T07:15:37.000Z
skypath_lib.h
agabrown/astrometric-sky-path
a72e4dc2db09038191f2fc03969228d91b4f39ee
[ "MIT" ]
null
null
null
skypath_lib.h
agabrown/astrometric-sky-path
a72e4dc2db09038191f2fc03969228d91b4f39ee
[ "MIT" ]
null
null
null
/* * Header file for skypath_lib.c * * Anthony Brown 23 Aug 2011 - Oct 2018 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "sofa.h" #include "sofam.h" #include "vecmat_utils.h" #include "astrometry.h" // Rename a number of the SOFA constants for clarity static const double RADIAN_TO_DEGREE = DR2D; static const double PARSEC_TO_AU = DR2AS; static const double AU_TO_KM = DAU/1000.0; static const double PI = DPI; /* Function prototypes */ void usage(char *argv[]); void usageLong(char *argv[]); void parseArgs(int argc, char *argv[], int *npoints, star *theStar, obsEpochs *theObsEpochs); void initCalc(star *theStar, obsEpochs *theObsEpochs); void myUnitsToSofa(star *myStar, star *sofaStar); void sofaUnitsToMine(star *sofaStar, star *myStar); void calcSkyPath(obsEpochs *theObsEpochs, int npoints, star *sofaStar, double *times, double* alpha, double *delta, double *xi, double *eta);
24.487179
93
0.726702
b14953d7c42857f62f591e778f1b08d0217fc952
6,953
h
C
xar/src/cpp_stl_11/xar.h
kaitai-io/formats-kaitai-io.github.io
2700514a2a8f67c5351fe93962c70abea02fd3d3
[ "0BSD" ]
4
2018-12-10T09:21:19.000Z
2021-11-03T16:43:22.000Z
xar/src/cpp_stl_11/xar.h
kaitai-io/formats-kaitai-io.github.io
2700514a2a8f67c5351fe93962c70abea02fd3d3
[ "0BSD" ]
null
null
null
xar/src/cpp_stl_11/xar.h
kaitai-io/formats-kaitai-io.github.io
2700514a2a8f67c5351fe93962c70abea02fd3d3
[ "0BSD" ]
3
2019-04-08T08:22:22.000Z
2021-10-10T19:11:51.000Z
#pragma once // This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild #include "kaitai/kaitaistruct.h" #include <stdint.h> #include <memory> #if KAITAI_STRUCT_VERSION < 9000L #error "Incompatible Kaitai Struct C++/STL API: version 0.9 or later is required" #endif /** * From [Wikipedia](https://en.wikipedia.org/wiki/Xar_(archiver)): * * "XAR (short for eXtensible ARchive format) is an open source file archiver * and the archiver’s file format. It was created within the OpenDarwin project * and is used in macOS X 10.5 and up for software installation routines, as * well as browser extensions in Safari 5.0 and up." * \sa https://github.com/mackyle/xar/wiki/xarformat Source */ class xar_t : public kaitai::kstruct { public: class file_header_prefix_t; class file_header_t; class toc_type_t; enum checksum_algorithms_apple_t { CHECKSUM_ALGORITHMS_APPLE_NONE = 0, CHECKSUM_ALGORITHMS_APPLE_SHA1 = 1, CHECKSUM_ALGORITHMS_APPLE_MD5 = 2, CHECKSUM_ALGORITHMS_APPLE_SHA256 = 3, CHECKSUM_ALGORITHMS_APPLE_SHA512 = 4 }; xar_t(kaitai::kstream* p__io, kaitai::kstruct* p__parent = nullptr, xar_t* p__root = nullptr); private: void _read(); void _clean_up(); public: ~xar_t(); class file_header_prefix_t : public kaitai::kstruct { public: file_header_prefix_t(kaitai::kstream* p__io, xar_t* p__parent = nullptr, xar_t* p__root = nullptr); private: void _read(); void _clean_up(); public: ~file_header_prefix_t(); private: std::string m_magic; uint16_t m_len_header; xar_t* m__root; xar_t* m__parent; public: std::string magic() const { return m_magic; } /** * internal; access `_root.header.len_header` instead */ uint16_t len_header() const { return m_len_header; } xar_t* _root() const { return m__root; } xar_t* _parent() const { return m__parent; } }; class file_header_t : public kaitai::kstruct { public: file_header_t(kaitai::kstream* p__io, xar_t* p__parent = nullptr, xar_t* p__root = nullptr); private: void _read(); void _clean_up(); public: ~file_header_t(); private: bool f_checksum_algorithm_name; std::string m_checksum_algorithm_name; public: /** * If it is not * * * `""` (empty string), indicating an unknown integer value (access * `checksum_algorithm_int` for debugging purposes to find out * what that value is), or * * `"none"`, indicating that the TOC checksum is not provided (in that * case, the `<checksum>` property or its `style` attribute should be * missing, or the `style` attribute must be set to `"none"`), * * it must exactly match the `style` attribute value of the * `<checksum>` property in the root node `<toc>`. See * <https://github.com/mackyle/xar/blob/66d451d/xar/lib/archive.c#L345-L371> * for reference. * * The `xar` (eXtensible ARchiver) program [uses OpenSSL's function * `EVP_get_digestbyname`]( * https://github.com/mackyle/xar/blob/66d451d/xar/lib/archive.c#L328 * ) to verify this value (if it's not `""` or `"none"`, of course). * So it's reasonable to assume that this can only have one of the values * that OpenSSL recognizes. */ std::string checksum_algorithm_name(); private: bool f_has_checksum_alg_name; bool m_has_checksum_alg_name; public: bool has_checksum_alg_name(); private: bool f_len_header; uint16_t m_len_header; public: uint16_t len_header(); private: uint16_t m_version; uint64_t m_len_toc_compressed; uint64_t m_toc_length_uncompressed; uint32_t m_checksum_algorithm_int; std::string m_checksum_alg_name; bool n_checksum_alg_name; public: bool _is_null_checksum_alg_name() { checksum_alg_name(); return n_checksum_alg_name; }; private: xar_t* m__root; xar_t* m__parent; public: uint16_t version() const { return m_version; } uint64_t len_toc_compressed() const { return m_len_toc_compressed; } uint64_t toc_length_uncompressed() const { return m_toc_length_uncompressed; } /** * internal; access `checksum_algorithm_name` instead */ uint32_t checksum_algorithm_int() const { return m_checksum_algorithm_int; } /** * internal; access `checksum_algorithm_name` instead */ std::string checksum_alg_name() const { return m_checksum_alg_name; } xar_t* _root() const { return m__root; } xar_t* _parent() const { return m__parent; } }; class toc_type_t : public kaitai::kstruct { public: toc_type_t(kaitai::kstream* p__io, xar_t* p__parent = nullptr, xar_t* p__root = nullptr); private: void _read(); void _clean_up(); public: ~toc_type_t(); private: std::string m_xml_string; xar_t* m__root; xar_t* m__parent; public: std::string xml_string() const { return m_xml_string; } xar_t* _root() const { return m__root; } xar_t* _parent() const { return m__parent; } }; private: bool f_checksum_algorithm_other; int8_t m_checksum_algorithm_other; public: /** * \sa https://github.com/mackyle/xar/blob/66d451d/xar/include/xar.h.in#L85 Source */ int8_t checksum_algorithm_other(); private: std::unique_ptr<file_header_prefix_t> m_header_prefix; std::unique_ptr<file_header_t> m_header; std::unique_ptr<toc_type_t> m_toc; xar_t* m__root; kaitai::kstruct* m__parent; std::string m__raw_header; std::unique_ptr<kaitai::kstream> m__io__raw_header; std::string m__raw_toc; std::unique_ptr<kaitai::kstream> m__io__raw_toc; std::string m__raw__raw_toc; public: /** * internal; access `_root.header` instead */ file_header_prefix_t* header_prefix() const { return m_header_prefix.get(); } file_header_t* header() const { return m_header.get(); } /** * zlib compressed XML further describing the content of the archive */ toc_type_t* toc() const { return m_toc.get(); } xar_t* _root() const { return m__root; } kaitai::kstruct* _parent() const { return m__parent; } std::string _raw_header() const { return m__raw_header; } kaitai::kstream* _io__raw_header() const { return m__io__raw_header.get(); } std::string _raw_toc() const { return m__raw_toc; } kaitai::kstream* _io__raw_toc() const { return m__io__raw_toc.get(); } std::string _raw__raw_toc() const { return m__raw__raw_toc; } };
29.713675
107
0.646052
d24747ffb50cd975dca357c4a214d0293f5edb4f
1,373
c
C
libk/WARF/wind.c
eingaeph/pip.imbue.hood
7aa271dadd1d23b19a95a68961b19f4249eec14e
[ "BSD-2-Clause" ]
null
null
null
libk/WARF/wind.c
eingaeph/pip.imbue.hood
7aa271dadd1d23b19a95a68961b19f4249eec14e
[ "BSD-2-Clause" ]
null
null
null
libk/WARF/wind.c
eingaeph/pip.imbue.hood
7aa271dadd1d23b19a95a68961b19f4249eec14e
[ "BSD-2-Clause" ]
null
null
null
#include "../libk.h" /* wind.c write a window into text to the screen window coordinates require intital cursor at top left that is text coordinate position xmin, ymin is at the top left at the screen note: wind.c is written in terms of text coordinates x,y */ void wind(int xmin, int xmax, int ymin, int ymax, int numbLines) { assert(ymin >= 0); assert(ymax < glob.numbLines); assert(ymax >= ymin); assert((ymax - ymin) < glob.rows); for (int y = ymin; y <= ymax; y++) { // description of <for> idiom // for (once first; before each conditional exec; after exec) int x; char* s = xmin + text[y].row; for ( x = xmin; x <= xmax; x++) { // following are two tests to determine whether *s should be written // to the screen if (x>=text[y].size ) {break;}; if (*s == '\n') {break;}; // *s tests ok, write it to the screen printf("%c",*s); s++; } // the next statement serves to omit the newline after writing the // last line of the window // otherwise the top line of the window gets pushed off the screen // when the window should exactly fit the screen if(y != ymax) printf("\n"); else fflush(stdout); // the final else fflush displays the last line without a newline // which would move the cursor to the next line } }
26.921569
69
0.613256
9a69d85687d9ae65f3745c7f6a899fa3b7ac338d
2,348
h
C
libncftp-3.2.6/sio/wincfg.h
AYM1607/advanced_programming_ad2020
e10d0ec0504c1aa1df1555f4e9a330d7ff5d3c61
[ "MIT" ]
null
null
null
libncftp-3.2.6/sio/wincfg.h
AYM1607/advanced_programming_ad2020
e10d0ec0504c1aa1df1555f4e9a330d7ff5d3c61
[ "MIT" ]
null
null
null
libncftp-3.2.6/sio/wincfg.h
AYM1607/advanced_programming_ad2020
e10d0ec0504c1aa1df1555f4e9a330d7ff5d3c61
[ "MIT" ]
null
null
null
/* config.h. Generated automatically by configure. */ /* config.h.in. Generated automatically from configure.in by autoheader. */ /* #define alarm_time_t unsigned int */ /* leave undefined */ #define gethost_addrptr_t const char * #define gethostname_size_t int #define listen_backlog_t int #define read_return_t int #define read_size_t unsigned int #define sockaddr_size_t int #define sockopt_size_t int #define SETSOCKOPT_ARG4 (char *) #define GETSOCKOPT_ARG4 (char *) #define write_return_t int #define write_size_t unsigned int #define tv_sec_t long #define tv_usec_t long #define recv_return_t int #define recv_size_t unsigned int #define send_return_t int #define send_size_t unsigned int #define sa_family_t short /* #define CAN_USE_SYS_SELECT_H 1 */ /* Define to empty if the keyword does not work. */ /* #undef const */ /* #undef HAVE_MSGHDR_ACCRIGHTS */ /* #define HAVE_MSGHDR_CONTROL 1 */ /* Define if you have sigsetjmp and siglongjmp. */ /* #define HAVE_SIGSETJMP 1 */ /* #undef HAVE_SOCKADDR_UN_SUN_LEN */ /* #define HAVE_STRUCT_CMSGDHR 1 */ /* Define to the type of arg1 for select(). */ #define SELECT_TYPE_ARG1 int /* Define to the type of args 2, 3 and 4 for select(). */ #define SELECT_TYPE_ARG234 (fd_set FAR *) /* Define to the type of arg5 for select(). */ #define SELECT_TYPE_ARG5 (const struct timeval FAR *) /* Define to `unsigned' if <sys/types.h> doesn't define. */ /* #undef size_t */ /* Define if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Define if you have the sigaction function. */ /* #define HAVE_SIGACTION 1 */ /* Define if you have the <sys/select.h> header file. */ /* #define HAVE_SYS_SELECT_H 1 */ /* Define if you have the <sys/time.h> header file. */ /* #undef HAVE_SYS_TIME_H */ /* Define if you have the <sys/un.h> header file. */ /* #define HAVE_SYS_UN_H 1 */ /* Define if you have the <unistd.h> header file. */ /* #define HAVE_UNISTD_H 1 */ /* Define if you have the 44bsd library (-l44bsd). */ /* #undef HAVE_LIB44BSD */ /* Define if you have the gen library (-lgen). */ /* #undef HAVE_LIBGEN */ /* Define if you have the nsl library (-lnsl). */ /* #undef HAVE_LIBNSL */ /* Define if you have the resolv library (-lresolv). */ /* #undef HAVE_LIBRESOLV */ /* Define if you have the socket library (-lsocket). */ /* #undef HAVE_LIBSOCKET */
27.952381
77
0.710392
82c93da676cc4aa6fc91de8bfa62a2718d75a105
304
h
C
usr/libexec/assistant_cdmd/NSData-CDMJSONSerialization.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
usr/libexec/assistant_cdmd/NSData-CDMJSONSerialization.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
usr/libexec/assistant_cdmd/NSData-CDMJSONSerialization.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 Steve Nygard. // #import <Foundation/NSData.h> @interface NSData (CDMJSONSerialization) - (id)_cdm_safeJSONString; // IMP=0x0000000100035d08 @end
23.384615
120
0.720395
324101ce163cfcdb6507916f6d0f4ec829670f7d
243
c
C
baekjoon/1735/source.c
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
4
2020-02-02T08:34:46.000Z
2021-10-01T11:21:17.000Z
baekjoon/1735/source.c
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
1
2021-09-04T14:03:50.000Z
2021-09-04T14:03:50.000Z
baekjoon/1735/source.c
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
null
null
null
#include <stdio.h> int e(int a, int b){ return a%b ? e(b, a%b) : b; } int main(void){ int a, b, c, d, q, w, k, t; scanf("%d %d %d %d", &a, &b, &c, &d); q = a*d+c*b; w = b*d; k = e(q, w); printf("%d %d", q/k, w/k); }
16.2
41
0.399177
aabb89f8fff226e4c9f422b0969e148887a05e3b
632
h
C
Dark soft/Buhtrap Source Code/10.vnc/VNC/VNC/layout.h
ExaByt3s/hack_scripts
cc801b36ea25f3b5a82d2900f53f5036e7abd8ad
[ "WTFPL" ]
3
2021-01-22T19:32:23.000Z
2022-01-03T01:06:44.000Z
Dark soft/IFSB_Bot src/IFSB_Source Code/10.vnc/VNC/VNC/layout.h
a04512/hack_scripts
cc801b36ea25f3b5a82d2900f53f5036e7abd8ad
[ "WTFPL" ]
null
null
null
Dark soft/IFSB_Bot src/IFSB_Source Code/10.vnc/VNC/VNC/layout.h
a04512/hack_scripts
cc801b36ea25f3b5a82d2900f53f5036e7abd8ad
[ "WTFPL" ]
1
2019-06-18T22:10:53.000Z
2019-06-18T22:10:53.000Z
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // VNC project. Version 1.9.17.3 // // module: layout.h // $Revision: 186 $ // $Date: 2014-07-04 19:05:58 +0400 (Пт, 04 июл 2014) $ // description: // keyboard layout switcher #ifndef LAYOUTSWITCHER_H_INCLUDED #define LAYOUTSWITCHER_H_INCLUDED #include <shellapi.h> #define IDM_AUTODETECT 100 #define ICONWIDTH 16 #define ICONHEIGHT 16 #define WM_TRAYMENU WM_USER+1488 void LS_Start(PVNC_SESSION pSession); void LS_Stop(PVNC_SESSION pSession); #endif // LAYOUTSWITCHER_H_INCLUDED
26.333333
119
0.583861
6537f64b0f68878377fe82670135d6eff6109907
4,953
h
C
celix/framework/public/include/bundle_revision.h
marcojansen/android-inaetics
c9b938c6a1323a96e8d7094f3a74300f67872bc4
[ "Apache-2.0" ]
null
null
null
celix/framework/public/include/bundle_revision.h
marcojansen/android-inaetics
c9b938c6a1323a96e8d7094f3a74300f67872bc4
[ "Apache-2.0" ]
null
null
null
celix/framework/public/include/bundle_revision.h
marcojansen/android-inaetics
c9b938c6a1323a96e8d7094f3a74300f67872bc4
[ "Apache-2.0" ]
null
null
null
/* *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. */ /** * * @defgroup BundleRevision Bundle Revision * @ingroup framework * @{ * * \author <a href="mailto:dev@celix.apache.org">Apache Celix Project Team</a> * \date April 12, 2011 * \copyright Apache License, Version 2.0 */ #ifndef BUNDLE_REVISION_H_ #define BUNDLE_REVISION_H_ #include <stdio.h> #include "celix_errno.h" #include "manifest.h" #include "celix_log.h" #include "array_list.h" /** * Typedef for bundle_revision_pt. * * A bundle revision represents the content of a bundle. A revision is associated with a bundle archive. * An archive can have multiple revisions, each update of a bundle results in a new one. * * In a revision the content of a bundle (ZIP file) is extracted to a specified location inside the archive. */ typedef struct bundleRevision * bundle_revision_pt; /** * Creates a new revision for the given inputFile or location. * The location parameter is used to identify the bundle, in case of an update or download, the inputFile * parameter can be used to point to the actual data. In the OSGi specification this is the inputstream. * * @param pool The pool on which this revision has to be allocated. * @param root The root for this revision in which the bundle is extracted and state is stored. * @param location The location associated with the revision * @param revisionNr The number of the revision * @param inputFile The (optional) location of the file to use as input for this revision * @param[out] bundle_revision The output parameter for the created revision. * * @return Status code indication failure or success: * - CELIX_SUCCESS when no errors are encountered. * - CELIX_ENOMEM If allocating memory for <code>bundle_revision</code> failed. */ celix_status_t bundleRevision_create(char *root, char *location, long revisionNr, char *inputFile, bundle_revision_pt *bundle_revision); celix_status_t bundleRevision_destroy(bundle_revision_pt revision); /** * Retrieves the revision number of the given revision. * * @param revision The revision to get the number for. * @param[out] revisionNr The revision number. * * @return Status code indication failure or success: * - CELIX_SUCCESS when no errors are encountered. * - CELIX_ILLEGAL_ARGUMENT If <code>revision</code> is illegal. */ celix_status_t bundleRevision_getNumber(bundle_revision_pt revision, long *revisionNr); /** * Retrieves the location of the given revision. * * @param revision The revision to get the location for. * @param[out] location The location. * * @return Status code indication failure or success: * - CELIX_SUCCESS when no errors are encountered. * - CELIX_ILLEGAL_ARGUMENT If <code>revision</code> is illegal. */ celix_status_t bundleRevision_getLocation(bundle_revision_pt revision, char **location); /** * Retrieves the root of the given revision. * * @param revision The revision to get the location for. * @param[out] root The root. * * @return Status code indication failure or success: * - CELIX_SUCCESS when no errors are encountered. * - CELIX_ILLEGAL_ARGUMENT If <code>revision</code> is illegal. */ celix_status_t bundleRevision_getRoot(bundle_revision_pt revision, char **root); /** * Retrieves the manifest of the given revision. * * @param revision The revision to get the manifest for. * @param[out] manifest The manifest. * * @return Status code indication failure or success: * - CELIX_SUCCESS when no errors are encountered. * - CELIX_ILLEGAL_ARGUMENT If <code>revision</code> is illegal. */ celix_status_t bundleRevision_getManifest(bundle_revision_pt revision, manifest_pt *manifest); /** * Retrieves the handles of the installed libraries for this revision. * * @param revision The revision to get the manifest for. * @param[out] handles array_list_pt containing the handles. * * @return Status code indication failure or success: * - CELIX_SUCCESS when no errors are encountered. * - CELIX_ILLEGAL_ARGUMENT If <code>revision</code> is illegal. */ celix_status_t bundleRevision_getHandles(bundle_revision_pt revision, array_list_pt *handles); #endif /* BUNDLE_REVISION_H_ */ /** * @} */
36.962687
136
0.752271
6539513eeca719af100a5e1d060d1acb253e2491
1,606
h
C
include/VRoutine/inner/AtomicQueueBase.h
fengsheng666/VictorRoutine
d9c9b9c9e49ead47812a0a1ddb08e777cea3a4cf
[ "Apache-2.0" ]
3
2021-09-16T08:49:25.000Z
2021-11-07T20:20:40.000Z
include/VRoutine/inner/AtomicQueueBase.h
fengsheng666/VictorRoutine
d9c9b9c9e49ead47812a0a1ddb08e777cea3a4cf
[ "Apache-2.0" ]
null
null
null
include/VRoutine/inner/AtomicQueueBase.h
fengsheng666/VictorRoutine
d9c9b9c9e49ead47812a0a1ddb08e777cea3a4cf
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2020 Feng Sheng(EN. Victor Fung) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef ATOMICQUEUEBASE_H_VROUTINE #define ATOMICQUEUEBASE_H_VROUTINE #include "../VRoutineDef.h" #include <atomic> #include <functional> namespace VictorRoutine { class VROUTINE_API AtomicQueueBase { public: struct AtomicQueueItem { AtomicQueueItem() : _ptr(0) { _next.store(0); } AtomicQueueItem(AtomicQueueItem* next, void* ptr) : _ptr(ptr){ _next.store(next); } inline AtomicQueueItem* getNext() { return _next.load(); } inline void setNext(AtomicQueueItem* next) { _next.store(next); } std::atomic<AtomicQueueItem*> _next; void* _ptr; }; ~AtomicQueueBase(); void append(AtomicQueueItem* begin, AtomicQueueItem* end, int length); AtomicQueueItem* pop(); AtomicQueueItem* pop(std::function<bool(void*)> filterFunc); void front(std::function<void(const void*)> recver); protected: AtomicQueueBase(); private: std::atomic<AtomicQueueItem*> m_head; std::atomic<AtomicQueueItem*> m_tail; }; } #endif
26.327869
75
0.709838
04cb07ee173b0eda4db5b211cdc4a01983bcebc3
1,688
h
C
src/include/fst/script/reweight.h
grammatek/openfst
ee52bdb80e60a0d0e82ba9399d53a4bb876a966a
[ "Apache-2.0" ]
25
2016-02-19T18:03:58.000Z
2022-03-09T08:12:41.000Z
src/include/fst/script/reweight.h
grammatek/openfst
ee52bdb80e60a0d0e82ba9399d53a4bb876a966a
[ "Apache-2.0" ]
1
2021-03-11T12:30:20.000Z
2021-03-11T12:30:20.000Z
src/include/fst/script/reweight.h
grammatek/openfst
ee52bdb80e60a0d0e82ba9399d53a4bb876a966a
[ "Apache-2.0" ]
22
2016-02-09T07:49:44.000Z
2022-02-03T06:40:27.000Z
// Copyright 2005-2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the 'License'); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // See www.openfst.org for extensive documentation on this weighted // finite-state transducer library. #ifndef FST_SCRIPT_REWEIGHT_H_ #define FST_SCRIPT_REWEIGHT_H_ #include <tuple> #include <vector> #include <fst/reweight.h> #include <fst/script/fst-class.h> #include <fst/script/script-impl.h> #include <fst/script/weight-class.h> namespace fst { namespace script { using ReweightArgs = std::tuple<MutableFstClass *, const std::vector<WeightClass> &, ReweightType>; template <class Arc> void Reweight(ReweightArgs *args) { using Weight = typename Arc::Weight; MutableFst<Arc> *fst = std::get<0>(*args)->GetMutableFst<Arc>(); const std::vector<WeightClass> &potentials = std::get<1>(*args); std::vector<Weight> typed_potentials; internal::CopyWeights(potentials, &typed_potentials); Reweight(fst, typed_potentials, std::get<2>(*args)); } void Reweight(MutableFstClass *fst, const std::vector<WeightClass> &potentials, ReweightType reweight_type); } // namespace script } // namespace fst #endif // FST_SCRIPT_REWEIGHT_H_
32.461538
80
0.727488
ca92b542457c11858986abe3b1426e45b0eb5d6e
3,688
c
C
Cores/Atari800/atari800-src/pbi_proto80.c
werminghoff/Provenance
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
[ "BSD-3-Clause" ]
3,459
2015-01-07T14:07:09.000Z
2022-03-25T03:51:10.000Z
Cores/Atari800/atari800-src/pbi_proto80.c
werminghoff/Provenance
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
[ "BSD-3-Clause" ]
1,046
2018-03-24T17:56:16.000Z
2022-03-23T08:13:09.000Z
Cores/Atari800/atari800-src/pbi_proto80.c
werminghoff/Provenance
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
[ "BSD-3-Clause" ]
549
2015-01-07T14:07:15.000Z
2022-01-07T16:13:05.000Z
/* * pbi_proto.c - Emulation of a prototype 80 column board for the * Atari 1090 expansion interface. * * Copyright (C) 2007-2008 Perry McFarlane * Copyright (C) 2002-2008 Atari800 development team (see DOC/CREDITS) * * This file is part of the Atari800 emulator project which emulates * the Atari 400, 800, 800XL, 130XE, and 5200 8-bit computers. * * Atari800 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. * * Atari800 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 Atari800; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "atari.h" #include "pbi.h" #include "pbi_proto80.h" #include "util.h" #include "log.h" #include "memory.h" #include <stdlib.h> #define PROTO80_PBI_NUM 2 #define PROTO80_MASK (1 << PROTO80_PBI_NUM) static UBYTE *proto80rom; static char proto80_rom_filename[FILENAME_MAX]; int PBI_PROTO80_enabled = FALSE; #ifdef PBI_DEBUG #define D(a) a #else #define D(a) do{}while(0) #endif int PBI_PROTO80_Initialise(int *argc, char *argv[]) { int i, j; for (i = j = 1; i < *argc; i++) { if (strcmp(argv[i], "-proto80") == 0) { Log_print("proto80 enabled"); PBI_PROTO80_enabled = TRUE; } else { if (strcmp(argv[i], "-help") == 0) { Log_print("\t-proto80 Emulate a prototype 80 column board for the 1090"); } argv[j++] = argv[i]; } } *argc = j; if (PBI_PROTO80_enabled) { proto80rom = (UBYTE *)Util_malloc(0x800); if (!Atari800_LoadImage(proto80_rom_filename, proto80rom, 0x800)) { free(proto80rom); PBI_PROTO80_enabled = FALSE; Log_print("Couldn't load proto80 rom image"); return FALSE; } else { Log_print("loaded proto80 rom image"); PBI_D6D7ram = TRUE; } } return TRUE; } void PBI_PROTO80_Exit(void) { if (PBI_PROTO80_enabled) { free(proto80rom); PBI_PROTO80_enabled = FALSE; } } int PBI_PROTO80_ReadConfig(char *string, char *ptr) { if (strcmp(string, "PROTO80_ROM") == 0) Util_strlcpy(proto80_rom_filename, ptr, sizeof(proto80_rom_filename)); else return FALSE; /* no match */ return TRUE; /* matched something */ } void PBI_PROTO80_WriteConfig(FILE *fp) { fprintf(fp, "PROTO80_ROM=%s\n", proto80_rom_filename); } int PBI_PROTO80_D1GetByte(UWORD addr, int no_side_effects) { int result = PBI_NOT_HANDLED; if (PBI_PROTO80_enabled) { } return result; } void PBI_PROTO80_D1PutByte(UWORD addr, UBYTE byte) { } int PBI_PROTO80_D1ffPutByte(UBYTE byte) { int result = 0; /* handled */ if (PBI_PROTO80_enabled && byte == PROTO80_MASK) { memcpy(MEMORY_mem + 0xd800, proto80rom, 0x800); D(printf("PROTO80 rom activated\n")); } else result = PBI_NOT_HANDLED; return result; } UBYTE PBI_PROTO80_GetPixels(int scanline, int column) { #define PROTO80_ROWS 24 #define PROTO80_CELL_HEIGHT 8 UBYTE character; UBYTE invert; UBYTE font_data; int row = scanline / PROTO80_CELL_HEIGHT; int line = scanline % PROTO80_CELL_HEIGHT; if (row >= PROTO80_ROWS) { return 0; } character = MEMORY_mem[0x9800 + row*80 + column]; invert = 0x00; if (character & 0x80) { invert = 0xff; character &= 0x7f; } font_data = MEMORY_mem[0xe000 + character*8 + line]; font_data ^= invert; return font_data; } /* vim:ts=4:sw=4: */
24.104575
85
0.708243
1082afdf0b4b76b0432278234fd322b2347ab3b5
793
h
C
matMPi.h
Nayaco/Mpi_Matrix
bb7849eb5f1d49c64bf94f39cee6fddd601ce43a
[ "MIT" ]
null
null
null
matMPi.h
Nayaco/Mpi_Matrix
bb7849eb5f1d49c64bf94f39cee6fddd601ce43a
[ "MIT" ]
null
null
null
matMPi.h
Nayaco/Mpi_Matrix
bb7849eb5f1d49c64bf94f39cee6fddd601ce43a
[ "MIT" ]
null
null
null
#ifndef MATMPI_H #define MATMPI_H #include <assert.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <mpi.h> #include "mat.h" #define NOSYNC 0 #define SYNC 1 #define MIN_LEN_P 131072 struct conn{ MPI_Comm _comm; mwise_callback *_wiseList; int list_len; int list_max; }; typedef struct conn *connPtr; connPtr CreateConn(MPI_Comm comm); void FreeConn(connPtr conn); void Addfun(connPtr conn, mwise_callback func); void synclizeMat(void* T, int size, MPI_Comm comm); matPtr AddMpi(matPtr A, matPtr B, connPtr conn, int sync); matPtr MultMpi(matPtr A, matPtr B, connPtr conn, int sync); int MWiseMpi(matPtr A, uint64_t func, connPtr conn, int sync); matPtr StrussenMpi(matPtr A, matPtr B, connPtr conn, int sync); #endif
20.333333
63
0.711223
b783b59d15e14896a37defda03a9729d1a587f39
903
h
C
usr/include/spike-fuzzer/spike_oncrpc.h
SofianeHamlaoui/Spike-Fuzzer
24551e4fa7a5183f22390a4a274229b122d2e55f
[ "MIT" ]
2
2021-01-19T18:48:54.000Z
2021-03-19T13:34:45.000Z
usr/include/spike-fuzzer/spike_oncrpc.h
SofianeHamlaoui/Spike-Fuzzer
24551e4fa7a5183f22390a4a274229b122d2e55f
[ "MIT" ]
null
null
null
usr/include/spike-fuzzer/spike_oncrpc.h
SofianeHamlaoui/Spike-Fuzzer
24551e4fa7a5183f22390a4a274229b122d2e55f
[ "MIT" ]
3
2019-12-13T17:47:56.000Z
2021-03-11T21:34:14.000Z
/* spike_oncrpc.h * Dominique Brezinski, 2002 * License: GPL v2.0 * * This is the public header file for spike_oncrpc.c * Use these functions to fuzz ONC-RPC applications to your heart's content */ #include <sys/types.h> #include "spike.h" struct onc_endpoint { uint prognum; uint progver; uint proto; uint port; }; void s_onc_call_header(uint, uint, uint, uint); void s_onc_opaqueauth_none(); void s_onc_opaqueauth_sys(uint, unsigned char*, uint, uint, uint*, uint); void s_onc_verifier_none(); int s_binary_block_size_onc_recordfrag(char*); int s_onc_push_random_bytes(uint); void s_onc_push_random_xdr_thing(); int s_onc_do_portmap_getport(char*, struct onc_endpoint*); int s_onc_do_portmap_dump(char*, struct onc_endpoint*, uint); int s_onc_read_reply(struct spike*, unsigned char*, uint*); int s_onc_parse_response(unsigned char*, uint, unsigned char*, uint);
21.5
75
0.750831
2e8e68a17cfb821f44c72bdae0fed1754c7099e5
22,488
c
C
openair2/NETWORK_DRIVER/MESH/tool.c
danghoaison91/openairinterface
ca28acccb2dfe85a0644d5fd6d379928d89f72a6
[ "Apache-2.0" ]
9
2019-09-09T19:57:39.000Z
2022-02-16T02:03:51.000Z
openair2/NETWORK_DRIVER/MESH/tool.c
danghoaison91/openairinterface
ca28acccb2dfe85a0644d5fd6d379928d89f72a6
[ "Apache-2.0" ]
null
null
null
openair2/NETWORK_DRIVER/MESH/tool.c
danghoaison91/openairinterface
ca28acccb2dfe85a0644d5fd6d379928d89f72a6
[ "Apache-2.0" ]
5
2019-06-11T17:18:47.000Z
2021-10-16T04:05:07.000Z
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the OAI Public License, Version 1.1 (the "License"); you may not use this file * except in compliance with the License. * You may obtain a copy of the License at * * http://www.openairinterface.org/?page_id=698 * * 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. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ #include "local.h" #include "proto_extern.h" //#include <linux/in.h> //#include <net/ndisc.h> //#include <linux/icmpv6.h> //#include <linux/icmp.h> //#include <linux/udp.h> //#include <linux/tcp.h> //#define NAS_DEBUG_TOOL 1 //--------------------------------------------------------------------------- // void nas_TOOL_fct(struct classifier_entity *gc, uint8_t fct) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_FCT - begin \n"); #endif if (gc==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_FCT - input parameter gc is NULL \n"); #endif return; } // End debug information switch(fct) { case NAS_FCT_QOS_SEND: gc->fct=nas_COMMON_QOS_send; break; case NAS_FCT_CTL_SEND: gc->fct=nas_CTL_send; break; case NAS_FCT_DC_SEND: gc->fct=nas_mesh_DC_send_sig_data_request; break; case NAS_FCT_DEL_SEND: gc->fct=nas_COMMON_del_send; break; default: gc->fct=nas_COMMON_del_send; } } //--------------------------------------------------------------------------- uint8_t nas_TOOL_invfct(struct classifier_entity *gc) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_INVFCT - begin \n"); #endif if (gc==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_INVFCT - input parameter gc is NULL \n"); #endif return 0; } // End debug information if (gc->fct==nas_COMMON_QOS_send) return NAS_FCT_QOS_SEND; if (gc->fct==nas_CTL_send) return NAS_FCT_CTL_SEND; if (gc->fct==nas_COMMON_del_send) return NAS_FCT_DEL_SEND; if (gc->fct==nas_mesh_DC_send_sig_data_request) return NAS_FCT_DC_SEND; return 0; } //--------------------------------------------------------------------------- uint8_t nas_TOOL_get_dscp6(struct ipv6hdr *iph) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_GET_DSCP6 - begin \n"); #endif if (iph==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_GET_DSCP6 - input parameter iph is NULL \n"); #endif return 0; } // End debug information return (ntohl(((*(__u32 *)iph)&NAS_TRAFFICCLASS_MASK)))>>22; //return ntohs(*(const __be16 *)iph) >> 4; // see linux/dsfield.h } //--------------------------------------------------------------------------- uint8_t nas_TOOL_get_dscp4(struct iphdr *iph) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_GET_DSCP4 - begin \n"); #endif if (iph==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_GET_DSCP4 - input parameter iph is NULL \n"); #endif return 0; } // End debug information return (iph->tos); } //--------------------------------------------------------------------------- int nas_TOOL_network6(struct in6_addr *addr, struct in6_addr *prefix, uint8_t plen) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_NETWORK6 - begin \n"); #endif if (addr==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_NETWORK6 - input parameter addr is NULL \n"); #endif return 0; } if (prefix==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_NETWORK6 - input parameter prefix is NULL \n"); #endif return 0; } // End debug information switch(plen/32) { case 0: return (((addr->s6_addr32[0]>>(32-plen))<<(32-plen))==prefix->s6_addr[0]); case 1: return ((addr->s6_addr32[0]==prefix->s6_addr[0])&& (((addr->s6_addr32[1]>>(64-plen))<<(64-plen))==prefix->s6_addr[1])); case 2: return ((addr->s6_addr32[0]==prefix->s6_addr[0])&& (addr->s6_addr32[1]==prefix->s6_addr[1])&& (((addr->s6_addr32[2]>>(96-plen))<<(96-plen))==prefix->s6_addr[2])); case 3: return ((addr->s6_addr32[0]==prefix->s6_addr[0])&& (addr->s6_addr32[1]==prefix->s6_addr[1])&& (addr->s6_addr32[2]==prefix->s6_addr[2])&& (((addr->s6_addr32[3]>>(128-plen))<<(128-plen))==prefix->s6_addr[3])); default: return ((addr->s6_addr32[0]==prefix->s6_addr[0])&& (addr->s6_addr32[1]==prefix->s6_addr[1])&& (addr->s6_addr32[2]==prefix->s6_addr[2])&& (addr->s6_addr32[3]==prefix->s6_addr[3])); } } //--------------------------------------------------------------------------- int nas_TOOL_network4(uint32_t *addr, uint32_t *prefix, uint8_t plen) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_NETWORK4 - begin \n"); #endif if (addr==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_NETWORK4 - input parameter addr is NULL \n"); #endif return 0; } if (prefix==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_NETWORK4 - input parameter prefix is NULL \n"); #endif return 0; } // End debug information if (plen>=32) return (*addr==*prefix); else return (((*addr>>(32-plen))<<(32-plen))==*prefix); } //--------------------------------------------------------------------------- //struct udphdr *nas_TOOL_get_udp6(struct ipv6hdr *iph){ //--------------------------------------------------------------------------- // return (struct udphdr *)((char *)iph+NAS_IPV6_SIZE); // to modify //} //--------------------------------------------------------------------------- uint8_t *nas_TOOL_get_protocol6(struct ipv6hdr *iph, uint8_t *protocol) { //--------------------------------------------------------------------------- uint16_t size; // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_GET_PROTOCOL6 - begin \n"); #endif if (iph==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_GET_PROTOCOL6 - input parameter iph is NULL \n"); #endif return NULL; } if (protocol==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_GET_PROTOCOL6 - input parameter protocol is NULL \n"); #endif return NULL; } // End debug information *protocol=iph->nexthdr; size=NAS_IPV6_SIZE; while (1) { switch(*protocol) { case IPPROTO_UDP: case IPPROTO_TCP: case IPPROTO_ICMPV6: return (uint8_t *)((uint8_t *)iph+size); case IPPROTO_HOPOPTS: case IPPROTO_ROUTING: case IPPROTO_DSTOPTS: *protocol=((uint8_t *)iph+size)[0]; size+=((uint8_t *)iph+size)[1]*8+8; break; case IPPROTO_FRAGMENT: *protocol=((uint8_t *)iph+size)[0]; size+=((uint8_t *)iph+size)[1]+8; break; case IPPROTO_NONE: case IPPROTO_AH: case IPPROTO_ESP: default: return NULL; } } } //--------------------------------------------------------------------------- uint8_t *nas_TOOL_get_protocol4(struct iphdr *iph, uint8_t *protocol) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_GET_PROTOCOL4 - begin \n"); #endif if (iph==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_GET_PROTOCOL4 - input parameter iph is NULL \n"); #endif return NULL; } if (protocol==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_GET_PROTOCOL4 - input parameter protocol is NULL \n"); #endif return NULL; } // End debug information *protocol=iph->protocol; switch(*protocol) { case IPPROTO_UDP: case IPPROTO_TCP: case IPPROTO_ICMP: return (uint8_t *)((uint8_t *)iph+iph->tot_len); default: return NULL; } } //--------------------------------------------------------------------------- // Convert the IMEI to iid void nas_TOOL_imei2iid(uint8_t *imei, uint8_t *iid) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_IMEI2IID - begin \n"); #endif if (imei==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_IMEI2IID - input parameter imei is NULL \n"); #endif return; } if (iid==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_IMEI2IID - input parameter iid is NULL \n"); #endif return; } // End debug information memset(iid, 0, NAS_ADDR_LEN); iid[0] = 0x03; iid[1] = 16*imei[0]+imei[1]; iid[2] = 16*imei[2]+imei[3]; iid[3] = 16*imei[4]+imei[5]; iid[4] = 16*imei[6]+imei[7]; iid[5] = 16*imei[8]+imei[9]; iid[6] = 16*imei[10]+imei[11]; iid[7] = 16*imei[12]+imei[13]; } //struct udphdr *nas_TOOL_get_udp4(struct iphdr *iph) //{ // return (struct udphdr *)((char *)iph+NAS_IPV4_SIZE); // to modify //} //--------------------------------------------------------------------------- char *nas_TOOL_get_udpmsg(struct udphdr *udph) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_GET_UDPMSG - begin \n"); #endif if (udph==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_GET_UDPMSG - input parameter udph is NULL \n"); #endif return NULL; } // End debug information return ((char *)udph+sizeof(struct udphdr)); } //--------------------------------------------------------------------------- // Compute the UDP checksum (the data size must be odd) uint16_t nas_TOOL_udpcksum(struct in6_addr *saddr, struct in6_addr *daddr, uint8_t proto, uint32_t udplen, void *data) { //--------------------------------------------------------------------------- uint32_t i; uint16_t *data16; uint32_t csum=0; // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_UDPCKSUM - begin \n"); #endif if (saddr==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_UDPCKSUM - input parameter saddr is NULL \n"); #endif return 0; } if (daddr==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_UDPCKSUM - input parameter daddr is NULL \n"); #endif return 0; } if (data==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_UDPCKSUM - input parameter data is NULL \n"); #endif return 0; } // End debug information data16=data; for (i=0; i<8; ++i) { csum+=ntohs(saddr->s6_addr16[i]); if (csum>0xffff) csum-=0xffff; } for (i=0; i<8; ++i) { csum+=ntohs(daddr->s6_addr16[i]); if (csum>0xffff) csum-=0xffff; } csum+=(udplen>>16); // udplen checksum if (csum>0xffff) csum -= 0xffff; csum+=udplen & 0xffff; if (csum>0xffff) csum -= 0xffff; csum+=proto; // protocol checksum if (csum>0xffff) csum-=0xffff; for (i = 0; 2*i < udplen; i++) { csum+=ntohs(data16[i]); if (csum>0xffff) csum-=0xffff; } return htons((uint16_t)(~csum)&0xffff); } //--------------------------------------------------------------------------- void print_TOOL_pk_udp(struct udphdr *udph) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("PRINT_TOOL_PK_UDP - begin \n"); #endif if (udph==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_PK_UDP - input parameter udph is NULL \n"); #endif return; } // End debug information if (udph!=NULL) { printk("UDP:\t source = %u, dest = %u, len = %u, check = %x\n", ntohs(udph->source), ntohs(udph->dest), ntohs(udph->len), udph->check); } } //--------------------------------------------------------------------------- void print_TOOL_pk_tcp(struct tcphdr *tcph) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("PRINT_TOOL_PK_TDP - begin \n"); #endif if (tcph==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_PK_TDP - input parameter tcph is NULL \n"); #endif return; } // End debug information if (tcph!=NULL) { printk("TCP:\t source = %u, dest = %u\n", tcph->source, tcph->dest); } } //--------------------------------------------------------------------------- void print_TOOL_pk_icmp6(struct icmp6hdr *icmph) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("PRINT_TOOL_PK_ICMP6 - begin \n"); #endif if (icmph==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_PK_ICMP6 - input parameter icmph is NULL \n"); #endif return; } // End debug information if (icmph!=NULL) { printk("ICMPv6:\t type= %d, code = %d\n", icmph->icmp6_type, icmph->icmp6_code); switch(icmph->icmp6_type) { case ICMPV6_DEST_UNREACH: printk("Destination unreachable\n"); break; case ICMPV6_PKT_TOOBIG: printk("Packet too big\n"); break; case ICMPV6_TIME_EXCEED: printk("Time exceeded\n"); break; case ICMPV6_PARAMPROB: printk("Parameter problem\n"); break; case ICMPV6_ECHO_REQUEST: printk("Echo request\n"); break; case ICMPV6_ECHO_REPLY: printk("Echo reply\n"); break; case ICMPV6_MGM_QUERY: printk("Multicast listener query\n"); break; case ICMPV6_MGM_REPORT: printk("Multicast listener report\n"); break; case ICMPV6_MGM_REDUCTION: printk("Multicast listener done\n"); break; case NDISC_ROUTER_SOLICITATION: printk("Router solicitation\n"); break; case NDISC_ROUTER_ADVERTISEMENT: printk("Router advertisment\n"); break; case NDISC_NEIGHBOUR_SOLICITATION: printk("Neighbour solicitation\n"); break; case NDISC_NEIGHBOUR_ADVERTISEMENT: printk("Neighbour advertisment\n"); break; case NDISC_REDIRECT: printk("redirect message\n"); break; } } } //--------------------------------------------------------------------------- void print_TOOL_pk_ipv6(struct ipv6hdr *iph) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("PRINT_TOOL_PK_IPv6 - begin \n"); #endif if (iph==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_PK_IPv6 - input parameter iph is NULL \n"); #endif return; } // End debug information if (iph!=NULL) { // char addr[NAS_INET6_ADDRSTRLEN]; printk("IP:\t version = %u, priority = %u, payload_len = %u\n", iph->version, iph->priority, ntohs(iph->payload_len)); printk("\t fl0 = %u, fl1 = %u, fl2 = %u\n",iph->flow_lbl[0],iph->flow_lbl[1],iph->flow_lbl[2]); printk("\t next header = %u, hop_limit = %u\n", iph->nexthdr, iph->hop_limit); // inet_ntop(AF_INET6, (void *)(&iph->saddr), addr, NAS_INET6_ADDRSTRLEN); // printk("\t saddr = %s",addr); // inet_ntop(AF_INET6, (void *)(&iph->daddr), addr, NAS_INET6_ADDRSTRLEN); // printk(", daddr = %s\n",addr); switch(iph->nexthdr) { case IPPROTO_UDP: print_TOOL_pk_udp((struct udphdr *)((char *)iph+sizeof(struct ipv6hdr))); break; case IPPROTO_TCP: print_TOOL_pk_tcp((struct tcphdr *)((char *)iph+sizeof(struct ipv6hdr))); break; case IPPROTO_ICMPV6: print_TOOL_pk_icmp6((struct icmp6hdr *)((char *)iph+sizeof(struct ipv6hdr))); break; case IPPROTO_IPV6: print_TOOL_pk_ipv6((struct ipv6hdr *)((char *)iph+sizeof(struct ipv6hdr))); break; default: printk("Unknown upper layer\n"); } } } //--------------------------------------------------------------------------- void print_TOOL_pk_ipv4(struct iphdr *iph) { //--------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("PRINT_TOOL_PK_IPv4 - begin \n"); #endif if (iph==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_PK_IPv4 - input parameter iph is NULL \n"); #endif return; } // End debug information if (iph!=NULL) { // char addr[NAS_INET_ADDRSTRLEN]; printk("IP:\t version = %u, IP length = %u\n", iph->version, iph->ihl); // inet_ntop(AF_INET, (void *)(&iph->saddr), addr, NAS_INET_ADDRSTRLEN); // printk("\t saddr = %s", addr); // inet_ntop(AF_INET, (void *)(&iph->saddr), addr, NAS_INET_ADDRSTRLEN); // printk("\t saddr = %s", addr); } } //--------------------------------------------------------------------------- void print_TOOL_pk_all(struct sk_buff *skb) { //--------------------------------------------------------------------------- printk("Skb:\t %p, len = %u\n", skb, skb->len); //navid: need to calculate the current used space: fixme? printk("Skb:\t available buf space = %u \n", skb->truesize); switch (ntohs(skb->protocol)) { case ETH_P_IPV6: print_TOOL_pk_ipv6((struct ipv6hdr *)skb->network_header); break; case ETH_P_IP: print_TOOL_pk_ipv4((struct iphdr *)skb->network_header); break; } } //--------------------------------------------------------------------------- /*int isdigit(char c) { switch(c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return 1; default: return 0; } }*/ /*int nas_TOOL_inet_pton4(char *src, uint32_t *dst) { uint32_t val; int n; uint8_t c; uint32_t parts[4]; c = *src; val=0; n=0 for (;;) { for (;;) { if (isdigit(c)) { val = (val * 10) + c - '0'; c = *++src; } else break; } if (c == '.') { if (n>4) return -1; parts[n]=val; c = *++src; ++n; } else break; } if ((c != '\0')||(n!=3)) return (0); if ((parts[0] | parts[1] | parts[2] | val) > 256) return (0); val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8); if (dst) dst = htonl(val); return (1); }*/ //--------------------------------------------------------------------------- void print_TOOL_state(uint8_t state) { //--------------------------------------------------------------------------- // case NAS_STATE_IDLE:printk(" State NAS_STATE_IDLE\n");return; // case NAS_STATE_CONNECTED:printk(" State NAS_STATE_CONNECTED\n");return; // case NAS_STATE_ESTABLISHMENT_REQUEST:printk(" State NAS_STATE_ESTABLISHMENT_REQUEST\n");return; // case NAS_STATE_ESTABLISHMENT_FAILURE:printk(" State NAS_STATE_ESTABLISHMENT_FAILURE\n");return; // case NAS_STATE_RELEASE_FAILURE:printk(" State NAS_STATE_RELEASE_FAILURE\n");return; switch(state) { case NAS_IDLE: printk("NAS_IDLE\n"); return; case NAS_CX_FACH: printk("NAS_CX_FACH\n"); return; case NAS_CX_DCH: printk("NAS_CX_DCH\n"); return; case NAS_CX_RECEIVED: printk("NAS_CX_RECEIVED\n"); return; case NAS_CX_CONNECTING: printk("NAS_CX_CONNECTING\n"); return; case NAS_CX_RELEASING: printk("NAS_CX_RELEASING\n"); return; case NAS_CX_CONNECTING_FAILURE: printk("NAS_CX_CONNECTING_FAILURE\n"); return; case NAS_CX_RELEASING_FAILURE: printk("NAS_CX_RELEASING_FAILURE\n"); return; case NAS_RB_ESTABLISHING: printk("NAS_RB_ESTABLISHING\n"); return; case NAS_RB_RELEASING: printk("NAS_RB_RELEASING\n"); return; case NAS_RB_DCH: printk("NAS_RB_DCH\n"); return; default: printk(" Unknown state\n"); } } //----------------------------------------------------------------------------- // Print the content of a buffer in hexadecimal void nas_tool_print_buffer(char * buffer,int length) { //----------------------------------------------------------------------------- int i; // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_PRINT_BUFFER - begin \n"); #endif if (buffer==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_TOOL_PRINT_BUFFER - input parameter buffer is NULL \n"); #endif return; } // End debug information printk("\nBuffer content: "); for (i=0; i<length; i++) printk("-%hx-",buffer[i]); printk(",\t length %d\n", length); } //----------------------------------------------------------------------------- void nas_print_rb_entity(struct rb_entity *rb) { //----------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_PRINT_RB_ENTITY - begin \n"); #endif if (rb==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_PRINT_RB_ENTITY - input parameter rb is NULL \n"); #endif return; } // End debug information printk("\nrb_entity content: rab_id %d, sapi %d, qos %d, \n", rb->rab_id, rb->sapi, rb->qos); printk("state %d, retry %d, countimer %d\n",rb->state, rb->retry, rb->countimer); }; //----------------------------------------------------------------------------- void nas_print_classifier(struct classifier_entity *gc) { //----------------------------------------------------------------------------- // Start debug information #ifdef NAS_DEBUG_TOOL printk("NAS_PRINT_GC_ENTITY - begin \n"); #endif if (gc==NULL) { #ifdef NAS_DEBUG_TOOL printk("NAS_PRINT_GC_ENTITY - input parameter gc is NULL \n"); #endif return; } // End debug information printk("\nClassifier content: classref %d, version %d, splen %d, dplen %d,\n", gc->classref, gc->version, gc->splen, gc->dplen); printk("protocol %d, sport %d, dport %d, rab_id %d\n", gc->protocol, gc->sport, gc->dport, gc->rab_id); if (gc->rb != NULL) { nas_print_rb_entity(gc->rb); } };
25.295838
139
0.54518
c82b3402477b2df681b9c4cbf970b51f9b5a38ba
757
h
C
mojowannabe/mojowannabe.h
towbes/rancha
156c69ca298d489cd660ee7ab2ba96bdec455e44
[ "MIT" ]
null
null
null
mojowannabe/mojowannabe.h
towbes/rancha
156c69ca298d489cd660ee7ab2ba96bdec455e44
[ "MIT" ]
null
null
null
mojowannabe/mojowannabe.h
towbes/rancha
156c69ca298d489cd660ee7ab2ba96bdec455e44
[ "MIT" ]
1
2022-01-03T16:46:02.000Z
2022-01-03T16:46:02.000Z
#pragma once #include "Resource.h" #include "Account.h" #include <string> #include <CommCtrl.h> #include <iostream> #include <fstream> #include <filesystem> //Index of menu for server, account name, password int LaunchDaoc(int server, const wchar_t* acct, const wchar_t* password, const wchar_t* character, int realm); wchar_t* GetText(HWND hWnd); void DrawLogin(HWND hWnd); void DrawProfiles(HWND hWnd); bool SaveAcct(Account acct); bool SaveChar(Account acct, Character character); void FetchAccounts(std::vector<Account>& acctList); //https://devblogs.microsoft.com/oldnewthing/20041025-00/?p=37483 EXTERN_C IMAGE_DOS_HEADER __ImageBase; #define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase) struct profileIndex { int acctIndex; int charIndex; };
26.103448
110
0.77675
c8f0f9dc0a3dbc7726dd67021fd4715353584657
4,810
h
C
TELCOVOICEMgrHal_Stub/include/TELCOVOICEMgrHal.h
rdkcmf/rdkb-tools-tdkb
9f9c3600cd701d5fc90ac86a6394ebd28d49267e
[ "Apache-2.0" ]
null
null
null
TELCOVOICEMgrHal_Stub/include/TELCOVOICEMgrHal.h
rdkcmf/rdkb-tools-tdkb
9f9c3600cd701d5fc90ac86a6394ebd28d49267e
[ "Apache-2.0" ]
null
null
null
TELCOVOICEMgrHal_Stub/include/TELCOVOICEMgrHal.h
rdkcmf/rdkb-tools-tdkb
9f9c3600cd701d5fc90ac86a6394ebd28d49267e
[ "Apache-2.0" ]
null
null
null
/* *If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2021 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __TELCOVOICEMGR_STUB_HAL_H__ #define __TELCOVOICEMGR_STUB_HAL_H__ #include "rdkteststubintf.h" #include "rdktestagentintf.h" #include "jsonhal_lib_wrp.h" #include "telcovoicemgrhal_lib_wrp.h" #include "json_hal_client.h" #include <jsonrpccpp/server/connectors/tcpsocketserver.h> /* for reference added it,(IN) indicates accepting the request from Test Manager and (OUT) indicates sending the response for the request back to the Manager */ #ifndef IN #define IN #endif #ifndef OUT #define OUT #endif #define TEST_SUCCESS true #define TEST_FAILURE false #define MAX_BUFFER_SIZE_TO_SEND 500 #define MAX_PARAMETER_SIZE 500 #define DETAILS_BUFFER_SIZE 2048 #define RETURN_SUCCESS 0 #define RETURN_FAILURE 1 #define TELCO_CONF_FILE "/etc/rdk/conf/telcovoice_manager_conf.json" using namespace std; /* RDKTestAgent : This Class provides interface for the module to enable RPC mechanism. */ class RDKTestAgent; /* RDKTestStubInterface : This Class provides provides interface for the modules. */ class TELCOVOICEMgrHal : public RDKTestStubInterface, public AbstractServer<TELCOVOICEMgrHal> { public: TELCOVOICEMgrHal(TcpSocketServer &ptrRpcServer) : AbstractServer <TELCOVOICEMgrHal>(ptrRpcServer) { this->bindAndAddMethod(Procedure("TELCOVOICEMgrHal_Init", PARAMS_BY_NAME, JSON_STRING, NULL), &TELCOVOICEMgrHal::TELCOVOICEMgrHal_Init); this->bindAndAddMethod(Procedure("TELCOVOICEMgrHal_InitData", PARAMS_BY_NAME, JSON_STRING, "bStatus", JSON_INTEGER, NULL), &TELCOVOICEMgrHal::TELCOVOICEMgrHal_InitData); this->bindAndAddMethod(Procedure("TELCOVOICEMgrHal_GetParamValue", PARAMS_BY_NAME, JSON_STRING, "paramName", JSON_STRING, NULL), &TELCOVOICEMgrHal::TELCOVOICEMgrHal_GetParamValue); this->bindAndAddMethod(Procedure("TELCOVOICEMgrHal_SetParamValue", PARAMS_BY_NAME, JSON_STRING, "paramName", JSON_STRING, "paramType", JSON_STRING,"paramValue", JSON_STRING, NULL), &TELCOVOICEMgrHal::TELCOVOICEMgrHal_SetParamValue); this->bindAndAddMethod(Procedure("TELCOVOICEMgrHal_GetLineStats", PARAMS_BY_NAME, JSON_STRING, "paramName", JSON_STRING, "flag", JSON_INTEGER, NULL), &TELCOVOICEMgrHal::TELCOVOICEMgrHal_GetLineStats); this->bindAndAddMethod(Procedure("TELCOVOICEMgrHal_GetCapabilities", PARAMS_BY_NAME, JSON_STRING, "flag", JSON_INTEGER, "paramName", JSON_STRING, NULL), &TELCOVOICEMgrHal::TELCOVOICEMgrHal_GetCapabilities); this->bindAndAddMethod(Procedure("TELCOVOICEMgrHal_GetVoiceProfile", PARAMS_BY_NAME, JSON_STRING, "index", JSON_INTEGER, "flag", JSON_INTEGER, "paramName", JSON_STRING, NULL), &TELCOVOICEMgrHal::TELCOVOICEMgrHal_GetVoiceProfile); this->bindAndAddMethod(Procedure("TELCOVOICEMgrHal_GetPhyInterface", PARAMS_BY_NAME, JSON_STRING, "index", JSON_INTEGER, "flag", JSON_INTEGER, "paramName", JSON_STRING, NULL), &TELCOVOICEMgrHal::TELCOVOICEMgrHal_GetPhyInterface); } bool initialize(IN const char* szVersion); bool cleanup(const char*); std::string testmodulepre_requisites(); bool testmodulepost_requisites(); void TELCOVOICEMgrHal_Init(IN const Json::Value& req, OUT Json::Value& response); void TELCOVOICEMgrHal_InitData(IN const Json::Value& req, OUT Json::Value& response); void TELCOVOICEMgrHal_GetParamValue(IN const Json::Value& req, OUT Json::Value& response); void TELCOVOICEMgrHal_SetParamValue(IN const Json::Value& req, OUT Json::Value& response); void TELCOVOICEMgrHal_GetLineStats(IN const Json::Value& req, OUT Json::Value& response); void TELCOVOICEMgrHal_GetCapabilities(IN const Json::Value& req, OUT Json::Value& response); void TELCOVOICEMgrHal_GetVoiceProfile(IN const Json::Value& req, OUT Json::Value& response); void TELCOVOICEMgrHal_GetPhyInterface(IN const Json::Value& req, OUT Json::Value& response); }; #endif
54.659091
252
0.739709
ae7cf554d17234de4433d35810d8e290359dfde2
394
c
C
qemu_mode/qemu-2.10.0/stubs/arch-query-cpu-model-expansion.c
braymar/afl
a6b2dad6bbd9c9401814e088582bc04a074651eb
[ "Apache-2.0" ]
60
2020-10-14T07:11:48.000Z
2022-02-14T23:00:51.000Z
qemu_mode/qemu-2.10.0/stubs/arch-query-cpu-model-expansion.c
braymar/afl
a6b2dad6bbd9c9401814e088582bc04a074651eb
[ "Apache-2.0" ]
8
2020-10-19T02:17:19.000Z
2022-01-15T05:52:46.000Z
qemu_mode/qemu-2.10.0/stubs/arch-query-cpu-model-expansion.c
braymar/afl
a6b2dad6bbd9c9401814e088582bc04a074651eb
[ "Apache-2.0" ]
17
2020-10-14T07:13:47.000Z
2022-03-31T03:40:44.000Z
#include "qemu/osdep.h" #include "qemu-common.h" #include "sysemu/arch_init.h" #include "qapi/qmp/qerror.h" CpuModelExpansionInfo *arch_query_cpu_model_expansion(CpuModelExpansionType type, CpuModelInfo *mode, Error **errp) { error_setg(errp, QERR_UNSUPPORTED); return NULL; }
30.307692
81
0.558376
ebe6cd674cdfa1c67bb4a909cb4deb28e733f1a8
21,090
c
C
netbsd/sys/dev/rnd.c
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
1
2019-10-15T06:29:32.000Z
2019-10-15T06:29:32.000Z
netbsd/sys/dev/rnd.c
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
null
null
null
netbsd/sys/dev/rnd.c
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
3
2017-01-09T02:15:36.000Z
2019-10-15T06:30:25.000Z
/* $NetBSD: rnd.c,v 1.26 2002/03/08 20:48:37 thorpej Exp $ */ /*- * Copyright (c) 1997 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Michael Graff <explorer@flame.org>. This code uses ideas and * algorithms from the Linux driver written by Ted Ts'o. * * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: rnd.c,v 1.26 2002/03/08 20:48:37 thorpej Exp $"); #include <sys/param.h> #include <sys/ioctl.h> #include <sys/fcntl.h> #include <sys/select.h> #include <sys/poll.h> #include <sys/malloc.h> #include <sys/proc.h> #include <sys/kernel.h> #include <sys/conf.h> #include <sys/systm.h> #include <sys/callout.h> #include <sys/rnd.h> #include <sys/vnode.h> #include <sys/pool.h> #ifdef __HAVE_CPU_COUNTER #include <machine/rnd.h> #endif #ifdef RND_DEBUG #define DPRINTF(l,x) if (rnd_debug & (l)) printf x int rnd_debug = 0; #else #define DPRINTF(l,x) #endif #define RND_DEBUG_WRITE 0x0001 #define RND_DEBUG_READ 0x0002 #define RND_DEBUG_IOCTL 0x0004 #define RND_DEBUG_SNOOZE 0x0008 /* * list devices attached */ #if 0 #define RND_VERBOSE #endif /* * Use the extraction time as a somewhat-random source */ #ifndef RND_USE_EXTRACT_TIME #define RND_USE_EXTRACT_TIME 1 #endif /* * The size of a temporary buffer, malloc()ed when needed, and used for * reading and writing data. */ #define RND_TEMP_BUFFER_SIZE 128 /* * This is a little bit of state information attached to each device that we * collect entropy from. This is simply a collection buffer, and when it * is full it will be "detached" from the source and added to the entropy * pool after entropy is distilled as much as possible. */ #define RND_SAMPLE_COUNT 64 /* collect N samples, then compress */ typedef struct _rnd_sample_t { SIMPLEQ_ENTRY(_rnd_sample_t) next; rndsource_t *source; int cursor; int entropy; u_int32_t ts[RND_SAMPLE_COUNT]; u_int32_t values[RND_SAMPLE_COUNT]; } rnd_sample_t; /* * The event queue. Fields are altered at an interrupt level. * All accesses must be protected at splhigh(). */ volatile int rnd_timeout_pending; SIMPLEQ_HEAD(, _rnd_sample_t) rnd_samples; /* * our select/poll queue */ struct selinfo rnd_selq; /* * Set when there are readers blocking on data from us */ #define RND_READWAITING 0x00000001 volatile u_int32_t rnd_status; /* * Memory pool; accessed only at splhigh(). */ struct pool rnd_mempool; /* * Our random pool. This is defined here rather than using the general * purpose one defined in rndpool.c. * * Samples are collected and queued at splhigh() into a separate queue * (rnd_samples, see above), and processed in a timeout routine; therefore, * all other accesses to the random pool must be at splsoftclock() as well. */ rndpool_t rnd_pool; /* * This source is used to easily "remove" queue entries when the source * which actually generated the events is going away. */ static rndsource_t rnd_source_no_collect = { { 'N', 'o', 'C', 'o', 'l', 'l', 'e', 'c', 't', 0, 0, 0, 0, 0, 0, 0 }, 0, 0, 0, 0, RND_TYPE_UNKNOWN, (RND_FLAG_NO_COLLECT | RND_FLAG_NO_ESTIMATE | RND_TYPE_UNKNOWN), NULL }; struct callout rnd_callout = CALLOUT_INITIALIZER; void rndattach __P((int)); int rndopen __P((dev_t, int, int, struct proc *)); int rndclose __P((dev_t, int, int, struct proc *)); int rndread __P((dev_t, struct uio *, int)); int rndwrite __P((dev_t, struct uio *, int)); int rndioctl __P((dev_t, u_long, caddr_t, int, struct proc *)); int rndpoll __P((dev_t, int, struct proc *)); static inline void rnd_wakeup_readers(void); static inline u_int32_t rnd_estimate_entropy(rndsource_t *, u_int32_t); static inline u_int32_t rnd_counter(void); static void rnd_timeout(void *); static int rnd_ready = 0; static int rnd_have_entropy = 0; LIST_HEAD(, __rndsource_element) rnd_sources; /* * Generate a 32-bit counter. This should be more machine dependant, * using cycle counters and the like when possible. */ static inline u_int32_t rnd_counter(void) { struct timeval tv; #ifdef __HAVE_CPU_COUNTER if (cpu_hascounter()) return (cpu_counter() & 0xffffffff); #endif microtime(&tv); return (tv.tv_sec * 1000000 + tv.tv_usec); } /* * Check to see if there are readers waiting on us. If so, kick them. * * Must be called at splsoftclock(). */ static inline void rnd_wakeup_readers(void) { /* * If we have added new bits, and now have enough to do something, * wake up sleeping readers. */ if (rndpool_get_entropy_count(&rnd_pool) > RND_ENTROPY_THRESHOLD * 8) { if (rnd_status & RND_READWAITING) { DPRINTF(RND_DEBUG_SNOOZE, ("waking up pending readers.\n")); rnd_status &= ~RND_READWAITING; wakeup(&rnd_selq); } selwakeup(&rnd_selq); /* * Allow open of /dev/random now, too. */ rnd_have_entropy = 1; } } /* * Use the timing of the event to estimate the entropy gathered. * If all the differentials (first, second, and third) are non-zero, return * non-zero. If any of these are zero, return zero. */ static inline u_int32_t rnd_estimate_entropy(rndsource_t *rs, u_int32_t t) { int32_t delta, delta2, delta3; /* * If the time counter has overflowed, calculate the real difference. * If it has not, it is simplier. */ if (t < rs->last_time) delta = UINT_MAX - rs->last_time + t; else delta = rs->last_time - t; if (delta < 0) delta = -delta; /* * Calculate the second and third order differentials */ delta2 = rs->last_delta - delta; if (delta2 < 0) delta2 = -delta2; delta3 = rs->last_delta2 - delta2; if (delta3 < 0) delta3 = -delta3; rs->last_time = t; rs->last_delta = delta; rs->last_delta2 = delta2; /* * If any delta is 0, we got no entropy. If all are non-zero, we * might have something. */ if (delta == 0 || delta2 == 0 || delta3 == 0) return (0); return (1); } /* * Attach the random device, and initialize the global random pool * for our use. */ void rndattach(int num) { rnd_init(); } void rnd_init(void) { if (rnd_ready) return; LIST_INIT(&rnd_sources); SIMPLEQ_INIT(&rnd_samples); pool_init(&rnd_mempool, sizeof(rnd_sample_t), 0, 0, 0, "rndsample", NULL); rndpool_init(&rnd_pool); rnd_ready = 1; #ifdef RND_VERBOSE printf("Random device ready\n"); #endif } int rndopen(dev_t dev, int flags, int ifmt, struct proc *p) { if (rnd_ready == 0) return (ENXIO); if (minor(dev) == RND_DEV_URANDOM) return (0); /* * If this is the strong random device and we have never collected * entropy (or have not yet) don't allow it to be opened. This will * prevent waiting forever for something that just will not appear. */ if (minor(dev) == RND_DEV_RANDOM) { if (rnd_have_entropy == 0) return (ENXIO); else return (0); } return (ENXIO); } int rndclose(dev_t dev, int flags, int ifmt, struct proc *p) { return (0); } int rndread(dev_t dev, struct uio *uio, int ioflag) { u_int8_t *buf; u_int32_t entcnt, mode, nread; int n, ret, s; DPRINTF(RND_DEBUG_READ, ("Random: Read of %d requested, flags 0x%08x\n", uio->uio_resid, ioflag)); if (uio->uio_resid == 0) return (0); switch (minor(dev)) { case RND_DEV_RANDOM: mode = RND_EXTRACT_GOOD; break; case RND_DEV_URANDOM: mode = RND_EXTRACT_ANY; break; default: /* Can't happen, but this is cheap */ return (ENXIO); } ret = 0; buf = malloc(RND_TEMP_BUFFER_SIZE, M_TEMP, M_WAITOK); while (uio->uio_resid > 0) { n = min(RND_TEMP_BUFFER_SIZE, uio->uio_resid); /* * Make certain there is data available. If there * is, do the I/O even if it is partial. If not, * sleep unless the user has requested non-blocking * I/O. */ for (;;) { /* * If not requesting strong randomness, we * can always read. */ if (mode == RND_EXTRACT_ANY) break; /* * How much entropy do we have? If it is enough for * one hash, we can read. */ s = splsoftclock(); entcnt = rndpool_get_entropy_count(&rnd_pool); splx(s); if (entcnt >= RND_ENTROPY_THRESHOLD * 8) break; /* * Data is not available. */ if (ioflag & IO_NDELAY) { ret = EWOULDBLOCK; goto out; } rnd_status |= RND_READWAITING; ret = tsleep(&rnd_selq, PRIBIO|PCATCH, "rndread", 0); if (ret) goto out; } nread = rnd_extract_data(buf, n, mode); /* * Copy (possibly partial) data to the user. * If an error occurs, or this is a partial * read, bail out. */ ret = uiomove((caddr_t)buf, nread, uio); if (ret != 0 || nread != n) goto out; } out: free(buf, M_TEMP); return (ret); } int rndwrite(dev_t dev, struct uio *uio, int ioflag) { u_int8_t *buf; int n, ret, s; DPRINTF(RND_DEBUG_WRITE, ("Random: Write of %d requested\n", uio->uio_resid)); if (uio->uio_resid == 0) return (0); ret = 0; buf = malloc(RND_TEMP_BUFFER_SIZE, M_TEMP, M_WAITOK); while (uio->uio_resid > 0) { n = min(RND_TEMP_BUFFER_SIZE, uio->uio_resid); ret = uiomove((caddr_t)buf, n, uio); if (ret != 0) break; /* * Mix in the bytes. */ s = splsoftclock(); rndpool_add_data(&rnd_pool, buf, n, 0); splx(s); DPRINTF(RND_DEBUG_WRITE, ("Random: Copied in %d bytes\n", n)); } free(buf, M_TEMP); return (ret); } int rndioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p) { rndsource_element_t *rse; rndstat_t *rst; rndstat_name_t *rstnm; rndctl_t *rctl; rnddata_t *rnddata; u_int32_t count, start; int ret, s; ret = 0; switch (cmd) { /* * Handled in upper layer really, but we have to return zero * for it to be accepted by the upper layer. */ case FIONBIO: case FIOASYNC: break; case RNDGETENTCNT: s = splsoftclock(); *(u_int32_t *)addr = rndpool_get_entropy_count(&rnd_pool); splx(s); break; case RNDGETPOOLSTAT: if ((ret = suser(p->p_ucred, &p->p_acflag)) != 0) return (ret); s = splsoftclock(); rndpool_get_stats(&rnd_pool, addr, sizeof(rndpoolstat_t)); splx(s); break; case RNDGETSRCNUM: if ((ret = suser(p->p_ucred, &p->p_acflag)) != 0) return (ret); rst = (rndstat_t *)addr; if (rst->count == 0) break; if (rst->count > RND_MAXSTATCOUNT) return (EINVAL); /* * Find the starting source by running through the * list of sources. */ rse = rnd_sources.lh_first; start = rst->start; while (rse != NULL && start >= 1) { rse = rse->list.le_next; start--; } /* * Return up to as many structures as the user asked * for. If we run out of sources, a count of zero * will be returned, without an error. */ for (count = 0; count < rst->count && rse != NULL; count++) { memcpy(&rst->source[count], &rse->data, sizeof(rndsource_t)); /* Zero out information which may leak */ rst->source[count].last_time = 0; rst->source[count].last_delta = 0; rst->source[count].last_delta2 = 0; rst->source[count].state = 0; rse = rse->list.le_next; } rst->count = count; break; case RNDGETSRCNAME: if ((ret = suser(p->p_ucred, &p->p_acflag)) != 0) return (ret); /* * Scan through the list, trying to find the name. */ rstnm = (rndstat_name_t *)addr; rse = rnd_sources.lh_first; while (rse != NULL) { if (strncmp(rse->data.name, rstnm->name, 16) == 0) { memcpy(&rstnm->source, &rse->data, sizeof(rndsource_t)); return (0); } rse = rse->list.le_next; } ret = ENOENT; /* name not found */ break; case RNDCTL: if ((ret = suser(p->p_ucred, &p->p_acflag)) != 0) return (ret); /* * Set flags to enable/disable entropy counting and/or * collection. */ rctl = (rndctl_t *)addr; rse = rnd_sources.lh_first; /* * Flags set apply to all sources of this type. */ if (rctl->type != 0xff) { while (rse != NULL) { if (rse->data.type == rctl->type) { rse->data.flags &= ~rctl->mask; rse->data.flags |= (rctl->flags & rctl->mask); } rse = rse->list.le_next; } return (0); } /* * scan through the list, trying to find the name */ while (rse != NULL) { if (strncmp(rse->data.name, rctl->name, 16) == 0) { rse->data.flags &= ~rctl->mask; rse->data.flags |= (rctl->flags & rctl->mask); return (0); } rse = rse->list.le_next; } ret = ENOENT; /* name not found */ break; case RNDADDDATA: if ((ret = suser(p->p_ucred, &p->p_acflag)) != 0) return (ret); rnddata = (rnddata_t *)addr; s = splsoftclock(); rndpool_add_data(&rnd_pool, rnddata->data, rnddata->len, rnddata->entropy); rnd_wakeup_readers(); splx(s); break; default: return (EINVAL); } return (ret); } int rndpoll(dev_t dev, int events, struct proc *p) { u_int32_t entcnt; int revents, s; /* * We are always writable. */ revents = events & (POLLOUT | POLLWRNORM); /* * Save some work if not checking for reads. */ if ((events & (POLLIN | POLLRDNORM)) == 0) return (revents); /* * If the minor device is not /dev/random, we are always readable. */ if (minor(dev) != RND_DEV_RANDOM) { revents |= events & (POLLIN | POLLRDNORM); return (revents); } /* * Make certain we have enough entropy to be readable. */ s = splsoftclock(); entcnt = rndpool_get_entropy_count(&rnd_pool); splx(s); if (entcnt >= RND_ENTROPY_THRESHOLD * 8) revents |= events & (POLLIN | POLLRDNORM); else selrecord(p, &rnd_selq); return (revents); } static rnd_sample_t * rnd_sample_allocate(rndsource_t *source) { rnd_sample_t *c; int s; s = splhigh(); c = pool_get(&rnd_mempool, PR_WAITOK); splx(s); if (c == NULL) return (NULL); c->source = source; c->cursor = 0; c->entropy = 0; return (c); } /* * Don't wait on allocation. To be used in an interrupt context. */ static rnd_sample_t * rnd_sample_allocate_isr(rndsource_t *source) { rnd_sample_t *c; int s; s = splhigh(); c = pool_get(&rnd_mempool, 0); splx(s); if (c == NULL) return (NULL); c->source = source; c->cursor = 0; c->entropy = 0; return (c); } static void rnd_sample_free(rnd_sample_t *c) { int s; memset(c, 0, sizeof(rnd_sample_t)); s = splhigh(); pool_put(&rnd_mempool, c); splx(s); } /* * Add a source to our list of sources. */ void rnd_attach_source(rndsource_element_t *rs, char *name, u_int32_t type, u_int32_t flags) { u_int32_t ts; ts = rnd_counter(); strcpy(rs->data.name, name); rs->data.last_time = ts; rs->data.last_delta = 0; rs->data.last_delta2 = 0; rs->data.total = 0; /* * Force network devices to not collect any entropy by * default. */ if (type == RND_TYPE_NET) flags |= (RND_FLAG_NO_COLLECT | RND_FLAG_NO_ESTIMATE); rs->data.type = type; rs->data.flags = flags; rs->data.state = rnd_sample_allocate(&rs->data); LIST_INSERT_HEAD(&rnd_sources, rs, list); #ifdef RND_VERBOSE printf("%s: attached as an entropy source\n", rs->data.name); #endif } /* * Remove a source from our list of sources. */ void rnd_detach_source(rndsource_element_t *rs) { rnd_sample_t *sample; rndsource_t *source; int s; s = splhigh(); LIST_REMOVE(rs, list); source = &rs->data; if (source->state) { rnd_sample_free(source->state); source->state = NULL; } /* * If there are samples queued up "remove" them from the sample queue * by setting the source to the no-collect pseudosource. */ sample = SIMPLEQ_FIRST(&rnd_samples); while (sample != NULL) { if (sample->source == source) sample->source = &rnd_source_no_collect; sample = SIMPLEQ_NEXT(sample, next); } splx(s); } /* * Add a value to the entropy pool. If rs is NULL no entropy estimation * will be performed, otherwise it should point to the source-specific * source structure. */ void rnd_add_uint32(rndsource_element_t *rs, u_int32_t val) { rndsource_t *rst; rnd_sample_t *state; u_int32_t ts; int s; /* * If we are not collecting any data at all, just return. */ if (rs == NULL) return; rst = &rs->data; if (rst->flags & RND_FLAG_NO_COLLECT) return; /* * Sample the counter as soon as possible to avoid * entropy overestimation. */ ts = rnd_counter(); /* * If the sample buffer is NULL, try to allocate one here. If this * fails, drop this sample. */ state = rst->state; if (state == NULL) { state = rnd_sample_allocate_isr(rst); if (state == NULL) return; rst->state = state; } /* * If we are estimating entropy on this source, * calculate differentials. */ if ((rst->flags & RND_FLAG_NO_ESTIMATE) == 0) state->entropy += rnd_estimate_entropy(rst, ts); state->ts[state->cursor] = ts; state->values[state->cursor] = val; state->cursor++; /* * If the state arrays are not full, we're done. */ if (state->cursor < RND_SAMPLE_COUNT) return; /* * State arrays are full. Queue this chunk on the processing queue. */ s = splhigh(); SIMPLEQ_INSERT_HEAD(&rnd_samples, state, next); rst->state = NULL; /* * If the timeout isn't pending, have it run in the near future. */ if (rnd_timeout_pending == 0) { rnd_timeout_pending = 1; callout_reset(&rnd_callout, 1, rnd_timeout, NULL); } splx(s); /* * To get here we have to have queued the state up, and therefore * we need a new state buffer. If we can, allocate one now; * if we don't get it, it doesn't matter; we'll try again on * the next random event. */ rst->state = rnd_sample_allocate_isr(rst); } void rnd_add_data(rndsource_element_t *rs, void *data, u_int32_t len, u_int32_t entropy) { rndsource_t *rst; /* Mix in the random data directly into the pool. */ rndpool_add_data(&rnd_pool, data, len, entropy); if (rs != NULL) { rst = &rs->data; rst->total += entropy; if ((rst->flags & RND_FLAG_NO_ESTIMATE) == 0) /* Estimate entropy using timing information */ rnd_add_uint32(rs, *(u_int8_t *)data); } /* Wake up any potential readers since we've just added some data. */ rnd_wakeup_readers(); } /* * Timeout, run to process the events in the ring buffer. Only one of these * can possibly be running at a time, run at splsoftclock(). */ static void rnd_timeout(void *arg) { rnd_sample_t *sample; rndsource_t *source; u_int32_t entropy; int s; /* * Sample queue is protected at splhigh(); go there briefly to dequeue. */ s = splhigh(); rnd_timeout_pending = 0; sample = SIMPLEQ_FIRST(&rnd_samples); while (sample != NULL) { SIMPLEQ_REMOVE_HEAD(&rnd_samples, sample, next); splx(s); source = sample->source; /* * We repeat this check here, since it is possible the source * was disabled before we were called, but after the entry * was queued. */ if ((source->flags & RND_FLAG_NO_COLLECT) == 0) { rndpool_add_data(&rnd_pool, sample->values, RND_SAMPLE_COUNT * 4, 0); entropy = sample->entropy; if (source->flags & RND_FLAG_NO_ESTIMATE) entropy = 0; rndpool_add_data(&rnd_pool, sample->ts, RND_SAMPLE_COUNT * 4, entropy); source->total += sample->entropy; } rnd_sample_free(sample); /* Go back to splhigh to dequeue the next one.. */ s = splhigh(); sample = SIMPLEQ_FIRST(&rnd_samples); } splx(s); /* * Wake up any potential readers waiting. */ rnd_wakeup_readers(); } int rnd_extract_data(void *p, u_int32_t len, u_int32_t flags) { int retval, s; s = splsoftclock(); retval = rndpool_extract_data(&rnd_pool, p, len, flags); splx(s); return (retval); }
21.697531
78
0.668658
d944313612cd0d419d3a3287eab0e79b7cf31ba7
3,020
h
C
lasrc/c_version/src/output.h
ldj01/espa-surface-reflectance
d6f617095710883763734ff6d8943e80822d80ed
[ "Unlicense" ]
1
2020-02-25T20:07:43.000Z
2020-02-25T20:07:43.000Z
lasrc/c_version/src/output.h
ldj01/espa-surface-reflectance
d6f617095710883763734ff6d8943e80822d80ed
[ "Unlicense" ]
null
null
null
lasrc/c_version/src/output.h
ldj01/espa-surface-reflectance
d6f617095710883763734ff6d8943e80822d80ed
[ "Unlicense" ]
1
2020-02-25T20:07:48.000Z
2020-02-25T20:07:48.000Z
#ifndef OUTPUT_H #define OUTPUT_H #include "common.h" #include "input.h" /* Define some of the constants to use in the output data products */ #define FILL_VALUE -9999 #define RADSAT_FILL_VALUE 1 #define CLOUD_FILL_VALUE 0 #define SCALE_FACTOR 0.0001 #define MULT_FACTOR 10000.0 #define SCALE_FACTOR_TH 0.1 #define MULT_FACTOR_TH 10.0 #define MIN_VALID -2000 #define MAX_VALID 16000 #define MIN_VALID_TH 1500 #define MAX_VALID_TH 3500 #define L1_SATURATED 65535 /* saturation value of the Level-1 pixel */ /* Define the output product types */ typedef enum {OUTPUT_TOA=0, OUTPUT_SR=1, OUTPUT_RADSAT=2} Myoutput_t; /* Structure for the 'output' data type */ typedef struct { bool open; /* Flag to indicate whether output file is open; 'true' = open, 'false' = not open */ Inst_t inst; /* instrument */ int nband; /* Number of output bands */ int nlines; /* Number of output lines */ int nsamps; /* Number of output samples */ Espa_internal_meta_t metadata; /* Metadata container to hold the band metadata for the output bands; global metadata won't be valid */ FILE *fp_bin[NBAND_TTL_OUT]; /* File pointer for binary files; see common.h for the bands and order of bands in the output */ } Output_t; /* Prototypes */ Output_t *open_output ( Espa_internal_meta_t *in_meta, /* I: input metadata structure */ Input_t *input, /* I: input band data structure */ Myoutput_t output_type /* I: are we processing TOA, SR, RADSAT outputs? */ ); int close_output ( Output_t *output, /* I/O: Output data structure to close */ Myoutput_t output_type /* I: are we processing TOA, SR, RADSAT outputs? */ ); int free_output ( Output_t *output, /* I/O: Output data structure to free */ Myoutput_t output_type /* I: are we processing TOA, SR, RADSAT outputs? */ ); int put_output_lines ( Output_t *output, /* I: Output data structure; buf contains the line to be written */ void *buf, /* I: buffer to be written */ int iband, /* I: current band to be written (0-based) */ int iline, /* I: current line to be written (0-based) */ int nlines, /* I: number of lines to be written */ int nbytes /* I: number of bytes per pixel in this band */ ); int get_output_lines ( Output_t *output, /* I: pointer to output data structure */ int iband, /* I: current band to read (0-based) */ int iline, /* I: current line to read (0-based) */ int nlines, /* I: number of lines to read */ int nbytes, /* I: number of bytes per pixel in this band */ void *buf /* I: pointer to the buffer to be returned */ ); char *upper_case_str ( char *str /* I: string to be converted to upper case */ ); #endif
34.712644
79
0.612914
c124da7547b6002a0d2daca4e9de43d14c98baae
2,843
h
C
meeting-qt/meeting-ipc/nem_sdk_interface/premeeting_service.h
GrowthEase/-
5cc7cab95fc309049de8023ff618219dff22d773
[ "MIT" ]
48
2022-03-02T07:15:08.000Z
2022-03-31T08:37:33.000Z
meeting-qt/meeting-ipc/nem_sdk_interface/premeeting_service.h
chandarlee/Meeting
9350fdea97eb2cdda28b8bffd9c4199de15460d9
[ "MIT" ]
1
2022-02-16T01:54:05.000Z
2022-02-16T01:54:05.000Z
meeting-qt/meeting-ipc/nem_sdk_interface/premeeting_service.h
chandarlee/Meeting
9350fdea97eb2cdda28b8bffd9c4199de15460d9
[ "MIT" ]
9
2022-03-01T13:41:37.000Z
2022-03-10T06:05:23.000Z
/** * @file premeeting_service.h * @brief 预约会议头文件 * @copyright (c) 2014-2021, NetEase Inc. All rights reserved * @author * @date 2021/04/08 */ #ifndef NEM_SDK_INTERFACE_INTERFACE_PREMEETING_SERVICE_H_ #define NEM_SDK_INTERFACE_INTERFACE_PREMEETING_SERVICE_H_ #include "service_define.h" #include <list> NNEM_SDK_INTERFACE_BEGIN_DECLS /** * @brief 监听预约会议状态变更通知 */ class NEScheduleMeetingStatusListener : public NEObject { public: /** * @brief 监听预约会议状态变更通知 * @param uniqueMeetingId 会议的唯一Id * @param meetingStatus 会与状态 参考{@link NEMeetingItemStatus} */ virtual void onScheduleMeetingStatusChanged(uint64_t uniqueMeetingId, const int& meetingStatus) = 0; }; /** * @brief 预约会议服务 */ class NEM_SDK_INTERFACE_EXPORT NEPreMeetingService : public NEService { public: using NEScheduleMeetingItemCallback = NECallback<NEMeetingItem>; using NEOperateScheduleMeetingCallback = NEEmptyCallback; using NEGetMeetingListCallback = NECallback<std::list<NEMeetingItem>&>; public: /** * @brief 预约会议 * @return NEMeetingItem */ virtual NEMeetingItem createScheduleMeetingItem() = 0; /** * @brief 预约会议 * @param item 会议条目 * @param callback 回调 * @return void */ virtual void scheduleMeeting(const NEMeetingItem& item, const NEScheduleMeetingItemCallback& callback) = 0; /** * @brief 取消已预约的会议 * @param meetingUniqueId 会议唯一Id * @param callback 回调 * @return void */ virtual void cancelMeeting(const int64_t &meetingUniqueId, const NEOperateScheduleMeetingCallback& callback) = 0; /** * @brief 编辑会议 * @param item 会议条目 * @param callback 回调 * @return void */ virtual void editMeeting(const NEMeetingItem& item, const NEOperateScheduleMeetingCallback& callback) = 0; /** * @brief 查询预约会议信息 * @param meetingUniqueId 会议唯一Id * @param callback 回调 * @return void */ virtual void getMeetingItemById(const int64_t &meetingUniqueId, const NEScheduleMeetingItemCallback& callback) = 0; /** * @brief 查询特定状态下的会议列表,目前仅仅支持查询待开始、进行中及已结束,后续将支持已取消和已回收状态。 * @param status 会议状态 参考{@link NEMeetingItemStatus} * @param callback 回调 * @return void */ virtual void getMeetingList(std::list<NEMeetingItemStatus> status,const NEGetMeetingListCallback& callback) = 0; /** * @brief 注册预约会议状态变更监听器 * @param listener 监听器 * @return void */ virtual void registerScheduleMeetingStatusListener(NEScheduleMeetingStatusListener* listener) = 0; /** * @brief 反注册预约会议状态变更监听器 * @param listener 监听器 * @return void */ virtual void unRegisterScheduleMeetingStatusListener(NEScheduleMeetingStatusListener* listener) = 0; }; NNEM_SDK_INTERFACE_END_DECLS #endif // NEM_SDK_INTERFACE_INTERFACE_PREMEETING_SERVICE_H_
27.07619
119
0.705593
1e2df04b33dc6123822097c9b491b867e880ea7b
126
h
C
wasm/src/lib/assert.h
carlpett/opa
7559ad0f51c051e56667b5d723f52cb42c979b0e
[ "Apache-2.0" ]
4
2020-10-06T11:03:26.000Z
2021-08-24T10:47:50.000Z
wasm/src/lib/assert.h
carlpett/opa
7559ad0f51c051e56667b5d723f52cb42c979b0e
[ "Apache-2.0" ]
1
2022-01-22T16:36:54.000Z
2022-01-22T16:36:54.000Z
wasm/src/lib/assert.h
soluble-ai/opa
eb8e8d186566c5c195e6b9497ca7d410300a16d6
[ "Apache-2.0" ]
1
2020-05-17T15:09:15.000Z
2020-05-17T15:09:15.000Z
#ifndef OPA_ASSERT_H #define OPA_ASSERT_H #include "../std.h" #define assert(expr) ((expr) ? 0 : opa_abort(#expr)); #endif
14
53
0.68254
8c0d707faf29ec119be9f8330f3f05f19f31eca2
2,224
h
C
Example/Pods/Headers/Public/XYCommonKit/NSString+XYDateStringExt.h
LinkRober/RBMonitor
472e7f1d8083da6c652b69f225411af4e1eba95f
[ "MIT" ]
null
null
null
Example/Pods/Headers/Public/XYCommonKit/NSString+XYDateStringExt.h
LinkRober/RBMonitor
472e7f1d8083da6c652b69f225411af4e1eba95f
[ "MIT" ]
null
null
null
Example/Pods/Headers/Public/XYCommonKit/NSString+XYDateStringExt.h
LinkRober/RBMonitor
472e7f1d8083da6c652b69f225411af4e1eba95f
[ "MIT" ]
null
null
null
// // NSString+XYDateStringExt.h // XiaoYing // // Created by hongru qi on 2016/12/14. // Copyright © 2016年 XiaoYing. All rights reserved. // #import <Foundation/Foundation.h> @interface NSString (XYDateStringExt) + (NSString *)xy_getDateStringWithFormat:(NSString *)format date:(NSDate *)date; /** Get a EN locale formatted date string @param format The date format for the receiver. eg.@"yyyyMMdd hhmmss" @param date The NSDate that will be converted to a NSString with the format above */ + (NSString *)xy_getDateStringWithEnFormat:(NSString *)format date:(NSDate *)date; /** Get a formatted date string @param format The date format for the receiver. eg.@"yyyyMMdd hhmmss" @param date The NSDate that will be converted to a NSString with the format above @param language Use the language string to get locale , then set it to the dateformat */ + (NSString *)xy_getDateStringWithFormat:(NSString *)format date:(NSDate *)date language:(NSString *)language; + (NSDate *)xy_getDateFromFormatString:(NSString *)dateStr; /** Returns YES if the string is nil or equal to @"" */ + (BOOL)xy_isEmptyString:(NSString *)string; /** The NSString eg:yyyyMMddHHmmss that will be converted to a string eg.yyyy/MM/dd with the format @param dateString a date string */ + (NSString *)xy_formatMessageListDateString:(NSString *)dateString; /** Returns YES or NO @param time1 time format:yyyyMMddHHmmss @param time2 time format:yyyyMMddHHmmss */ + (BOOL)xy_checkTime:(NSString*)time1 earliertThan:(NSString*)time2; /** Returns YES or NO @param expiredTime time format:yyyyMMddHHmmss */ + (BOOL)xy_checkTimeExpiredNow:(NSString*)expiredTime; /** return YES, if lastUpdateTime is minInterval(second) before @param lastUpdateTime time format:yyyyMMddHHmmss @param minInterval time format:yyyyMMddHHmmss */ + (BOOL)xy_checkIfNeedUpdateList:(NSString*)lastUpdateTime minInterval:(double)minInterval; + (NSString *)xy_stringFromMilliseconds:(UInt32)totalMilliseconds style:(NSString *)style; + (NSString *)xy_stringFromMilliseconds:(UInt32)totalMilliseconds; + (NSString *)xy_stringFromSeconds:(UInt32)totalSeconds; + (NSDictionary *)xy_dictionaryWithJsonString:(NSString *)jsonString; @end
32.231884
110
0.759442
1b0821cabce4e952a44725bae929cf2d34e0b3fc
1,155
c
C
security/id2/src/log/log.c
mu340881/alios_Integrate
a9f98898e13725423bd2379b2d766e2414c40e99
[ "Apache-2.0" ]
12
2020-12-04T15:06:22.000Z
2022-01-19T09:57:47.000Z
security/id2/src/log/log.c
mu340881/alios_Integrate
a9f98898e13725423bd2379b2d766e2414c40e99
[ "Apache-2.0" ]
1
2019-11-05T08:31:41.000Z
2019-11-05T08:31:41.000Z
security/id2/src/log/log.c
mu340881/alios_Integrate
a9f98898e13725423bd2379b2d766e2414c40e99
[ "Apache-2.0" ]
5
2020-12-10T09:09:24.000Z
2021-04-15T11:50:32.000Z
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdint.h> #include <string.h> #include <stdio.h> #include "config.h" #include "log.h" #if (ID2_DEBUG) #define COL_SIZE 0x10 void id2_log_hex_dump(const char* name, const uint8_t* in_data, uint32_t in_len) { uint32_t i; char buf[80]; int pos; if (name) { id2_log_debug("%s [length = 0x%04X]\n", name, in_len); } i = 0; pos = 0; memset(buf, 0x00, sizeof(buf)); while (i < in_len) { pos += snprintf(buf + pos, sizeof(buf) - pos, "%02X ", in_data[i]); i++; if (i % COL_SIZE == 0x00) { pos += snprintf(buf + pos, sizeof(buf) - pos, "\n"); id2_log_debug("%s", buf); pos = 0; } else if (i % COL_SIZE == (COL_SIZE >> 1)) { pos += snprintf(buf + pos, sizeof(buf) - pos, " "); } else { } } if (pos > 0) { if (i % COL_SIZE == 0x00) { id2_log_debug("%s", buf); } else { id2_log_debug("%s\n", buf); } } } #endif
19.576271
80
0.467532
1453f4162cec66df4ce182c0d00921f83d862f90
2,614
h
C
009_Assimp/assimp_app.h
kumakoko/KumaGL
b5179c72f148332fc16786d7f2186c3368614c39
[ "MIT" ]
10
2019-02-14T06:44:52.000Z
2021-11-17T07:33:34.000Z
009_Assimp/assimp_app.h
kumakoko/KumaGL
b5179c72f148332fc16786d7f2186c3368614c39
[ "MIT" ]
null
null
null
009_Assimp/assimp_app.h
kumakoko/KumaGL
b5179c72f148332fc16786d7f2186c3368614c39
[ "MIT" ]
2
2019-02-14T06:56:12.000Z
2021-11-17T07:33:24.000Z
/************************************************************************************************************************** Copyright(C) 2014-2017 www.xionggf.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 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. **************************************************************************************************************************/ /*! * \file assimp_app.h * \date 2017/12/31 14:50 * * \author www.xionggf.com * Contact: sun_of_lover@sina.com * * \brief 演示使用Assimp库装载和现实模型 * * TODO: 演示使用kgl::BasicStaticMesh类 * * \note */ #ifndef assimp_app_h__ #define assimp_app_h__ #include "../klib/kgl_lib_pch.h" #include "../klib/kgl_app.h" #include "../klib/kgl_gpu_program.h" #include "../klib/kgl_primitive.h" #include "../klib/kgl_source_texture.h" #include "../klib/kgl_basic_static_mesh.h" #include "../klib/kgl_font_renderer.h" #include "../klib/kgl_render_state_blend.h" #include "../klib/kgl_render_state_depth.h" class AssimpApp : public kgl::App { public: AssimpApp(); virtual ~AssimpApp(); virtual void InitScene() override; protected: virtual void RenderScene() override; virtual void ProcessInput() override; virtual void InitModel() override; virtual void InitShaders() override; virtual void InitMainCamera() override; virtual void RenderGUI() override; private: kgl::GPUProgramSPtr model_shader_; kgl::BasicStaticMesh* model_; kgl::RenderStateDepth rs_depth_; kgl::RenderStateBlend rs_blend_; float box_scale_factor_ = 1.0f; }; #endif // assimp_app_h__
40.215385
125
0.656465
6cf97be43804aeeabc164b373f139f2991597511
311
h
C
source_to_source_translator/boiler_plate_code_for_textures_template.h
paulmetzger/Device-Hopping-Paper
323acf941080760990ad58b4ed7418462a3c8e0c
[ "BSD-3-Clause" ]
null
null
null
source_to_source_translator/boiler_plate_code_for_textures_template.h
paulmetzger/Device-Hopping-Paper
323acf941080760990ad58b4ed7418462a3c8e0c
[ "BSD-3-Clause" ]
null
null
null
source_to_source_translator/boiler_plate_code_for_textures_template.h
paulmetzger/Device-Hopping-Paper
323acf941080760990ad58b4ed7418462a3c8e0c
[ "BSD-3-Clause" ]
1
2021-11-08T22:51:16.000Z
2021-11-08T22:51:16.000Z
texture<%TYPE%, 1> %BUFFER_NAME%_tex; // vector textures struct %BUFFER_NAME%_tex_reader_struct { __device__ __forceinline__ float operator()(const int idx) const { // The IDE shows an error here but the CUDA compiler compiles this fine. return tex1Dfetch(%BUFFER_NAME%_tex, idx); } };
38.875
80
0.707395
37ff63ee8fc12341297885839b97fb9ab76a6f9f
2,761
c
C
nitan/kungfu/skill/bihai-chaosheng.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/kungfu/skill/bihai-chaosheng.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/kungfu/skill/bihai-chaosheng.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
#include <ansi.h> inherit SKILL; string type() { return "knowledge"; } int valid_enable(string usage) { return usage == "chuixiao-jifa"; } int valid_learn(object me) { if (me->query_skill("chuixiao-jifa", 1) < 100) return notify_fail("你的吹蕭技法水平不夠,還是先練好再説吧!\n"); if (me->query_skill("chuixiao-jifa", 1) < me->query_skill("bihai-chaosheng", 1)) return notify_fail("你的吹蕭技法水平有限,無法領會更精妙的碧海潮生曲。\n"); return 1; } int practice_skill(object me) { object ob; if( !objectp(ob=query_temp("handing", me)) || ! ob->valid_as_xiao()) return notify_fail("不拿根簫在手上,你怎麼練習?\n"); if( query("jing", me)<80 ) return notify_fail("你的精神不夠好,沒法練習了。\n"); if( query("qi", me)<30 ) return notify_fail("你現在口乾舌燥,實在是太累了。\n"); me->receive_damage("jing", 45); me->receive_damage("qi", 20); return 1; } void do_effect(object me) { object *obs; int lvl; int i; int damage; lvl = me->query_skill("chuixiao-jifa", 1) / 2 + me->query_skill("bihai-chaosheng", 1); if( query("no_fight", environment(me) ) || query("skybook", environment(me) ) || lvl < 150) return; lvl = lvl / 5 + me->query_skill("force"); lvl /= 2; // special effort obs = all_inventory(environment(me)); for (i = 0; i < sizeof(obs); i++) { if (! obs[i]->is_character() || obs[i] == me || ! living(obs[i])) continue; // 被死亡保護的玩家不受傷害 if ((int)obs[i]->query_condition("die_guard")) continue; if (me->query_skill("bihai-chaosheng") * 2 / 3 < obs[i]->query_skill("bihai-chaosheng")) continue; if (lvl + random(lvl) < obs[i]->query_skill("force")) { tell_object(obs[i], HIM "你聽了心中不禁微微一動,發現這曲子頗有奧妙之處。\n" NOR); continue; } damage=query("max_neili", me)-query("max_neili", obs[i]); if (damage < 500) { tell_object(obs[i], HIM "你忽然覺得一陣迷亂,連忙運了一口氣,才清醒過來。\n" NOR); continue; } damage /= 10; me->want_kill(obs[i]); me->fight_ob(obs[i]); obs[i]->kill_ob(me); obs[i]->receive_damage("jing", damage, me); obs[i]->receive_wound("jing", damage / 3, me); tell_object(obs[i], HIM "你只覺得心迷神亂,忍不住要翩翩起舞……\n" NOR); } }
29.063158
88
0.469033
15c7d49b1e357b03a8b48c53efea8ca35907ecc2
1,912
h
C
pwiz_tools/BiblioSpec/src/original-LibIterator.h
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
2
2019-12-28T21:24:36.000Z
2020-04-18T03:52:05.000Z
pwiz_tools/BiblioSpec/src/original-LibIterator.h
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
null
null
null
pwiz_tools/BiblioSpec/src/original-LibIterator.h
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
null
null
null
// // $Id: original-LibIterator.h 6870 2014-11-03 19:12:11Z chambm $ // // // Original author: Barbara Frewen <frewen@u.washington.edu> // // Copyright 2012 University of Washington - Seattle, WA 98195 // // 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. // //header file for an iterator that gives access to a library's spectra #ifndef LIB_ITERATOR #define LIB_ITERATOR #include <vector> #include "original-RefSpectrum.h" #include "original-ProcessedPeaks.h" struct refSpecPair{ RefSpectrum* specp; ProcessedPeaks* pPeaksp; refSpecPair(); }; class LibIterator { private: // vector<RefSpectrum>* specs; vector<RefSpectrum*> &specs; vector<ProcessedPeaks*> &pPeaks; int first; //index of first spectrum to return int last; //index of spectrum AFTER the last one to return int current; //index of the next spectrum to return void init(); public: //LibIterator(); LibIterator( vector<RefSpectrum*> &libsVectorp, vector<ProcessedPeaks*> &libsPPvectorp, int first, int last ); LibIterator(const LibIterator& l); ~LibIterator(); LibIterator& operator=(const LibIterator& right); RefSpectrum* getSpecp(); refSpecPair getSpecPair(); void getSpec(RefSpectrum* refSpec);//not used RefSpectrum getSpec(); bool hasSpec(); int numLeft(); }; #endif // LIB_ITERATOR /* * Local Variables: * mode: c * c-basic-offset: 4 * End: */
25.157895
76
0.710774
63cfcead9e35c71aa392119b7808d6f9c7b3a8af
869
h
C
client/Audio.h
blazeroni/foxc
c143edb63b90a6c500193ea5eac95f9c89e3c4ff
[ "MIT" ]
null
null
null
client/Audio.h
blazeroni/foxc
c143edb63b90a6c500193ea5eac95f9c89e3c4ff
[ "MIT" ]
null
null
null
client/Audio.h
blazeroni/foxc
c143edb63b90a6c500193ea5eac95f9c89e3c4ff
[ "MIT" ]
null
null
null
#ifndef XCLONE_AUDIO_H #define XCLONE_AUDIO_H #include "includes.h" #include "xcore/Singleton.h" #include <SDL/SDL_mixer.h> class Audio : public Singleton<Audio> { friend class Singleton<Audio>; public: static Mix_Chunk *_blaster; static Mix_Chunk *_scream; Audio(); void init(); void deinit(); Mix_Chunk* loadEffect(string fileName); Mix_Music* loadMusic(string fileName); // luis i changed this so you can play a sound // by calling with just the effect name --nick // Ok man sounds good!. int playEffect(Mix_Chunk* effect, int Channel = 1, int NumOfRep = 0); int playMusic(int NumOfRep, Mix_Music* music); // (-1, <name>) makes it keep playing int PauseResumeMusic(); int StopMusic(); private: Mix_Music* _music; Mix_Chunk* _effect; }; #endif
24.138889
89
0.644419
29da9d92d83f9c65a8298771f08c6eb6780187d5
15,143
c
C
projects/samples/curriculum/controllers/advanced_path_planning_NF1/advanced_path_planning_NF1.c
victorhu3/webots
60d173850f0b4714c500db004e69f2df8cfb9e8a
[ "Apache-2.0" ]
1
2020-06-08T13:38:11.000Z
2020-06-08T13:38:11.000Z
projects/samples/curriculum/controllers/advanced_path_planning_NF1/advanced_path_planning_NF1.c
victorhu3/webots
60d173850f0b4714c500db004e69f2df8cfb9e8a
[ "Apache-2.0" ]
2
2020-05-18T12:49:14.000Z
2020-12-01T15:13:43.000Z
projects/samples/curriculum/controllers/advanced_path_planning_NF1/advanced_path_planning_NF1.c
victorhu3/webots
60d173850f0b4714c500db004e69f2df8cfb9e8a
[ "Apache-2.0" ]
1
2022-02-25T12:34:18.000Z
2022-02-25T12:34:18.000Z
/* * Copyright 1996-2020 Cyberbotics Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <webots/display.h> #include <webots/motor.h> #include <webots/position_sensor.h> #include <webots/robot.h> #include "../../lib/odometry.h" #include "../../lib/odometry_goto.h" #define PI 3.14159265358979 #define LEFT 0 #define RIGHT 1 #define EPUCK_RADIUS 0.037 #define VERBOSE 1 #define TIME_STEP 64 /* * define the world configuration * the map is a rectangle of size MAP_X * MAP_Y * it is modeled as RES_X * RES_Y cells */ #define MAP_X 0.42 #define MAP_Y 0.30 #define RES_X 42 #define RES_Y 30 // only one obstacle, vertices ordered clockwise #define OBSTACLE_SIZE 3 float obstacle[OBSTACLE_SIZE][2] = {{0.07, 0.21}, {0.26, 0.25}, {0.22, 0.09}}; /* * the map structure containing occupied cells * the syntax is as follows : * -1 : obstacle * 0 : goal * >0 : distance to goal */ int map[RES_X][RES_Y]; // the goal (in world coordinates) float goal_x = 0.36; float goal_y = 0.245; // speed and previous speed of the robot int speed[2] = {0, 0}; int pspeed[2] = {0, 0}; float nspeed[2] = {0, 0}; int cpt = 0; int finished = -1; // size of the display int width, height; // Instantiate odometry track and goto structures struct sOdometryTrack ot; struct sOdometryGoto og; // wheel #define SPEED_UNIT 0.00628 #define ENCODER_UNIT 159.23 WbDeviceTag left_motor, right_motor, left_position_sensor, right_position_sensor; // display to plot the NF1 map WbDeviceTag display; WbImageRef background; static void init_display(); static void draw_on_display(); static void init_map(); static int wtoc_x(float x); static int wtoc_y(float y); static float ctow_x(int x); static float ctow_y(int y); static float distance_to_segment(float x, float y, float ax, float ay, float bx, float by, float *vec_x, float *vec_y); static float distance_to_obstacle(float x, float y, float *vec_x, float *vec_y); static void set_cell(int x, int y, int val); static void print_map(); static void set_speed(int l, int r); static void goto_position(float x, float y, float theta); static void goto_cell(int x, int y, float theta); static void next_cell(int x, int y, int *nx, int *ny, float *ntheta); static int run(); static void step(); static void step() { if (wb_robot_step(TIME_STEP) == -1) { wb_robot_cleanup(); exit(EXIT_SUCCESS); } } static void init_display() { int i, j, gray; width = wb_display_get_width(display); height = wb_display_get_height(display); for (i = 0; i < width; i++) { for (j = 0; j < height; j++) { gray = 255 - map[i][height - j - 1]; wb_display_set_color(display, (gray << 16) + (gray << 8) + gray); wb_display_draw_rectangle(display, i, j, 1, 1); } } background = wb_display_image_copy(display, 0, 0, width, height); wb_display_set_color(display, 0xFF0000); } static void draw_on_display() { wb_display_image_paste(display, background, 0, 0, false); wb_display_draw_rectangle(display, wtoc_x(ot.result.x), height - wtoc_y(ot.result.y) - 1, 1, 1); } /* * This functions initializes the map end computes the distances to the goal * for each cell using the NF1 (grassfire) algorithm. */ static void init_map() { int i, j; float vx, vy; // init to "infinity" or obstacle for (i = 0; i < RES_X; i++) { for (j = 0; j < RES_Y; j++) { float d = distance_to_obstacle(ctow_x(i), ctow_y(j), &vx, &vy); if (d < EPUCK_RADIUS && d != -1) map[i][j] = -1; else map[i][j] = RES_X * RES_Y; } } // compute goal cell int x = wtoc_x(goal_x); int y = wtoc_y(goal_y); printf("Goal = (%f,%f) => (%d,%d)\n", goal_x, goal_y, x, y); // start the NF1 recursion set_cell(x, y, 0); print_map(); // check for out of bound values for (i = 0; i < RES_X; i++) { for (j = 0; j < RES_Y; j++) { if (map[i][j] < 0 || map[i][j] > 255) map[i][j] = 255; } } print_map(); if (VERBOSE > 1) print_map(); return; } static int wtoc_x(float x) { return (int)(x * RES_X / MAP_X); } static int wtoc_y(float y) { return (int)(y * RES_Y / MAP_Y); } static float ctow_x(int x) { return (x + 0.5) * MAP_X / RES_X; } static float ctow_y(int y) { return (y + 0.5) * MAP_Y / RES_Y; } /* * Compute the distance from the point (x,y) to the segment * determined by the points (ax,ay) and (bx,by). Returns -1 if * the point is not on the clockwise side of the segment. Otherwise, * (vec_x,vec_y) contains a unit vector representing the direction of * the closest point of segment. * * stores the obstacle point considered in (obs_x, obs_y) and returns the distance */ static float distance_to_segment(float x, float y, float ax, float ay, float bx, float by, float *vec_x, float *vec_y) { // lets compute useful vectors float v12_x = bx - ax; // vector from 1st segment point to 2nd point float v12_y = by - ay; float v1p_x = x - ax; // vector from 1st segment point to test point float v1p_y = y - ay; float norm_v12 = sqrt(v12_x * v12_x + v12_y * v12_y); float norm_v1p = sqrt(v1p_x * v1p_x + v1p_y * v1p_y); float dot_v12_v1p = v12_x * v1p_x + v12_y * v1p_y; float vx, vy, dist; /* // We can determine using the third composant of the cross product // if the point is on the wrong side. float tmp = v12_x*v1p_y - v12_y*v1p_x; if (tmp < 0) { *vec_x = 0; *vec_y = 0; return -1; } */ // Now, we project v1p on v12 and get the norm. float n = dot_v12_v1p / norm_v12; if (n <= 0) { // the closest point is the segment start dist = sqrt((x - ax) * (x - ax) + (y - ay) * (y - ay)); // norm([x y]-seg(1, :)); vx = ax - x; vy = ay - y; // seg(1, :) - [x y]; } else if (n >= norm_v12) { // the closest point is the segment end dist = sqrt((x - bx) * (x - bx) + (y - by) * (y - by)); // norm([x y]-seg(2, :)); vx = bx - x; vy = by - y; // seg(2, :) - [x y]; } else { // we need to project to get the closest distance dist = norm_v1p * sin(acos(dot_v12_v1p / norm_v12 / norm_v1p)); vx = v12_x * dot_v12_v1p / (norm_v12 * norm_v12) - v1p_x; vy = v12_y * dot_v12_v1p / (norm_v12 * norm_v12) - v1p_y; // v12 * dot_v12_v1p / (norm_v12*norm_v12) - v1p; } float norm_v = sqrt(vx * vx + vy * vy); if (norm_v > 0) { vx = vx / norm_v; vy = vy / norm_v; // vec/norm(vec); } *vec_x = vx; *vec_y = vy; return dist; } /* * Compute the shortest distance from the position (x,y) to the obstacle. * If dist is not -1, then (vec_x, vec_y) contains the normal vector * pointing from (x,y) to the closest obstacle. */ static float distance_to_obstacle(float x, float y, float *vec_x, float *vec_y) { float dist = -1; *vec_x = 0.0; *vec_y = 0.0; float cand_x = 0.0; float cand_y = 0.0; int i = 0; int inObstacle = 1; // for each segment of the obstacle for (i = 0; i < OBSTACLE_SIZE; i++) { int ip = i + 1; if (ip > OBSTACLE_SIZE) ip = 1; float d = distance_to_segment(x, y, obstacle[i][0], obstacle[i][1], obstacle[(i + 1) % OBSTACLE_SIZE][0], obstacle[(i + 1) % OBSTACLE_SIZE][1], &cand_x, &cand_y); if (d != -1) inObstacle = 0; if (d < dist || dist == -1) { dist = d; *vec_x = cand_x; *vec_y = cand_y; } } if (inObstacle == 1) { dist = -1; *vec_x = 0.0; *vec_y = 0.0; } return dist; } static void set_cell(int x, int y, int val) { map[x][y] = val; // recursively set all cells if (x + 1 < RES_X && map[x + 1][y] > val + 1) set_cell(x + 1, y, val + 1); if (y + 1 < RES_Y && map[x][y + 1] > val + 1) set_cell(x, y + 1, val + 1); if (x > 0 && map[x - 1][y] > val + 1) set_cell(x - 1, y, val + 1); if (y > 0 && map[x][y - 1] > val + 1) set_cell(x, y - 1, val + 1); return; } static void print_map() { printf("Current map :\n"); printf("##########\n"); int i = 0; for (; i < RES_X; i++) { int j = 0; for (; j < RES_Y; j++) printf("%d\t", map[i][j]); printf("\n"); } printf("##########\n"); return; } /* * This functions sets the speed of both motors sending the command if and only if * the speed has changed. */ static void set_speed(int l, int r) { pspeed[LEFT] = speed[LEFT]; pspeed[RIGHT] = speed[RIGHT]; speed[LEFT] = l; speed[RIGHT] = r; if (pspeed[LEFT] != speed[LEFT] || pspeed[RIGHT] != speed[RIGHT]) { wb_motor_set_velocity(left_motor, SPEED_UNIT * speed[LEFT]); wb_motor_set_velocity(right_motor, SPEED_UNIT * speed[RIGHT]); } } /* * Send the robot to a relative position (x,y,theta) * using the "odometry" and "odometry_goto" modules */ static void goto_position(float x, float y, float theta) { // Set a target position odometry_goto_set_goal(&og, x, y, theta); // Move until the robot is close enough to the target position while (og.result.atgoal == 0) { // Update position and calculate new speeds odometry_track_step_pos(og.track, ENCODER_UNIT * wb_position_sensor_get_value(left_position_sensor), ENCODER_UNIT * wb_position_sensor_get_value(right_position_sensor)); if (VERBOSE > 1) printf("Current position = (%f,%f,%f)\n", ot.result.x, ot.result.y, ot.result.theta); odometry_goto_step(&og); // Set the wheel speed set_speed(og.result.speed_left, og.result.speed_right); draw_on_display(); step(); } return; } static void goto_cell(int x, int y, float theta) { // Set a target position odometry_goto_set_goal(&og, ctow_x(x), ctow_y(y), theta); // Move until the robot is close enough to the target position while (wtoc_x(ot.result.x) != x || wtoc_y(ot.result.y) != y) { // Update position and calculate new speeds odometry_track_step_pos(og.track, ENCODER_UNIT * wb_position_sensor_get_value(left_position_sensor), ENCODER_UNIT * wb_position_sensor_get_value(right_position_sensor)); if (VERBOSE > 1) printf("Current position = (%f,%f,%f) => (%d,%d)\n", ot.result.x, ot.result.y, ot.result.theta, wtoc_x(ot.result.x), wtoc_y(ot.result.y)); odometry_goto_step(&og); // Set the wheel speed set_speed(og.result.speed_left, og.result.speed_right); draw_on_display(); step(); } return; } static void next_cell(int x, int y, int *nx, int *ny, float *ntheta) { int d = map[x][y]; if (d == 0) { *nx = x; *ny = y; *ntheta = 0; } else if (x + 1 < RES_X && y + 1 < RES_Y && map[x + 1][y + 1] < d && map[x + 1][y + 1] != -1) { *nx = x + 1; *ny = y + 1; *ntheta = PI / 4; } else if (x + 1 < RES_X && y > 0 && map[x + 1][y - 1] < d && map[x + 1][y - 1] != -1) { *nx = x + 1; *ny = y - 1; *ntheta = -PI / 4; } else if (x > 0 && y + 1 < RES_Y && map[x - 1][y + 1] < d && map[x - 1][y + 1] != -1) { *nx = x - 1; *ny = y + 1; *ntheta = 3 * PI / 4; } else if (x > 0 && y > 0 && map[x - 1][y - 1] < d && map[x - 1][y - 1] != -1) { *nx = x - 1; *ny = y - 1; *ntheta = -3 * PI / 4; } else if (y + 1 < RES_Y && map[x][y + 1] < d && map[x][y + 1] != -1) { *nx = x; *ny = y + 1; *ntheta = PI / 2; } else if (x + 1 < RES_X && map[x + 1][y] < d && map[x + 1][y] != -1) { *nx = x + 1; *ny = y; *ntheta = 0; } else if (y > 0 && map[x][y - 1] < d && map[x][y - 1] != -1) { *nx = x; *ny = y - 1; *ntheta = -PI / 2; } else if (x > 0 && map[x - 1][y] < d && map[x - 1][y] != -1) { *nx = x - 1; *ny = y; *ntheta = -PI; } return; } /* * This is the main control loop function, it is called repeatedly by Webots */ static int run() { odometry_track_step_pos(og.track, ENCODER_UNIT * wb_position_sensor_get_value(left_position_sensor), ENCODER_UNIT * wb_position_sensor_get_value(right_position_sensor)); int x = wtoc_x(ot.result.x); int y = wtoc_y(ot.result.y); int d = map[x][y]; int nx, ny, nnx, nny; float ntheta; next_cell(x, y, &nx, &ny, &ntheta); next_cell(nx, ny, &nnx, &nny, &ntheta); if (d == 1 && finished == -1) { if (VERBOSE > 0) { printf("Current position = (%f,%f,%f) => (%d, %d)\n", ot.result.x, ot.result.y, ot.result.theta, x, y); printf("Distance = %d\n", d); printf("Final goal : (%f,%f)\n", goal_x, goal_y); } goto_position(goal_x, goal_y, ntheta); finished++; } else if (d > 0) { if (VERBOSE > 0) { printf("Current position = (%f,%f,%f) => (%d, %d)\n", ot.result.x, ot.result.y, ot.result.theta, x, y); printf("Distance = %d\n", d); printf("Next goal : (%d,%d)\n", nx, ny); } goto_cell(nx, ny, ntheta); } else if (finished == 0) { set_speed(0, 0); finished++; printf("Final position = (%f,%f,%f)\n", ot.result.x, ot.result.y, ot.result.theta); } draw_on_display(); return TIME_STEP; } /* * This is the main program which sets up the reset and run function. */ int main() { wb_robot_init(); /* initialize the webots controller library */ // get a handler to the motors and set target position to infinity (speed control). left_motor = wb_robot_get_device("left wheel motor"); right_motor = wb_robot_get_device("right wheel motor"); wb_motor_set_position(left_motor, INFINITY); wb_motor_set_position(right_motor, INFINITY); wb_motor_set_velocity(left_motor, 0.0); wb_motor_set_velocity(right_motor, 0.0); // get a handler to the position sensors and enable them. left_position_sensor = wb_robot_get_device("left wheel sensor"); right_position_sensor = wb_robot_get_device("right wheel sensor"); wb_position_sensor_enable(left_position_sensor, TIME_STEP); wb_position_sensor_enable(right_position_sensor, TIME_STEP); // robot init speed is 0 speed[LEFT] = speed[RIGHT] = 0; pspeed[LEFT] = pspeed[RIGHT] = 0; wb_motor_set_velocity(left_motor, SPEED_UNIT * speed[LEFT]); wb_motor_set_velocity(right_motor, SPEED_UNIT * speed[RIGHT]); // required to get the position sensor values wb_robot_step(TIME_STEP); // Initializes tracking and goto structures odometry_track_start_pos(&ot, ENCODER_UNIT * wb_position_sensor_get_value(left_position_sensor), ENCODER_UNIT * wb_position_sensor_get_value(right_position_sensor)); odometry_goto_start(&og, &ot); ot.result.x = 0.04; ot.result.y = 0.04; ot.result.theta = 0; init_map(); display = wb_robot_get_device("display"); init_display(); draw_on_display(); printf("Reset OK\n"); /* main loop */ while (true) { step(); run(); } return 0; }
28.251866
122
0.612824
6328844a8babb7aa77f3b6f4c7c35544f2332098
497
h
C
RunsCamera/Classes/RunsCameraViewDelegate.h
RunsCode/Camera
ebddc6660c277876287322f60510f93a4e94cbec
[ "MIT" ]
2
2017-07-06T10:50:11.000Z
2017-07-06T11:33:05.000Z
RunsCamera/Classes/RunsCameraViewDelegate.h
RunsCode/Camera
ebddc6660c277876287322f60510f93a4e94cbec
[ "MIT" ]
null
null
null
RunsCamera/Classes/RunsCameraViewDelegate.h
RunsCode/Camera
ebddc6660c277876287322f60510f93a4e94cbec
[ "MIT" ]
2
2018-02-01T06:52:37.000Z
2021-11-17T06:46:25.000Z
// // RunsCameraViewDelegate.h // Hey // // Created by Dev_Wang on 2017/5/31. // Copyright © 2017年 www.dev_wang.com. All rights reserved. // #import <Foundation/Foundation.h> @protocol RunsCameraViewDelegate <NSObject> - (void)cameraViewDidDismissed:(UIView *)cameraView; - (void)cameraViewDidSelectedAlnbum:(UIView *)cameraView; - (void)cameraView:(UIView *)cameraView captureStillImage:(UIImage *)image; - (void)cameraView:(UIView *)cameraView captureVideoURL:(NSURL *)outputFileURL; @end
29.235294
79
0.756539
49ae12ab64c4c50d1a329b40ea846dc7ad0d28d0
1,821
h
C
connections/implementation/wifi_hotspot_endpoint_channel.h
google/nearby
1aeb1093a9864c73394d27598684f2e9287d6e4e
[ "Apache-2.0" ]
69
2021-10-18T00:37:29.000Z
2022-03-20T19:53:38.000Z
connections/implementation/wifi_hotspot_endpoint_channel.h
google/nearby
1aeb1093a9864c73394d27598684f2e9287d6e4e
[ "Apache-2.0" ]
14
2021-10-13T19:49:27.000Z
2022-03-31T22:19:13.000Z
connections/implementation/wifi_hotspot_endpoint_channel.h
google/nearby
1aeb1093a9864c73394d27598684f2e9287d6e4e
[ "Apache-2.0" ]
22
2021-10-20T12:36:47.000Z
2022-03-31T18:39:46.000Z
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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 CORE_INTERNAL_WIFI_HOTSPOT_ENDPOINT_CHANNEL_H_ #define CORE_INTERNAL_WIFI_HOTSPOT_ENDPOINT_CHANNEL_H_ #include <string> #include "connections/implementation/base_endpoint_channel.h" #include "internal/platform/wifi_hotspot.h" namespace location { namespace nearby { namespace connections { class WifiHotspotEndpointChannel final : public BaseEndpointChannel { public: // Creates both outgoing and incoming WifiHotspot channels. WifiHotspotEndpointChannel(const std::string& service_id, const std::string& channel_name, WifiHotspotSocket socket); // Not copyable or movable WifiHotspotEndpointChannel(const WifiHotspotEndpointChannel&) = delete; WifiHotspotEndpointChannel& operator=(const WifiHotspotEndpointChannel&) = delete; WifiHotspotEndpointChannel(WifiHotspotEndpointChannel&&) = delete; WifiHotspotEndpointChannel& operator=(WifiHotspotEndpointChannel&&) = delete; proto::connections::Medium GetMedium() const override; private: void CloseImpl() override; WifiHotspotSocket socket_; }; } // namespace connections } // namespace nearby } // namespace location #endif // CORE_INTERNAL_WIFI_HOTSPOT_ENDPOINT_CHANNEL_H_
33.722222
79
0.763317
a0b38f5e00ac0c3eacc5650f0791933010d0a094
3,030
h
C
include/afv-native/audio/WavFile.h
kuroneko/AFV-Native
6e333322badb5248bb5b37994815066838034bde
[ "BSD-3-Clause" ]
6
2020-03-22T21:45:30.000Z
2021-10-10T09:04:32.000Z
include/afv-native/audio/WavFile.h
xpilot-project/AFV-Native
b79feb90f31ded5f736234a58c6b07ee86cf9384
[ "BSD-3-Clause" ]
2
2019-11-24T20:58:29.000Z
2020-06-27T07:41:50.000Z
include/afv-native/audio/WavFile.h
xpilot-project/AFV-Native
b79feb90f31ded5f736234a58c6b07ee86cf9384
[ "BSD-3-Clause" ]
3
2020-10-12T11:57:47.000Z
2020-12-14T14:41:36.000Z
/* WavFile.h * * Class(es) for reading audio samples * * Copyright (C) 2018, Christopher Collins * * This file is part of AFV-Native. * * Copyright (c) 2019 Christopher Collins * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * This module is only intended to support a narrow subset of possible Wav * files, namely: PCM only. */ #ifndef AFV_NATIVE_WAVFILE_H #define AFV_NATIVE_WAVFILE_H #include <cstdlib> #include <cstdint> namespace afv_native { namespace audio { class AudioSampleData { protected: int8_t mNumChannels; int8_t mBitsPerSample; uint8_t mSampleAlignment; int mSampleRate; unsigned mSampleCount; void *mSampleData; bool mIsFloat; public: AudioSampleData(int numChannels, int bitsPerSample, int sampleRate, bool isFloat = false); AudioSampleData(AudioSampleData &&move_src) noexcept; AudioSampleData(const AudioSampleData &cpy_src); virtual ~AudioSampleData(); int8_t getNumChannels() const; int8_t getBitsPerSample() const; uint8_t getSampleAlignment() const; int getSampleRate() const; size_t getSampleCount() const; const void *getSampleData() const; bool isFloat() const; void AppendSamples(uint8_t blockSize, unsigned count, void *data); }; AudioSampleData *LoadWav(const char *fileName); } } #endif /* AFV_NATIVE_WAVFILE_H */
36.071429
102
0.69835
6f32fe39c88ee000dcd785d1cd0b032522e2352e
4,024
h
C
cs6V81-kinect-research/project/MyKinect.h
gsteelman/utd
65bf3b81b7a089612f6c7546aa0bbdfbdcdb334e
[ "Apache-2.0" ]
3
2017-03-17T15:15:11.000Z
2020-10-01T16:05:17.000Z
cs6V81-kinect-research/project/MyKinect.h
gsteelman/utd
65bf3b81b7a089612f6c7546aa0bbdfbdcdb334e
[ "Apache-2.0" ]
null
null
null
cs6V81-kinect-research/project/MyKinect.h
gsteelman/utd
65bf3b81b7a089612f6c7546aa0bbdfbdcdb334e
[ "Apache-2.0" ]
7
2016-02-07T22:56:26.000Z
2021-02-26T02:50:28.000Z
#pragma once #include "NuiApi.h" #include "ImageMap.h" class MyKinect { public: // Pointer to actual Kinect sensor struct INuiSensor* m_pNuiSensor; // Received image resolutions static const NUI_IMAGE_RESOLUTION cDepthResolution = NUI_IMAGE_RESOLUTION_640x480; static const NUI_IMAGE_RESOLUTION cColorResolution = NUI_IMAGE_RESOLUTION_640x480; // Handles for Kinect events HANDLE m_hNextDepthFrameEvent; HANDLE m_pDepthStreamHandle; bool m_bDepthReceived; HANDLE m_hNextColorFrameEvent; HANDLE m_pColorStreamHandle; bool m_bColorReceived; static const unsigned int cBytesPerPixel = 4; // Storage of depth and color pixels in arrays for working with later! ImageMap<unsigned __int16> m_depth_map; ImageMap<unsigned __int32> m_color_map; USHORT* m_depthD16; BYTE* m_colorRGBX; LONG* m_colorCoordinates; bool m_bNearMode; /// <summary> /// Toggles between near and default mode /// Does nothing on a non-Kinect for Windows device /// </summary> /// <returns>S_OK for success, or failure code</returns> HRESULT toggle_near_mode() { HRESULT hr = E_FAIL; if ( m_pNuiSensor ) { hr = m_pNuiSensor->NuiImageStreamSetImageFrameFlags( m_pDepthStreamHandle, m_bNearMode ? 0 : NUI_IMAGE_STREAM_FLAG_ENABLE_NEAR_MODE); if ( SUCCEEDED(hr) ) { m_bNearMode = !m_bNearMode; } } return hr; } /// <summary> /// Create the first connected Kinect found /// </summary> /// <returns>indicates success or failure</returns> HRESULT create_device() { INuiSensor * pNuiSensor = NULL; HRESULT hr; int iSensorCount = 0; hr = NuiGetSensorCount(&iSensorCount); if ( FAILED(hr) ) { return hr; } // Look at each Kinect sensor for ( int i = 0; i < iSensorCount; ++i ) { // Create the sensor. If we can't create it, try the next hr = NuiCreateSensorByIndex( i, &pNuiSensor ); if ( FAILED(hr) ) { continue; } // If sensor is connected, initialize it hr = pNuiSensor->NuiStatus(); if ( S_OK == hr ) { m_pNuiSensor = pNuiSensor; break; } // This sensor wasn't OK, so release it since we're not using it pNuiSensor->Release(); } // Coult not connec to any Kinect sensors if ( NULL == m_pNuiSensor ) { return E_FAIL; } // Initialize the Kinect and specify to use depth (with player index) and color streams hr = m_pNuiSensor->NuiInitialize(NUI_INITIALIZE_FLAG_USES_COLOR | NUI_INITIALIZE_FLAG_USES_DEPTH_AND_PLAYER_INDEX); if ( FAILED(hr) ) { return hr; } // Create an event that will be signaled when depth data is available m_hNextDepthFrameEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); // Open a depth image stream to receive depth frames hr = m_pNuiSensor->NuiImageStreamOpen( NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX, cDepthResolution, 0, 2, m_hNextDepthFrameEvent, &m_pDepthStreamHandle ); if ( FAILED(hr) ) { return hr; } // Create an event that will be signaled when color data is available m_hNextColorFrameEvent = CreateEvent( NULL, TRUE, FALSE, NULL ); // Open a color image stream to receive color frames hr = m_pNuiSensor->NuiImageStreamOpen( NUI_IMAGE_TYPE_COLOR, cColorResolution, 0, 2, m_hNextColorFrameEvent, &m_pColorStreamHandle ); if (FAILED(hr) ) { return hr; } // Start with near mode on toggle_near_mode(); return hr; } }; // Kinect
31.685039
120
0.593439
1782c2167ffa51c8a8cb53a78f73ae2b297b99d8
4,641
h
C
sys/bus/u4b/net/if_cuereg.h
cooljeanius/DragonFlyBSD
4c4e823ecc4019d4536be9493e38fef118f9a8cf
[ "BSD-3-Clause" ]
1
2018-01-12T03:55:33.000Z
2018-01-12T03:55:33.000Z
sys/bus/u4b/net/if_cuereg.h
jorisgio/DragonFlyBSD
d37cc9027d161f3e36bf2667d32f41f87606b2ac
[ "BSD-3-Clause" ]
null
null
null
sys/bus/u4b/net/if_cuereg.h
jorisgio/DragonFlyBSD
d37cc9027d161f3e36bf2667d32f41f87606b2ac
[ "BSD-3-Clause" ]
null
null
null
/*- * Copyright (c) 1997, 1998, 1999, 2000 * Bill Paul <wpaul@ee.columbia.edu>. 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Bill Paul. * 4. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Bill Paul 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 Bill Paul OR THE VOICES IN HIS HEAD * 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. * * $FreeBSD$ */ /* * Definitions for the CATC Netmate II USB to ethernet controller. */ /* Vendor specific control commands. */ #define CUE_CMD_RESET 0xF4 #define CUE_CMD_GET_MACADDR 0xF2 #define CUE_CMD_WRITEREG 0xFA #define CUE_CMD_READREG 0xFB #define CUE_CMD_READSRAM 0xF1 #define CUE_CMD_WRITESRAM 0xFC /* Internal registers. */ #define CUE_TX_BUFCNT 0x20 #define CUE_RX_BUFCNT 0x21 #define CUE_ADVANCED_OPMODES 0x22 #define CUE_TX_BUFPKTS 0x23 #define CUE_RX_BUFPKTS 0x24 #define CUE_RX_MAXCHAIN 0x25 #define CUE_ETHCTL 0x60 #define CUE_ETHSTS 0x61 #define CUE_PAR5 0x62 #define CUE_PAR4 0x63 #define CUE_PAR3 0x64 #define CUE_PAR2 0x65 #define CUE_PAR1 0x66 #define CUE_PAR0 0x67 /* Error counters, all 16 bits wide. */ #define CUE_TX_SINGLECOLL 0x69 #define CUE_TX_MULTICOLL 0x6B #define CUE_TX_EXCESSCOLL 0x6D #define CUE_RX_FRAMEERR 0x6F #define CUE_LEDCTL 0x81 /* Advenced operating mode register. */ #define CUE_AOP_SRAMWAITS 0x03 #define CUE_AOP_EMBED_RXLEN 0x08 #define CUE_AOP_RXCOMBINE 0x10 #define CUE_AOP_TXCOMBINE 0x20 #define CUE_AOP_EVEN_PKT_READS 0x40 #define CUE_AOP_LOOPBK 0x80 /* Ethernet control register. */ #define CUE_ETHCTL_RX_ON 0x01 #define CUE_ETHCTL_LINK_POLARITY 0x02 #define CUE_ETHCTL_LINK_FORCE_OK 0x04 #define CUE_ETHCTL_MCAST_ON 0x08 #define CUE_ETHCTL_PROMISC 0x10 /* Ethernet status register. */ #define CUE_ETHSTS_NO_CARRIER 0x01 #define CUE_ETHSTS_LATECOLL 0x02 #define CUE_ETHSTS_EXCESSCOLL 0x04 #define CUE_ETHSTS_TXBUF_AVAIL 0x08 #define CUE_ETHSTS_BAD_POLARITY 0x10 #define CUE_ETHSTS_LINK_OK 0x20 /* LED control register. */ #define CUE_LEDCTL_BLINK_1X 0x00 #define CUE_LEDCTL_BLINK_2X 0x01 #define CUE_LEDCTL_BLINK_QUARTER_ON 0x02 #define CUE_LEDCTL_BLINK_QUARTER_OFF 0x03 #define CUE_LEDCTL_OFF 0x04 #define CUE_LEDCTL_FOLLOW_LINK 0x08 /* * Address in ASIC's internal SRAM where the multicast hash table lives. * The table is 64 bytes long, giving us a 512-bit table. We have to set * the bit that corresponds to the broadcast address in order to enable * reception of broadcast frames. */ #define CUE_MCAST_TABLE_ADDR 0xFA80 #define CUE_TIMEOUT 1000 #define CUE_MIN_FRAMELEN 60 #define CUE_RX_FRAMES 1 #define CUE_TX_FRAMES 1 #define CUE_CTL_READ 0x01 #define CUE_CTL_WRITE 0x02 #define CUE_CONFIG_IDX 0 /* config number 1 */ #define CUE_IFACE_IDX 0 /* The interrupt endpoint is currently unused by the KLSI part. */ enum { CUE_BULK_DT_WR, CUE_BULK_DT_RD, CUE_N_TRANSFER, }; struct cue_softc { struct usb_ether sc_ue; struct mtx sc_mtx; struct usb_xfer *sc_xfer[CUE_N_TRANSFER]; int sc_flags; #define CUE_FLAG_LINK 0x0001 /* got a link */ }; #define CUE_LOCK(_sc) mtx_lock(&(_sc)->sc_mtx) #define CUE_UNLOCK(_sc) mtx_unlock(&(_sc)->sc_mtx) #define CUE_LOCK_ASSERT(_sc, t) mtx_assert(&(_sc)->sc_mtx, t)
34.894737
77
0.776557
a5679ffb4a9384a8649ea4dd1ca3b5c82abfedcf
30,593
c
C
third_party/cordio/ble-profiles/sources/apps/app/app_master.c
vaxradius/Apollo4B-SDK-2021.02.08
507e328b16a179f5d5b18685d5be4a5c6753f852
[ "BSD-3-Clause" ]
null
null
null
third_party/cordio/ble-profiles/sources/apps/app/app_master.c
vaxradius/Apollo4B-SDK-2021.02.08
507e328b16a179f5d5b18685d5be4a5c6753f852
[ "BSD-3-Clause" ]
null
null
null
third_party/cordio/ble-profiles/sources/apps/app/app_master.c
vaxradius/Apollo4B-SDK-2021.02.08
507e328b16a179f5d5b18685d5be4a5c6753f852
[ "BSD-3-Clause" ]
null
null
null
/*************************************************************************************************/ /*! * \file * * \brief Application framework module for master. * * Copyright (c) 2011-2019 Arm Ltd. * * Copyright (c) 2019 Packetcraft, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*************************************************************************************************/ #include "wsf_types.h" #include "wsf_msg.h" #include "wsf_timer.h" #include "wsf_trace.h" #include "wsf_assert.h" #include "dm_api.h" #include "att_api.h" #include "svc_core.h" #include "app_api.h" #include "app_main.h" #include "app_cfg.h" #include <stdbool.h> #include "hci_drv_apollo.h" #include "dm_api.h" /************************************************************************************************** Macros **************************************************************************************************/ /* Constant used in the address type indicating value not present */ #define APP_ADDR_NONE 0xFF /************************************************************************************************** Global Variables **************************************************************************************************/ /* Master control block */ appMasterCb_t appMasterCb; /*************************************************************************************************/ /*! * \brief Initiate security * * \param connId Connection ID. * \param initiatePairing TRUE to initiate pairing. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appMasterInitiateSec(dmConnId_t connId, bool_t initiatePairing, appConnCb_t *pCb) { uint8_t rKeyDist; uint8_t secLevel; dmSecKey_t *pKey; /* if we have an LTK for peer device */ if ((pCb->dbHdl != APP_DB_HDL_NONE) && ((pKey = AppDbGetKey(pCb->dbHdl, DM_KEY_PEER_LTK, &secLevel)) != NULL)) { pCb->bondByLtk = TRUE; pCb->initiatingSec = TRUE; /* encrypt with LTK */ DmSecEncryptReq(connId, secLevel, &pKey->ltk); } /* no key; initiate pairing only if requested */ else if (initiatePairing) { /* store bonding state */ pCb->bondByPairing = (pAppSecCfg->auth & DM_AUTH_BOND_FLAG) == DM_AUTH_BOND_FLAG; /* if bonding and no device record */ if (pCb->bondByPairing && pCb->dbHdl == APP_DB_HDL_NONE) { /* create a device record if none exists */ pCb->dbHdl = AppDbNewRecord(DmConnPeerAddrType(connId), DmConnPeerAddr(connId), TRUE); } /* initialize stored keys */ pCb->rcvdKeys = 0; /* if peer is using random address request IRK */ rKeyDist = pAppSecCfg->rKeyDist; if (DmConnPeerAddrType(connId) == DM_ADDR_RANDOM) { rKeyDist |= DM_KEY_DIST_IRK; } pCb->initiatingSec = TRUE; /* initiate pairing */ DmSecPairReq(connId, pAppSecCfg->oob, pAppSecCfg->auth, pAppSecCfg->iKeyDist, rKeyDist); } } /*************************************************************************************************/ /*! * \brief Clear all scan results. * * \return None. */ /*************************************************************************************************/ static void appScanResultsClear(void) { uint8_t i; appDevInfo_t *pDev = appMasterCb.scanResults; appMasterCb.numScanResults = 0; for (i = APP_SCAN_RESULT_MAX; i > 0; i--, pDev++) { pDev->addrType = APP_ADDR_NONE; } /* end address resolution */ appMasterCb.inProgress = FALSE; } /*************************************************************************************************/ /*! * \brief Add a scan report to the scan result list. * * \param pMsg Pointer to DM callback event message. * * \return None. */ /*************************************************************************************************/ static void appScanResultAdd(dmEvt_t *pMsg) { uint8_t i; appDevInfo_t *pDev = appMasterCb.scanResults; /* see if device is in list already */ for (i = 0; i < APP_SCAN_RESULT_MAX; i++, pDev++) { if(DmScanModeLeg()) { /* if address matches list entry */ if ((pDev->addrType == pMsg->scanReport.addrType) && BdaCmp(pDev->addr, pMsg->scanReport.addr)) { /* device already exists in list; we are done */ break; } /* if entry is free end then of list has been reached */ else if (pDev->addrType == APP_ADDR_NONE) { /* add device to list */ pDev->addrType = pMsg->scanReport.addrType; BdaCpy(pDev->addr, pMsg->scanReport.addr); pDev->directAddrType = pMsg->scanReport.directAddrType; BdaCpy(pDev->directAddr, pMsg->scanReport.directAddr); appMasterCb.numScanResults++; break; } } else { /* if address matches list entry */ if ((pDev->addrType == pMsg->extScanReport.addrType) && BdaCmp(pDev->addr, pMsg->extScanReport.addr)) { /* device already exists in list; we are done */ break; } /* if entry is free end then of list has been reached */ else if (pDev->addrType == APP_ADDR_NONE) { /* add device to list */ pDev->addrType = pMsg->extScanReport.addrType; pDev->secPhy = pMsg->extScanReport.secPhy; BdaCpy(pDev->addr, pMsg->extScanReport.addr); pDev->directAddrType = pMsg->extScanReport.directAddrType; BdaCpy(pDev->directAddr, pMsg->extScanReport.directAddr); appMasterCb.numScanResults++; break; } } } } /*************************************************************************************************/ /*! * \brief Find a scan report in the scan result list. * * \param pMsg Pointer to DM callback event message. * * \return Index of result in scan result list. APP_SCAN_RESULT_MAX, otherwise. */ /*************************************************************************************************/ static uint8_t appScanResultFind(dmEvt_t *pMsg) { uint8_t i; appDevInfo_t *pDev = appMasterCb.scanResults; /* see if device is in list already */ for (i = 0; i < APP_SCAN_RESULT_MAX; i++, pDev++) { if(DmScanModeLeg()) { /* if address matches list entry */ if ((pDev->addrType == pMsg->scanReport.addrType) && BdaCmp(pDev->addr, pMsg->scanReport.addr)) { /* device already exists in list; we are done */ break; } } else { /* if address matches list entry */ if ((pDev->addrType == pMsg->extScanReport.addrType) && BdaCmp(pDev->addr, pMsg->extScanReport.addr)) { /* device already exists in list; we are done */ break; } } } return i; } /*************************************************************************************************/ /*! * \brief Handle a DM_SCAN_START_IND event. * * \param pMsg Pointer to DM callback event message. * * \return None. */ /*************************************************************************************************/ static void appMasterScanStart(dmEvt_t *pMsg) { if (pMsg->hdr.status == HCI_SUCCESS) { /* clear current scan results */ appScanResultsClear(); } } /*************************************************************************************************/ /*! * \brief Handle a DM_SCAN_STOP_IND event. * * \param pMsg Pointer to DM callback event message. * * \return None. */ /*************************************************************************************************/ static void appMasterScanStop(dmEvt_t *pMsg) { if (pMsg->hdr.status == HCI_SUCCESS) { APP_TRACE_INFO1("Scan results: %d", AppScanGetNumResults()); } } /*************************************************************************************************/ /*! * \brief Handle a DM_SCAN_REPORT_IND event. * * \param pMsg Pointer to DM callback event message. * * \return None. */ /*************************************************************************************************/ static void appMasterScanReport(dmEvt_t *pMsg) { /* add to scan result list */ appScanResultAdd(pMsg); } /*************************************************************************************************/ /*! * \brief Handle a DM_CONN_OPEN_IND event. * * \param pMsg Pointer to DM callback event message. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appMasterConnOpen(dmEvt_t *pMsg, appConnCb_t *pCb) { DmReadRemoteFeatures((dmConnId_t) pMsg->hdr.param); } /*************************************************************************************************/ /*! * \brief Handle a DM_CONN_CLOSE_IND event. * * \param pMsg Pointer to DM callback event message. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appMasterConnClose(dmEvt_t *pMsg, appConnCb_t *pCb) { /* update privacy mode for peer device */ AppUpdatePrivacyMode(pCb->dbHdl); /* clear connection ID */ pCb->connId = DM_CONN_ID_NONE; /* cancel any address resolution in progress */ appMasterCb.inProgress = FALSE; } /*************************************************************************************************/ /*! * \brief Perform master security procedures on connection open. * * \param pMsg Pointer to DM callback event message. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appMasterSecConnOpen(dmEvt_t *pMsg, appConnCb_t *pCb) { /* initialize state variables */ pCb->bonded = FALSE; pCb->bondByLtk = FALSE; pCb->bondByPairing = FALSE; pCb->initiatingSec = FALSE; /* if master initiates security on connection open */ appMasterInitiateSec((dmConnId_t) pMsg->hdr.param, pAppSecCfg->initiateSec, pCb); } /*************************************************************************************************/ /*! * \brief Perform security procedures on connection close. * * \param pMsg Pointer to DM callback event message. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appMasterSecConnClose(dmEvt_t *pMsg, appConnCb_t *pCb) { /* if a device record was created check if it is valid */ if (pCb->dbHdl != APP_DB_HDL_NONE) { AppDbCheckValidRecord(pCb->dbHdl); } } /*************************************************************************************************/ /*! * \brief Handle a slave security request. * * \param pMsg Pointer to DM callback event message. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appMasterSecSlaveReq(dmEvt_t *pMsg, appConnCb_t *pCb) { /* if master is not initiating security and not already secure */ if (!pAppSecCfg->initiateSec && !pCb->initiatingSec && (DmConnSecLevel((dmConnId_t) pMsg->hdr.param) == DM_SEC_LEVEL_NONE)) { appMasterInitiateSec((dmConnId_t) pMsg->hdr.param, TRUE, pCb); } } /*************************************************************************************************/ /*! * \brief Handle set address resolution enable indication. * * \param pMsg Pointer to DM callback event message. * * \return None. */ /*************************************************************************************************/ static void appPrivSetAddrResEnableInd(dmEvt_t *pMsg) { if (pMsg->hdr.status == HCI_SUCCESS) { SvcCoreGapCentAddrResUpdate(DmLlPrivEnabled()); } } /*************************************************************************************************/ /*! * \brief Handle add device to resolving list indication. * * \param pMsg Pointer to DM callback event message. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appPrivAddDevToResListInd(dmEvt_t *pMsg, appConnCb_t *pCb) { if ((pMsg->hdr.status == HCI_SUCCESS) && (pCb->dbHdl != APP_DB_HDL_NONE)) { /* peer device's been added to resolving list */ AppDbSetPeerAddedToRl(pCb->dbHdl, TRUE); } } /*************************************************************************************************/ /*! * \brief Handle remove device from resolving list indication. * * \param pMsg Pointer to DM callback event message. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appPrivRemDevFromResListInd(dmEvt_t *pMsg, appConnCb_t *pCb) { if ((pMsg->hdr.status == HCI_SUCCESS) && (pCb->dbHdl != APP_DB_HDL_NONE)) { /* peer device's been removed from resolving list */ AppDbSetPeerAddedToRl(pCb->dbHdl, FALSE); } } /*************************************************************************************************/ /*! * \brief Store security key. * * \param pMsg Pointer to DM callback event message. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appMasterSecStoreKey(dmEvt_t *pMsg, appConnCb_t *pCb) { if (pCb->bondByPairing && pCb->dbHdl != APP_DB_HDL_NONE) { /* key was received */ pCb->rcvdKeys |= pMsg->keyInd.type; /* store key in record */ AppDbSetKey(pCb->dbHdl, &pMsg->keyInd); } } /*************************************************************************************************/ /*! * \brief Handle pairing complete. * * \param pMsg Pointer to DM callback event message. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appMasterSecPairCmpl(dmEvt_t *pMsg, appConnCb_t *pCb) { /* if bonding */ if (pMsg->pairCmpl.auth & DM_AUTH_BOND_FLAG) { /* set bonded state */ pCb->bonded = TRUE; /* validate record and received keys */ if (pCb->dbHdl != APP_DB_HDL_NONE) { AppDbValidateRecord(pCb->dbHdl, pCb->rcvdKeys); } /* if bonded, add device to resolving list */ if (pCb->dbHdl != APP_DB_HDL_NONE) { AppAddDevToResList(pMsg, pCb->connId); } } pCb->initiatingSec = FALSE; } /*************************************************************************************************/ /*! * \brief Handle pairing failed * * \param pMsg Pointer to DM callback event message. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appMasterSecPairFailed(dmEvt_t *pMsg, appConnCb_t *pCb) { pCb->initiatingSec = FALSE; // disconnect the connection when paired failed to avoid spoofing reported by https://nvd.nist.gov/vuln/detail/CVE-2020-9770 AppConnClose(pMsg->hdr.param); return; } /*************************************************************************************************/ /*! * \brief Handle encryption indication * * \param pMsg Pointer to DM callback event message. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appMasterSecEncryptInd(dmEvt_t *pMsg, appConnCb_t *pCb) { /* check if bonding state should be set */ if (pCb->bondByLtk && pMsg->encryptInd.usingLtk) { pCb->bonded = TRUE; pCb->bondByLtk = FALSE; pCb->initiatingSec = FALSE; } } /*************************************************************************************************/ /*! * \brief Process app framework messages for a master. * * \param pMsg Pointer to message. * * \return None. */ /*************************************************************************************************/ void appMasterProcMsg(wsfMsgHdr_t *pMsg) { switch(pMsg->event) { case APP_CONN_UPDATE_TIMEOUT_IND: break; default: break; } } /*************************************************************************************************/ /*! * \brief Process a received privacy resolved address indication. * * \param pMsg Pointer to DM message. * * \return None. */ /*************************************************************************************************/ static void appMasterResolvedAddrInd(dmEvt_t *pMsg) { appDevInfo_t *pDev; dmSecKey_t *pPeerKey; /* if address resolution is not in progress */ if (!appMasterCb.inProgress) { return; } /* get device record */ pDev = &appMasterCb.scanResults[appMasterCb.idx]; /* if RPA resolved */ if (pMsg->hdr.status == HCI_SUCCESS) { /* if resolved advertising was directed with an RPA initiator address */ if ((pMsg->hdr.param == APP_RESOLVE_ADV_RPA) && DM_RAND_ADDR_RPA(pDev->directAddr, pDev->directAddrType)) { /* resolve initiator's RPA to see if directed advertisement was addressed to us */ DmPrivResolveAddr(pDev->directAddr, DmSecGetLocalIrk(), APP_RESOLVE_DIRECT_RPA); /* not done yet */ return; } if(DmScanModeLeg()) { /* stop scanning */ AppScanStop(); /* connect to peer device using its advertising address */ AppConnOpen(pDev->addrType, pDev->addr, appMasterCb.dbHdl); } else { AppExtScanStop(); AppExtConnOpen(pDev->secPhy, pDev->addrType, pDev->addr, appMasterCb.dbHdl); } } /* if RPA did not resolve and there're more bonded records to go through */ else if ((pMsg->hdr.status == HCI_ERR_AUTH_FAILURE) && (appMasterCb.dbHdl != APP_DB_HDL_NONE)) { /* get the next database record */ appMasterCb.dbHdl = AppDbGetNextRecord(appMasterCb.dbHdl); /* if there's another bond record */ if ((appMasterCb.dbHdl != APP_DB_HDL_NONE) && ((pPeerKey = AppDbGetKey(appMasterCb.dbHdl, DM_KEY_IRK, NULL)) != NULL)) { /* resolve RPA using the next stored IRK */ DmPrivResolveAddr(pDev->addr, pPeerKey->irk.key, APP_RESOLVE_ADV_RPA); /* not done yet */ return; } } /* done with this address resolution */ appMasterCb.inProgress = FALSE; } /*************************************************************************************************/ /*! * \brief Handle a DM_REM_CONN_PARAM_REQ_IND event. * * \param pMsg Pointer to DM callback event message. * \param pCb Connection control block. * * \return None. */ /*************************************************************************************************/ static void appMasterRemoteConnParamReq(dmEvt_t *pMsg, appConnCb_t *pCb) { /* if configured to accept the remote connection parameter request */ if (pAppMasterReqActCfg->remConnParamReqAct == APP_ACT_ACCEPT) { hciConnSpec_t connSpec; connSpec.connIntervalMin = pMsg->remConnParamReq.intervalMin; connSpec.connIntervalMax = pMsg->remConnParamReq.intervalMax; connSpec.connLatency = pMsg->remConnParamReq.latency; connSpec.supTimeout = pMsg->remConnParamReq.timeout; connSpec.minCeLen = connSpec.maxCeLen = 0; /* accept the remote device's request to change connection parameters */ DmRemoteConnParamReqReply(pCb->connId, &connSpec); } /* if configured to reject the remote connection parameter request */ else if (pAppMasterReqActCfg->remConnParamReqAct == APP_ACT_REJECT) { /* reject the remote device's request to change connection parameters */ DmRemoteConnParamReqNegReply(pCb->connId, HCI_ERR_UNSUP_FEAT); } /* else - app will handle the remote connection parameter request */ } /*************************************************************************************************/ /*! * \brief Initialize app framework master. * * \return None. */ /*************************************************************************************************/ void AppMasterInit(void) { appMasterCb.inProgress = FALSE; /* initialize scan mode */ appMasterCb.scanMode = APP_SCAN_MODE_NONE; /* set up callback from main */ appCb.masterCback = appMasterProcMsg; } /*************************************************************************************************/ /*! * \brief Process connection-related DM messages for a master. This function should be called * from the application's event handler. * * \param pMsg Pointer to DM callback event message. * * \return None. */ /*************************************************************************************************/ void AppMasterProcDmMsg(dmEvt_t *pMsg) { appConnCb_t *pCb = NULL; /* look up app connection control block from DM connection ID */ if (pMsg->hdr.event == DM_CONN_OPEN_IND || pMsg->hdr.event == DM_CONN_CLOSE_IND || pMsg->hdr.event == DM_REM_CONN_PARAM_REQ_IND) { pCb = &appConnCb[pMsg->hdr.param - 1]; } switch(pMsg->hdr.event) { case DM_RESET_CMPL_IND: /* reset scan mode */ appMasterCb.scanMode = APP_SCAN_MODE_NONE; break; case DM_EXT_SCAN_START_IND: case DM_SCAN_START_IND: appMasterScanStart(pMsg); break; case DM_EXT_SCAN_STOP_IND: case DM_SCAN_STOP_IND: appMasterScanStop(pMsg); break; case DM_EXT_SCAN_REPORT_IND: case DM_SCAN_REPORT_IND: appMasterScanReport(pMsg); break; case DM_CONN_OPEN_IND: appMasterConnOpen(pMsg, pCb); break; case DM_CONN_CLOSE_IND: appMasterConnClose(pMsg, pCb); break; case DM_PRIV_RESOLVED_ADDR_IND: appMasterResolvedAddrInd(pMsg); break; case DM_REM_CONN_PARAM_REQ_IND: appMasterRemoteConnParamReq(pMsg, pCb); break; default: break; } } /*************************************************************************************************/ /*! * \brief Process security-related DM messages for a master. This function should be called * from the application's event handler. * * \param pMsg Pointer to DM callback event message. * * \return None. */ /*************************************************************************************************/ void AppMasterSecProcDmMsg(dmEvt_t *pMsg) { appConnCb_t *pCb; /* look up app connection control block from DM connection ID */ pCb = &appConnCb[pMsg->hdr.param - 1]; switch(pMsg->hdr.event) { case DM_CONN_OPEN_IND: appMasterSecConnOpen(pMsg, pCb); break; case DM_CONN_CLOSE_IND: appMasterSecConnClose(pMsg, pCb); break; case DM_SEC_PAIR_CMPL_IND: appMasterSecPairCmpl(pMsg, pCb); break; case DM_SEC_PAIR_FAIL_IND: appMasterSecPairFailed(pMsg, pCb); break; case DM_SEC_ENCRYPT_IND: appMasterSecEncryptInd(pMsg, pCb); break; case DM_SEC_ENCRYPT_FAIL_IND: // disconnect the connection when paired failed to avoid spoofing reported by https://nvd.nist.gov/vuln/detail/CVE-2020-9770 AppConnClose(pMsg->hdr.param); break; case DM_SEC_KEY_IND: appMasterSecStoreKey(pMsg, pCb); break; case DM_SEC_SLAVE_REQ_IND: appMasterSecSlaveReq(pMsg, pCb); break; case DM_PRIV_SET_ADDR_RES_ENABLE_IND: appPrivSetAddrResEnableInd(pMsg); break; case DM_PRIV_ADD_DEV_TO_RES_LIST_IND: appPrivAddDevToResListInd(pMsg, pCb); break; case DM_PRIV_REM_DEV_FROM_RES_LIST_IND: appPrivRemDevFromResListInd(pMsg, pCb); break; case DM_HW_ERROR_IND: HciDrvRadioBoot(0); DmDevReset(); break; default: break; } } /*************************************************************************************************/ /*! * \brief Get a stored scan result from the scan result list. * * \param idx Index of result in scan result list. * * \return Pointer to scan result device info or NULL if index contains no result. */ /*************************************************************************************************/ appDevInfo_t *AppScanGetResult(uint8_t idx) { if (idx < APP_SCAN_RESULT_MAX && appMasterCb.scanResults[idx].addrType != APP_ADDR_NONE) { return &appMasterCb.scanResults[idx]; } else { return NULL; } } /*************************************************************************************************/ /*! * \brief Get the number of stored scan results. * * \return Number of stored scan results. */ /*************************************************************************************************/ uint8_t AppScanGetNumResults(void) { return appMasterCb.numScanResults; } /*************************************************************************************************/ /*! * \brief Open a connection to a peer device with the given initiator PHYs, and address. * * \param initPhys Initiator PHYs. * \param addrType Address type. * \param pAddr Peer device address. * \param dbHdl Device database handle. * * \return Connection identifier. */ /*************************************************************************************************/ dmConnId_t appConnOpen(uint8_t initPhys, uint8_t addrType, uint8_t *pAddr, appDbHdl_t dbHdl) { dmConnId_t connId; appConnCb_t *pCb; /* open connection */ connId = DmConnOpen(DM_CLIENT_ID_APP, initPhys, addrType, pAddr); if (connId != DM_CONN_ID_NONE) { /* set up conn. control block */ pCb = &appConnCb[connId - 1]; pCb->connId = connId; /* if database record handle is in use */ if ((dbHdl != APP_DB_HDL_NONE) && AppDbRecordInUse(dbHdl)) { pCb->dbHdl = dbHdl; } else { pCb->dbHdl = AppDbFindByAddr(addrType, pAddr); } } return connId; } /*************************************************************************************************/ /*! * \brief Initiate security as a master device. If there is a stored encryption key * for the peer device this function will initiate encryption, otherwise it will * initiate pairing. * * \param connId Connection identifier. * * \return None. */ /*************************************************************************************************/ void AppMasterSecurityReq(dmConnId_t connId) { appConnCb_t *pCb; WSF_ASSERT((connId > 0) && (connId <= DM_CONN_MAX)); /* look up app connection control block from DM connection ID */ pCb = &appConnCb[connId - 1]; /* if master is not initiating security and not already secure */ if (!pAppSecCfg->initiateSec && !pCb->initiatingSec && (DmConnSecLevel(connId) == DM_SEC_LEVEL_NONE)) { appMasterInitiateSec(connId, TRUE, pCb); } } /*************************************************************************************************/ /*! * \brief Resolve the advertiser's RPA (AdvA) or the initiator's RPA (InitA) of a directed * advertisement report. If the addresses resolved then a connection will be initiated. * * \param pMsg Pointer to DM callback event message. * \param dbHdl Database record handle. * \param resolveType Which address in advertising report to be resolved. * * \return None. */ /*************************************************************************************************/ void AppMasterResolveAddr(dmEvt_t *pMsg, appDbHdl_t dbHdl, uint8_t resolveType) { uint8_t idx; /* if address resolution's in progress or scan record is not found */ if ((appMasterCb.inProgress) || ((idx = appScanResultFind(pMsg)) >= APP_SCAN_RESULT_MAX)) { return; } /* if asked to resolve direct address */ if (resolveType == APP_RESOLVE_DIRECT_RPA) { if(DmScanModeLeg()) { /* resolve initiator's RPA to see if the directed advertisement is addressed to us */ DmPrivResolveAddr(pMsg->scanReport.directAddr, DmSecGetLocalIrk(), APP_RESOLVE_DIRECT_RPA); } else { /* resolve initiator's RPA to see if the directed advertisement is addressed to us */ DmPrivResolveAddr(pMsg->extScanReport.directAddr, DmSecGetLocalIrk(), APP_RESOLVE_DIRECT_RPA); } /* store scan record index and database record handle for later */ appMasterCb.idx = idx; appMasterCb.dbHdl = dbHdl; appMasterCb.inProgress = TRUE; } /* if asked to resolve advertiser's address */ else if (resolveType == APP_RESOLVE_ADV_RPA) { dmSecKey_t *pPeerKey; appDbHdl_t hdl = AppDbGetNextRecord(APP_DB_HDL_NONE); /* if we have any bond records */ if ((hdl != APP_DB_HDL_NONE) && ((pPeerKey = AppDbGetKey(hdl, DM_KEY_IRK, NULL)) != NULL)) { if(DmScanModeLeg()) { /* resolve advertiser's RPA to see if we already have a bond with this device */ DmPrivResolveAddr(pMsg->scanReport.addr, pPeerKey->irk.key, APP_RESOLVE_ADV_RPA); } else { /* resolve advertiser's RPA to see if we already have a bond with this device */ DmPrivResolveAddr(pMsg->extScanReport.addr, pPeerKey->irk.key, APP_RESOLVE_ADV_RPA); } /* store scan record index and database record handle for later */ appMasterCb.idx = idx; appMasterCb.dbHdl = hdl; appMasterCb.inProgress = TRUE; } } }
30.839718
130
0.515837
02148c48b89d1cb1e05ddb2b4083d57536eb438c
3,815
h
C
Modules/Rendering/DirectX/vaRenderDeviceContextDX11.h
KakCAT/ASSAO
06881a1632576468b9816d3d28aa06b49a06afa8
[ "MIT" ]
234
2016-11-16T06:00:37.000Z
2022-01-06T05:19:14.000Z
Modules/Rendering/DirectX/vaRenderDeviceContextDX11.h
KakCAT/ASSAO
06881a1632576468b9816d3d28aa06b49a06afa8
[ "MIT" ]
9
2017-01-06T17:00:37.000Z
2021-09-03T22:10:00.000Z
Modules/Rendering/DirectX/vaRenderDeviceContextDX11.h
KakCAT/ASSAO
06881a1632576468b9816d3d28aa06b49a06afa8
[ "MIT" ]
34
2016-11-16T16:30:33.000Z
2022-02-23T06:41:30.000Z
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2016, Intel Corporation // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of // the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // File changes (yyyy-mm-dd) // 2016-09-07: filip.strugar@intel.com: first commit (extracted from VertexAsylum codebase, 2006-2016 by Filip Strugar) /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "Core/vaCoreIncludes.h" #include "Rendering/DirectX/vaDirectXCore.h" #include "Rendering/DirectX/vaDirectXTools.h" #include "Rendering/DirectX/vaDirectXShader.h" #include "Rendering/vaRenderingIncludes.h" namespace VertexAsylum { class vaRenderDeviceContextDX11 : public vaRenderDeviceContext, private VertexAsylum::vaDirectXNotifyTarget { VA_RENDERING_MODULE_MAKE_FRIENDS( ); private: ID3D11DeviceContext * m_deviceImmediateContext; private: // fullscreen pass stuff vaDirectXVertexShader m_fullscreenVS; ID3D11Buffer * m_fullscreenVB; ID3D11Buffer * m_fullscreenVBDynamic; protected: vaRenderDeviceContextDX11( const vaConstructorParamsBase * params ); virtual ~vaRenderDeviceContextDX11( ); public: static vaRenderDeviceContext * Create( ID3D11DeviceContext * deviceContext ); ID3D11DeviceContext * GetDXImmediateContext( ) const { return m_deviceImmediateContext; } public: void FullscreenPassDraw( ID3D11DeviceContext * context, ID3D11PixelShader * pixelShader, ID3D11BlendState * blendState = vaDirectXTools::GetBS_Opaque(), ID3D11DepthStencilState * depthStencilState = vaDirectXTools::GetDSS_DepthDisabled_NoDepthWrite(), UINT stencilRef = 0, ID3D11VertexShader * vertexShader = NULL, float ZDistance = 0.0f ); private: void Initialize( ID3D11DeviceContext * deviceContext ); void Destroy( ); private: // vaDirectXNotifyTarget virtual void OnDeviceCreated( ID3D11Device* device, IDXGISwapChain* swapChain ); virtual void OnDeviceDestroyed( ); private: // vaRenderDeviceContext virtual void UpdateViewport( ); virtual void UpdateRenderTargetsDepthStencilUAVs( ); virtual void * GetAPIImmediateContextPtr( ) { return m_deviceImmediateContext; } }; }
50.866667
371
0.618611
9d3e34da53868c4923700e5fadc080353e7a6cc9
84,214
h
C
content/common/view_messages.h
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2015-10-12T09:14:22.000Z
2015-10-12T09:14:22.000Z
content/common/view_messages.h
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
null
null
null
content/common/view_messages.h
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2020-11-04T07:22:28.000Z
2020-11-04T07:22:28.000Z
// Copyright (c) 2011 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. // IPC messages for page rendering. // Multiply-included message file, hence no include guard. #include "base/process.h" #include "base/shared_memory.h" #include "content/common/common_param_traits.h" #include "content/common/css_colors.h" #include "content/common/edit_command.h" #include "content/common/navigation_gesture.h" #include "content/common/page_transition_types.h" #include "content/common/page_zoom.h" #include "content/common/renderer_preferences.h" #include "content/common/webkit_param_traits.h" #include "content/common/window_container_type.h" #include "ipc/ipc_message_macros.h" #include "ipc/ipc_platform_file.h" #include "net/base/host_port_pair.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebCompositionUnderline.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFindOptions.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebMediaPlayerAction.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupType.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebScreenInfo.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebTextInputType.h" #include "ui/gfx/rect.h" #include "webkit/glue/context_menu.h" #include "webkit/glue/password_form.h" #include "webkit/glue/webcookie.h" #include "webkit/glue/webmenuitem.h" #include "webkit/glue/webpreferences.h" #include "webkit/glue/webaccessibility.h" #include "webkit/plugins/npapi/webplugin.h" #include "webkit/plugins/npapi/webplugininfo.h" #include "base/meegotouch_config.h" #if defined(OS_MACOSX) #include "content/common/font_descriptor_mac.h" #endif // Define enums used in this file inside an include-guard. #ifndef CONTENT_COMMON_VIEW_MESSAGES_H_ #define CONTENT_COMMON_VIEW_MESSAGES_H_ struct ViewHostMsg_AccessibilityNotification_Type { enum Value { // The node checked state has changed. NOTIFICATION_TYPE_CHECK_STATE_CHANGED, // The node tree structure has changed. NOTIFICATION_TYPE_CHILDREN_CHANGED, // The node in focus has changed. NOTIFICATION_TYPE_FOCUS_CHANGED, // The document node has loaded. NOTIFICATION_TYPE_LOAD_COMPLETE, // The node value has changed. NOTIFICATION_TYPE_VALUE_CHANGED, // The text cursor or selection changed. NOTIFICATION_TYPE_SELECTED_TEXT_CHANGED, }; }; // Values that may be OR'd together to form the 'flags' parameter of the // ViewMsg_EnablePreferredSizeChangedMode message. enum ViewHostMsg_EnablePreferredSizeChangedMode_Flags { kPreferredSizeNothing, kPreferredSizeWidth = 1 << 0, // Requesting the height currently requires a polling loop in render_view.cc. kPreferredSizeHeightThisIsSlow = 1 << 1, }; struct ViewHostMsg_RunFileChooser_Mode { public: enum Value { // Requires that the file exists before allowing the user to pick it. Open, // Like Open, but allows picking multiple files to open. OpenMultiple, // Like Open, but selects a folder. OpenFolder, // Allows picking a nonexistent file, and prompts to overwrite if the file // already exists. Save, }; }; // Values that may be OR'd together to form the 'flags' parameter of a // ViewHostMsg_UpdateRect_Params structure. struct ViewHostMsg_UpdateRect_Flags { enum { IS_RESIZE_ACK = 1 << 0, IS_RESTORE_ACK = 1 << 1, IS_REPAINT_ACK = 1 << 2, }; static bool is_resize_ack(int flags) { return (flags & IS_RESIZE_ACK) != 0; } static bool is_restore_ack(int flags) { return (flags & IS_RESTORE_ACK) != 0; } static bool is_repaint_ack(int flags) { return (flags & IS_REPAINT_ACK) != 0; } }; struct ViewMsg_Navigate_Type { public: enum Value { // Reload the page. RELOAD, // Reload the page, ignoring any cache entries. RELOAD_IGNORING_CACHE, // The navigation is the result of session restore and should honor the // page's cache policy while restoring form state. This is set to true if // restoring a tab/session from the previous session and the previous // session did not crash. If this is not set and the page was restored then // the page's cache policy is ignored and we load from the cache. RESTORE, // Speculatively prerendering the page. PRERENDER, // Navigation type not categorized by the other types. NORMAL }; }; // The user has completed a find-in-page; this type defines what actions the // renderer should take next. struct ViewMsg_StopFinding_Params { enum Action { kClearSelection, kKeepSelection, kActivateSelection }; ViewMsg_StopFinding_Params() : action(kClearSelection) {} // The action that should be taken when the find is completed. Action action; }; #endif // CONTENT_COMMON_VIEW_MESSAGES_H_ #define IPC_MESSAGE_START ViewMsgStart IPC_ENUM_TRAITS(CSSColors::CSSColorName) IPC_ENUM_TRAITS(NavigationGesture) IPC_ENUM_TRAITS(PageZoom::Function) IPC_ENUM_TRAITS(RendererPreferencesHintingEnum) IPC_ENUM_TRAITS(RendererPreferencesSubpixelRenderingEnum) IPC_ENUM_TRAITS(ViewHostMsg_AccessibilityNotification_Type::Value) IPC_ENUM_TRAITS(ViewHostMsg_RunFileChooser_Mode::Value) IPC_ENUM_TRAITS(ViewMsg_Navigate_Type::Value) IPC_ENUM_TRAITS(ViewMsg_StopFinding_Params::Action) IPC_ENUM_TRAITS(WebKit::WebContextMenuData::MediaType) IPC_ENUM_TRAITS(WebKit::WebMediaPlayerAction::Type) IPC_ENUM_TRAITS(WebKit::WebPopupType) IPC_ENUM_TRAITS(WebKit::WebTextInputType) IPC_ENUM_TRAITS(WebMenuItem::Type) IPC_ENUM_TRAITS(WindowContainerType) IPC_ENUM_TRAITS(webkit_glue::WebAccessibility::Role) IPC_ENUM_TRAITS(webkit_glue::WebAccessibility::State) IPC_STRUCT_TRAITS_BEGIN(ContextMenuParams) IPC_STRUCT_TRAITS_MEMBER(media_type) IPC_STRUCT_TRAITS_MEMBER(x) IPC_STRUCT_TRAITS_MEMBER(y) IPC_STRUCT_TRAITS_MEMBER(link_url) IPC_STRUCT_TRAITS_MEMBER(unfiltered_link_url) IPC_STRUCT_TRAITS_MEMBER(src_url) IPC_STRUCT_TRAITS_MEMBER(is_image_blocked) IPC_STRUCT_TRAITS_MEMBER(page_url) IPC_STRUCT_TRAITS_MEMBER(frame_url) IPC_STRUCT_TRAITS_MEMBER(frame_content_state) IPC_STRUCT_TRAITS_MEMBER(media_flags) IPC_STRUCT_TRAITS_MEMBER(selection_text) IPC_STRUCT_TRAITS_MEMBER(misspelled_word) IPC_STRUCT_TRAITS_MEMBER(dictionary_suggestions) IPC_STRUCT_TRAITS_MEMBER(spellcheck_enabled) IPC_STRUCT_TRAITS_MEMBER(is_editable) #if defined(OS_MACOSX) IPC_STRUCT_TRAITS_MEMBER(writing_direction_default) IPC_STRUCT_TRAITS_MEMBER(writing_direction_left_to_right) IPC_STRUCT_TRAITS_MEMBER(writing_direction_right_to_left) #endif // OS_MACOSX IPC_STRUCT_TRAITS_MEMBER(edit_flags) IPC_STRUCT_TRAITS_MEMBER(security_info) IPC_STRUCT_TRAITS_MEMBER(frame_charset) IPC_STRUCT_TRAITS_MEMBER(custom_context) IPC_STRUCT_TRAITS_MEMBER(custom_items) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(EditCommand) IPC_STRUCT_TRAITS_MEMBER(name) IPC_STRUCT_TRAITS_MEMBER(value) IPC_STRUCT_TRAITS_END() #if defined(OS_MACOSX) IPC_STRUCT_TRAITS_BEGIN(FontDescriptor) IPC_STRUCT_TRAITS_MEMBER(font_name) IPC_STRUCT_TRAITS_MEMBER(font_point_size) IPC_STRUCT_TRAITS_END() #endif IPC_STRUCT_TRAITS_BEGIN(RendererPreferences) IPC_STRUCT_TRAITS_MEMBER(can_accept_load_drops) IPC_STRUCT_TRAITS_MEMBER(should_antialias_text) IPC_STRUCT_TRAITS_MEMBER(hinting) IPC_STRUCT_TRAITS_MEMBER(subpixel_rendering) IPC_STRUCT_TRAITS_MEMBER(focus_ring_color) IPC_STRUCT_TRAITS_MEMBER(thumb_active_color) IPC_STRUCT_TRAITS_MEMBER(thumb_inactive_color) IPC_STRUCT_TRAITS_MEMBER(track_color) IPC_STRUCT_TRAITS_MEMBER(active_selection_bg_color) IPC_STRUCT_TRAITS_MEMBER(active_selection_fg_color) IPC_STRUCT_TRAITS_MEMBER(inactive_selection_bg_color) IPC_STRUCT_TRAITS_MEMBER(inactive_selection_fg_color) IPC_STRUCT_TRAITS_MEMBER(browser_handles_top_level_requests) IPC_STRUCT_TRAITS_MEMBER(caret_blink_interval) IPC_STRUCT_TRAITS_MEMBER(enable_referrers) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(ViewMsg_StopFinding_Params) IPC_STRUCT_TRAITS_MEMBER(action) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(WebKit::WebCompositionUnderline) IPC_STRUCT_TRAITS_MEMBER(startOffset) IPC_STRUCT_TRAITS_MEMBER(endOffset) IPC_STRUCT_TRAITS_MEMBER(color) IPC_STRUCT_TRAITS_MEMBER(thick) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(WebKit::WebFindOptions) IPC_STRUCT_TRAITS_MEMBER(forward) IPC_STRUCT_TRAITS_MEMBER(matchCase) IPC_STRUCT_TRAITS_MEMBER(findNext) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(WebKit::WebMediaPlayerAction) IPC_STRUCT_TRAITS_MEMBER(type) IPC_STRUCT_TRAITS_MEMBER(enable) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(WebKit::WebRect) IPC_STRUCT_TRAITS_MEMBER(x) IPC_STRUCT_TRAITS_MEMBER(y) IPC_STRUCT_TRAITS_MEMBER(width) IPC_STRUCT_TRAITS_MEMBER(height) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(WebKit::WebScreenInfo) IPC_STRUCT_TRAITS_MEMBER(depth) IPC_STRUCT_TRAITS_MEMBER(depthPerComponent) IPC_STRUCT_TRAITS_MEMBER(isMonochrome) IPC_STRUCT_TRAITS_MEMBER(rect) IPC_STRUCT_TRAITS_MEMBER(availableRect) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(WebPreferences) IPC_STRUCT_TRAITS_MEMBER(standard_font_family) IPC_STRUCT_TRAITS_MEMBER(fixed_font_family) IPC_STRUCT_TRAITS_MEMBER(serif_font_family) IPC_STRUCT_TRAITS_MEMBER(sans_serif_font_family) IPC_STRUCT_TRAITS_MEMBER(cursive_font_family) IPC_STRUCT_TRAITS_MEMBER(fantasy_font_family) IPC_STRUCT_TRAITS_MEMBER(default_font_size) IPC_STRUCT_TRAITS_MEMBER(default_fixed_font_size) IPC_STRUCT_TRAITS_MEMBER(minimum_font_size) IPC_STRUCT_TRAITS_MEMBER(minimum_logical_font_size) IPC_STRUCT_TRAITS_MEMBER(default_encoding) IPC_STRUCT_TRAITS_MEMBER(javascript_enabled) IPC_STRUCT_TRAITS_MEMBER(web_security_enabled) IPC_STRUCT_TRAITS_MEMBER(javascript_can_open_windows_automatically) IPC_STRUCT_TRAITS_MEMBER(loads_images_automatically) IPC_STRUCT_TRAITS_MEMBER(plugins_enabled) IPC_STRUCT_TRAITS_MEMBER(dom_paste_enabled) IPC_STRUCT_TRAITS_MEMBER(developer_extras_enabled) IPC_STRUCT_TRAITS_MEMBER(inspector_settings) IPC_STRUCT_TRAITS_MEMBER(site_specific_quirks_enabled) IPC_STRUCT_TRAITS_MEMBER(shrinks_standalone_images_to_fit) IPC_STRUCT_TRAITS_MEMBER(uses_universal_detector) IPC_STRUCT_TRAITS_MEMBER(text_areas_are_resizable) IPC_STRUCT_TRAITS_MEMBER(java_enabled) IPC_STRUCT_TRAITS_MEMBER(allow_scripts_to_close_windows) IPC_STRUCT_TRAITS_MEMBER(uses_page_cache) IPC_STRUCT_TRAITS_MEMBER(remote_fonts_enabled) IPC_STRUCT_TRAITS_MEMBER(javascript_can_access_clipboard) IPC_STRUCT_TRAITS_MEMBER(xss_auditor_enabled) IPC_STRUCT_TRAITS_MEMBER(local_storage_enabled) IPC_STRUCT_TRAITS_MEMBER(databases_enabled) IPC_STRUCT_TRAITS_MEMBER(application_cache_enabled) IPC_STRUCT_TRAITS_MEMBER(tabs_to_links) IPC_STRUCT_TRAITS_MEMBER(hyperlink_auditing_enabled) IPC_STRUCT_TRAITS_MEMBER(user_style_sheet_enabled) IPC_STRUCT_TRAITS_MEMBER(user_style_sheet_location) IPC_STRUCT_TRAITS_MEMBER(author_and_user_styles_enabled) IPC_STRUCT_TRAITS_MEMBER(frame_flattening_enabled) IPC_STRUCT_TRAITS_MEMBER(allow_universal_access_from_file_urls) IPC_STRUCT_TRAITS_MEMBER(allow_file_access_from_file_urls) IPC_STRUCT_TRAITS_MEMBER(webaudio_enabled) IPC_STRUCT_TRAITS_MEMBER(experimental_webgl_enabled) IPC_STRUCT_TRAITS_MEMBER(gl_multisampling_enabled) IPC_STRUCT_TRAITS_MEMBER(show_composited_layer_borders) IPC_STRUCT_TRAITS_MEMBER(show_composited_layer_tree) IPC_STRUCT_TRAITS_MEMBER(show_fps_counter) IPC_STRUCT_TRAITS_MEMBER(accelerated_compositing_enabled) IPC_STRUCT_TRAITS_MEMBER(force_compositing_mode) IPC_STRUCT_TRAITS_MEMBER(composite_to_texture_enabled) IPC_STRUCT_TRAITS_MEMBER(accelerated_2d_canvas_enabled) IPC_STRUCT_TRAITS_MEMBER(accelerated_drawing_enabled) IPC_STRUCT_TRAITS_MEMBER(accelerated_plugins_enabled) IPC_STRUCT_TRAITS_MEMBER(accelerated_layers_enabled) IPC_STRUCT_TRAITS_MEMBER(accelerated_video_enabled) IPC_STRUCT_TRAITS_MEMBER(memory_info_enabled) IPC_STRUCT_TRAITS_MEMBER(interactive_form_validation_enabled) IPC_STRUCT_TRAITS_MEMBER(fullscreen_enabled) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(WebMenuItem) IPC_STRUCT_TRAITS_MEMBER(label) IPC_STRUCT_TRAITS_MEMBER(type) IPC_STRUCT_TRAITS_MEMBER(action) IPC_STRUCT_TRAITS_MEMBER(rtl) IPC_STRUCT_TRAITS_MEMBER(has_directional_override) IPC_STRUCT_TRAITS_MEMBER(enabled) IPC_STRUCT_TRAITS_MEMBER(checked) IPC_STRUCT_TRAITS_MEMBER(submenu) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(webkit_glue::CustomContextMenuContext) IPC_STRUCT_TRAITS_MEMBER(is_pepper_menu) IPC_STRUCT_TRAITS_MEMBER(request_id) IPC_STRUCT_TRAITS_MEMBER(render_widget_id) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(webkit_glue::WebAccessibility) IPC_STRUCT_TRAITS_MEMBER(id) IPC_STRUCT_TRAITS_MEMBER(name) IPC_STRUCT_TRAITS_MEMBER(value) IPC_STRUCT_TRAITS_MEMBER(role) IPC_STRUCT_TRAITS_MEMBER(state) IPC_STRUCT_TRAITS_MEMBER(location) IPC_STRUCT_TRAITS_MEMBER(attributes) IPC_STRUCT_TRAITS_MEMBER(children) IPC_STRUCT_TRAITS_MEMBER(indirect_child_ids) IPC_STRUCT_TRAITS_MEMBER(html_attributes) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(webkit_glue::WebCookie) IPC_STRUCT_TRAITS_MEMBER(name) IPC_STRUCT_TRAITS_MEMBER(value) IPC_STRUCT_TRAITS_MEMBER(domain) IPC_STRUCT_TRAITS_MEMBER(path) IPC_STRUCT_TRAITS_MEMBER(expires) IPC_STRUCT_TRAITS_MEMBER(http_only) IPC_STRUCT_TRAITS_MEMBER(secure) IPC_STRUCT_TRAITS_MEMBER(session) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(webkit::npapi::WebPluginGeometry) IPC_STRUCT_TRAITS_MEMBER(window) IPC_STRUCT_TRAITS_MEMBER(window_rect) IPC_STRUCT_TRAITS_MEMBER(clip_rect) IPC_STRUCT_TRAITS_MEMBER(cutout_rects) IPC_STRUCT_TRAITS_MEMBER(rects_valid) IPC_STRUCT_TRAITS_MEMBER(visible) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(webkit::npapi::WebPluginMimeType) IPC_STRUCT_TRAITS_MEMBER(mime_type) IPC_STRUCT_TRAITS_MEMBER(file_extensions) IPC_STRUCT_TRAITS_MEMBER(description) IPC_STRUCT_TRAITS_MEMBER(additional_param_names) IPC_STRUCT_TRAITS_MEMBER(additional_param_values) IPC_STRUCT_TRAITS_END() IPC_STRUCT_TRAITS_BEGIN(webkit::npapi::WebPluginInfo) IPC_STRUCT_TRAITS_MEMBER(name) IPC_STRUCT_TRAITS_MEMBER(path) IPC_STRUCT_TRAITS_MEMBER(version) IPC_STRUCT_TRAITS_MEMBER(desc) IPC_STRUCT_TRAITS_MEMBER(mime_types) IPC_STRUCT_TRAITS_MEMBER(enabled) IPC_STRUCT_TRAITS_END() IPC_STRUCT_BEGIN(ViewHostMsg_CreateWindow_Params) // Routing ID of the view initiating the open. IPC_STRUCT_MEMBER(int, opener_id) // True if this open request came in the context of a user gesture. IPC_STRUCT_MEMBER(bool, user_gesture) // Type of window requested. IPC_STRUCT_MEMBER(WindowContainerType, window_container_type) // The session storage namespace ID this view should use. IPC_STRUCT_MEMBER(int64, session_storage_namespace_id) // The name of the resulting frame that should be created (empty if none // has been specified). IPC_STRUCT_MEMBER(string16, frame_name) // The frame identifier of the frame initiating the open. IPC_STRUCT_MEMBER(int64, opener_frame_id) // The URL of the frame initiating the open. IPC_STRUCT_MEMBER(GURL, opener_url) // The security origin of the frame initiating the open. IPC_STRUCT_MEMBER(std::string, opener_security_origin) // The URL that will be loaded in the new window (empty if none has been // sepcified). IPC_STRUCT_MEMBER(GURL, target_url) IPC_STRUCT_END() IPC_STRUCT_BEGIN(ViewHostMsg_CreateWorker_Params) // URL for the worker script. IPC_STRUCT_MEMBER(GURL, url) // True if this is a SharedWorker, false if it is a dedicated Worker. IPC_STRUCT_MEMBER(bool, is_shared) // Name for a SharedWorker, otherwise empty string. IPC_STRUCT_MEMBER(string16, name) // The ID of the parent document (unique within parent renderer). IPC_STRUCT_MEMBER(unsigned long long, document_id) // RenderView routing id used to send messages back to the parent. IPC_STRUCT_MEMBER(int, render_view_route_id) // The route ID to associate with the worker. If MSG_ROUTING_NONE is passed, // a new unique ID is created and assigned to the worker. IPC_STRUCT_MEMBER(int, route_id) // The ID of the parent's appcache host, only valid for dedicated workers. IPC_STRUCT_MEMBER(int, parent_appcache_host_id) // The ID of the appcache the main shared worker script resource was loaded // from, only valid for shared workers. IPC_STRUCT_MEMBER(int64, script_resource_appcache_id) IPC_STRUCT_END() // Parameters structure for ViewHostMsg_FrameNavigate, which has too many data // parameters to be reasonably put in a predefined IPC message. IPC_STRUCT_BEGIN(ViewHostMsg_FrameNavigate_Params) // Page ID of this navigation. The renderer creates a new unique page ID // anytime a new session history entry is created. This means you'll get new // page IDs for user actions, and the old page IDs will be reloaded when // iframes are loaded automatically. IPC_STRUCT_MEMBER(int32, page_id) // The frame ID for this navigation. The frame ID uniquely identifies the // frame the navigation happened in for a given renderer. IPC_STRUCT_MEMBER(int64, frame_id) // URL of the page being loaded. IPC_STRUCT_MEMBER(GURL, url) // URL of the referrer of this load. WebKit generates this based on the // source of the event that caused the load. IPC_STRUCT_MEMBER(GURL, referrer) // The type of transition. IPC_STRUCT_MEMBER(PageTransition::Type, transition) // Lists the redirects that occurred on the way to the current page. This // vector has the same format as reported by the WebDataSource in the glue, // with the current page being the last one in the list (so even when // there's no redirect, there will be one entry in the list. IPC_STRUCT_MEMBER(std::vector<GURL>, redirects) // Set to false if we want to update the session history but not update // the browser history. E.g., on unreachable urls. IPC_STRUCT_MEMBER(bool, should_update_history) // See SearchableFormData for a description of these. IPC_STRUCT_MEMBER(GURL, searchable_form_url) IPC_STRUCT_MEMBER(std::string, searchable_form_encoding) // See password_form.h. IPC_STRUCT_MEMBER(webkit_glue::PasswordForm, password_form) // Information regarding the security of the connection (empty if the // connection was not secure). IPC_STRUCT_MEMBER(std::string, security_info) // The gesture that initiated this navigation. IPC_STRUCT_MEMBER(NavigationGesture, gesture) // Contents MIME type of main frame. IPC_STRUCT_MEMBER(std::string, contents_mime_type) // True if this was a post request. IPC_STRUCT_MEMBER(bool, is_post) // Whether the frame navigation resulted in no change to the documents within // the page. For example, the navigation may have just resulted in scrolling // to a named anchor. IPC_STRUCT_MEMBER(bool, was_within_same_page) // The status code of the HTTP request. IPC_STRUCT_MEMBER(int, http_status_code) // Remote address of the socket which fetched this resource. IPC_STRUCT_MEMBER(net::HostPortPair, socket_address) // True if the connection was proxied. In this case, socket_address // will represent the address of the proxy, rather than the remote host. IPC_STRUCT_MEMBER(bool, was_fetched_via_proxy) // Serialized history item state to store in the navigation entry. IPC_STRUCT_MEMBER(std::string, content_state) IPC_STRUCT_END() IPC_STRUCT_BEGIN(ViewHostMsg_AccessibilityNotification_Params) // Type of notification. IPC_STRUCT_MEMBER(ViewHostMsg_AccessibilityNotification_Type::Value, notification_type) // The accessibility node tree. IPC_STRUCT_MEMBER(webkit_glue::WebAccessibility, acc_obj) IPC_STRUCT_END() IPC_STRUCT_BEGIN(ViewHostMsg_RunFileChooser_Params) IPC_STRUCT_MEMBER(ViewHostMsg_RunFileChooser_Mode::Value, mode) // Title to be used for the dialog. This may be empty for the default title, // which will be either "Open" or "Save" depending on the mode. IPC_STRUCT_MEMBER(string16, title) // Default file name to select in the dialog. IPC_STRUCT_MEMBER(FilePath, default_file_name) // A comma-separated MIME types such as "audio/*,text/plain", that is used // to restrict selectable files to such types. IPC_STRUCT_MEMBER(string16, accept_types) IPC_STRUCT_END() // This message is used for supporting popup menus on Mac OS X using native // Cocoa controls. The renderer sends us this message which we use to populate // the popup menu. IPC_STRUCT_BEGIN(ViewHostMsg_ShowPopup_Params) // Position on the screen. IPC_STRUCT_MEMBER(gfx::Rect, bounds) // The height of each item in the menu. IPC_STRUCT_MEMBER(int, item_height) // The size of the font to use for those items. IPC_STRUCT_MEMBER(double, item_font_size) // The currently selected (displayed) item in the menu. IPC_STRUCT_MEMBER(int, selected_item) // The entire list of items in the popup menu. IPC_STRUCT_MEMBER(std::vector<WebMenuItem>, popup_items) // Whether items should be right-aligned. IPC_STRUCT_MEMBER(bool, right_aligned) IPC_STRUCT_END() IPC_STRUCT_BEGIN(ViewHostMsg_UpdateRect_Params) // The bitmap to be painted into the view at the locations specified by // update_rects. IPC_STRUCT_MEMBER(TransportDIB::Id, bitmap) // The position and size of the bitmap. IPC_STRUCT_MEMBER(gfx::Rect, bitmap_rect) // The scroll offset. Only one of these can be non-zero, and if they are // both zero, then it means there is no scrolling and the scroll_rect is // ignored. IPC_STRUCT_MEMBER(int, dx) IPC_STRUCT_MEMBER(int, dy) // The rectangular region to scroll. IPC_STRUCT_MEMBER(gfx::Rect, scroll_rect) // The scroll offset of the render view. IPC_STRUCT_MEMBER(gfx::Point, scroll_offset) // The regions of the bitmap (in view coords) that contain updated pixels. // In the case of scrolling, this includes the scroll damage rect. IPC_STRUCT_MEMBER(std::vector<gfx::Rect>, copy_rects) // The size of the RenderView when this message was generated. This is // included so the host knows how large the view is from the perspective of // the renderer process. This is necessary in case a resize operation is in // progress. IPC_STRUCT_MEMBER(gfx::Size, view_size) // The area of the RenderView reserved for resize corner when this message // was generated. Reported for the same reason as view_size is. IPC_STRUCT_MEMBER(gfx::Rect, resizer_rect) // New window locations for plugin child windows. IPC_STRUCT_MEMBER(std::vector<webkit::npapi::WebPluginGeometry>, plugin_window_moves) // The following describes the various bits that may be set in flags: // // ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK // Indicates that this is a response to a ViewMsg_Resize message. // // ViewHostMsg_UpdateRect_Flags::IS_RESTORE_ACK // Indicates that this is a response to a ViewMsg_WasRestored message. // // ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK // Indicates that this is a response to a ViewMsg_Repaint message. // // If flags is zero, then this message corresponds to an unsoliticed paint // request by the render view. Any of the above bits may be set in flags, // which would indicate that this paint message is an ACK for multiple // request messages. IPC_STRUCT_MEMBER(int, flags) IPC_STRUCT_END() IPC_STRUCT_BEGIN(ViewMsg_ClosePage_Params) // The identifier of the RenderProcessHost for the currently closing view. // // These first two parameters are technically redundant since they are // needed only when processing the ACK message, and the processor // theoretically knows both the process and route ID. However, this is // difficult to figure out with our current implementation, so this // information is duplicate here. IPC_STRUCT_MEMBER(int, closing_process_id) // The route identifier for the currently closing RenderView. IPC_STRUCT_MEMBER(int, closing_route_id) // True when this close is for the first (closing) tab of a cross-site // transition where we switch processes. False indicates the close is for the // entire tab. // // When true, the new_* variables below must be filled in. Otherwise they must // both be -1. IPC_STRUCT_MEMBER(bool, for_cross_site_transition) // The identifier of the RenderProcessHost for the new view attempting to // replace the closing one above. This must be valid when // for_cross_site_transition is set, and must be -1 otherwise. IPC_STRUCT_MEMBER(int, new_render_process_host_id) // The identifier of the *request* the new view made that is causing the // cross-site transition. This is *not* a route_id, but the request that we // will resume once the ACK from the closing view has been received. This // must be valid when for_cross_site_transition is set, and must be -1 // otherwise. IPC_STRUCT_MEMBER(int, new_request_id) IPC_STRUCT_END() IPC_STRUCT_BEGIN(ViewMsg_Navigate_Params) // The page_id for this navigation, or -1 if it is a new navigation. Back, // Forward, and Reload navigations should have a valid page_id. If the load // succeeds, then this page_id will be reflected in the resultant // ViewHostMsg_FrameNavigate message. IPC_STRUCT_MEMBER(int32, page_id) // If page_id is -1, then pending_history_list_offset will also be -1. // Otherwise, it contains the offset into the history list corresponding to // the current navigation. IPC_STRUCT_MEMBER(int, pending_history_list_offset) // Informs the RenderView of where its current page contents reside in // session history and the total size of the session history list. IPC_STRUCT_MEMBER(int, current_history_list_offset) IPC_STRUCT_MEMBER(int, current_history_list_length) // The URL to load. IPC_STRUCT_MEMBER(GURL, url) // The URL to send in the "Referer" header field. Can be empty if there is // no referrer. // TODO: consider folding this into extra_headers. IPC_STRUCT_MEMBER(GURL, referrer) // The type of transition. IPC_STRUCT_MEMBER(PageTransition::Type, transition) // Opaque history state (received by ViewHostMsg_UpdateState). IPC_STRUCT_MEMBER(std::string, state) // Type of navigation. IPC_STRUCT_MEMBER(ViewMsg_Navigate_Type::Value, navigation_type) // The time the request was created IPC_STRUCT_MEMBER(base::Time, request_time) // Extra headers (separated by \n) to send during the request. IPC_STRUCT_MEMBER(std::string, extra_headers) IPC_STRUCT_END() IPC_STRUCT_BEGIN(ViewMsg_New_Params) // The parent window's id. IPC_STRUCT_MEMBER(gfx::NativeViewId, parent_window) // Surface for accelerated rendering. IPC_STRUCT_MEMBER(gfx::PluginWindowHandle, compositing_surface) // Renderer-wide preferences. IPC_STRUCT_MEMBER(RendererPreferences, renderer_preferences) // Preferences for this view. IPC_STRUCT_MEMBER(WebPreferences, web_preferences) // The ID of the view to be created. IPC_STRUCT_MEMBER(int32, view_id) // The session storage namespace ID this view should use. IPC_STRUCT_MEMBER(int64, session_storage_namespace_id) // The name of the frame associated with this view (or empty if none). IPC_STRUCT_MEMBER(string16, frame_name) IPC_STRUCT_END() // Messages sent from the browser to the renderer. // Used typically when recovering from a crash. The new rendering process // sets its global "next page id" counter to the given value. IPC_MESSAGE_CONTROL1(ViewMsg_SetNextPageID, int32 /* next_page_id */) // Sends System Colors corresponding to a set of CSS color keywords // down the pipe. // This message must be sent to the renderer immediately on launch // before creating any new views. // The message can also be sent during a renderer's lifetime if system colors // are updated. // TODO(jeremy): Possibly change IPC format once we have this all hooked up. IPC_MESSAGE_ROUTED1(ViewMsg_SetCSSColors, std::vector<CSSColors::CSSColorMapping>) // Asks the browser for a unique routing ID. IPC_SYNC_MESSAGE_CONTROL0_1(ViewHostMsg_GenerateRoutingID, int /* routing_id */) // Tells the renderer to create a new view. // This message is slightly different, the view it takes (via // ViewMsg_New_Params) is the view to create, the message itself is sent as a // non-view control message. IPC_MESSAGE_CONTROL1(ViewMsg_New, ViewMsg_New_Params) // Reply in response to ViewHostMsg_ShowView or ViewHostMsg_ShowWidget. // similar to the new command, but used when the renderer created a view // first, and we need to update it. IPC_MESSAGE_ROUTED2(ViewMsg_CreatingNew_ACK, gfx::NativeViewId /* parent_hwnd */, gfx::PluginWindowHandle /* compositing_surface */) // Sends updated preferences to the renderer. IPC_MESSAGE_ROUTED1(ViewMsg_SetRendererPrefs, RendererPreferences) // This passes a set of webkit preferences down to the renderer. IPC_MESSAGE_ROUTED1(ViewMsg_UpdateWebPreferences, WebPreferences) // Tells the render view to close. IPC_MESSAGE_ROUTED0(ViewMsg_Close) // Tells the render view to change its size. A ViewHostMsg_PaintRect message // is generated in response provided new_size is not empty and not equal to // the view's current size. The generated ViewHostMsg_PaintRect message will // have the IS_RESIZE_ACK flag set. It also receives the resizer rect so that // we don't have to fetch it every time WebKit asks for it. IPC_MESSAGE_ROUTED2(ViewMsg_Resize, gfx::Size /* new_size */, gfx::Rect /* resizer_rect */) // Sent to inform the view that it was hidden. This allows it to reduce its // resource utilization. IPC_MESSAGE_ROUTED0(ViewMsg_WasHidden) // Tells the render view that it is no longer hidden (see WasHidden), and the // render view is expected to respond with a full repaint if needs_repainting // is true. In that case, the generated ViewHostMsg_PaintRect message will // have the IS_RESTORE_ACK flag set. If needs_repainting is false, then this // message does not trigger a message in response. IPC_MESSAGE_ROUTED1(ViewMsg_WasRestored, bool /* needs_repainting */) // Sent to render the view into the supplied transport DIB, resize // the web widget to match the |page_size|, scale it by the // appropriate scale to make it fit the |desired_size|, and return // it. In response to this message, the host generates a // ViewHostMsg_PaintAtSize_ACK message. Note that the DIB *must* be // the right size to receive an RGBA image at the |desired_size|. // |tag| is sent along with ViewHostMsg_PaintAtSize_ACK unmodified to // identify the PaintAtSize message the ACK belongs to. IPC_MESSAGE_ROUTED4(ViewMsg_PaintAtSize, TransportDIB::Handle /* dib_handle */, int /* tag */, gfx::Size /* page_size */, gfx::Size /* desired_size */) // Tells the render view that a ViewHostMsg_UpdateRect message was processed. // This signals the render view that it can send another UpdateRect message. IPC_MESSAGE_ROUTED0(ViewMsg_UpdateRect_ACK) // Message payload includes: // 1. A blob that should be cast to WebInputEvent // 2. An optional boolean value indicating if a RawKeyDown event is associated // to a keyboard shortcut of the browser. IPC_MESSAGE_ROUTED0(ViewMsg_HandleInputEvent) // This message notifies the renderer that the next key event is bound to one // or more pre-defined edit commands. If the next key event is not handled // by webkit, the specified edit commands shall be executed against current // focused frame. // Parameters // * edit_commands (see chrome/common/edit_command_types.h) // Contains one or more edit commands. // See third_party/WebKit/Source/WebCore/editing/EditorCommand.cpp for detailed // definition of webkit edit commands. // // This message must be sent just before sending a key event. IPC_MESSAGE_ROUTED1(ViewMsg_SetEditCommandsForNextKeyEvent, std::vector<EditCommand> /* edit_commands */) // Message payload is the name/value of a WebCore edit command to execute. IPC_MESSAGE_ROUTED2(ViewMsg_ExecuteEditCommand, std::string, /* name */ std::string /* value */) IPC_MESSAGE_ROUTED0(ViewMsg_MouseCaptureLost) // TODO(darin): figure out how this meshes with RestoreFocus IPC_MESSAGE_ROUTED1(ViewMsg_SetFocus, bool /* enable */) // Tells the renderer to focus the first (last if reverse is true) focusable // node. IPC_MESSAGE_ROUTED1(ViewMsg_SetInitialFocus, bool /* reverse */) // Tells the renderer to scroll the currently focused node into view only if // the currently focused node is a Text node (textfield, text area or content // editable divs). IPC_MESSAGE_ROUTED0(ViewMsg_ScrollFocusedEditableNodeIntoView) // Executes custom context menu action that was provided from WebKit. IPC_MESSAGE_ROUTED2(ViewMsg_CustomContextMenuAction, webkit_glue::CustomContextMenuContext /* custom_context */, unsigned /* action */) // Sent in response to a ViewHostMsg_ContextMenu to let the renderer know that // the menu has been closed. IPC_MESSAGE_ROUTED1(ViewMsg_ContextMenuClosed, webkit_glue::CustomContextMenuContext /* custom_context */) // Tells the renderer to perform the specified navigation, interrupting any // existing navigation. IPC_MESSAGE_ROUTED1(ViewMsg_Navigate, ViewMsg_Navigate_Params) IPC_MESSAGE_ROUTED0(ViewMsg_Stop) // Tells the renderer to reload the current focused frame IPC_MESSAGE_ROUTED0(ViewMsg_ReloadFrame) // Sent when the user wants to search for a word on the page (find in page). IPC_MESSAGE_ROUTED3(ViewMsg_Find, int /* request_id */, string16 /* search_text */, WebKit::WebFindOptions) // This message notifies the renderer that the user has closed the FindInPage // window (and what action to take regarding the selection). IPC_MESSAGE_ROUTED1(ViewMsg_StopFinding, ViewMsg_StopFinding_Params /* action */) // Used to notify the render-view that the browser has received a reply for // the Find operation and is interested in receiving the next one. This is // used to prevent the renderer from spamming the browser process with // results. IPC_MESSAGE_ROUTED0(ViewMsg_FindReplyACK) // These messages are typically generated from context menus and request the // renderer to apply the specified operation to the current selection. IPC_MESSAGE_ROUTED0(ViewMsg_Undo) IPC_MESSAGE_ROUTED0(ViewMsg_Redo) IPC_MESSAGE_ROUTED0(ViewMsg_Cut) IPC_MESSAGE_ROUTED0(ViewMsg_Copy) #if defined(OS_MACOSX) IPC_MESSAGE_ROUTED0(ViewMsg_CopyToFindPboard) #endif IPC_MESSAGE_ROUTED0(ViewMsg_Paste) // Replaces the selected region or a word around the cursor with the // specified string. IPC_MESSAGE_ROUTED1(ViewMsg_Replace, string16) IPC_MESSAGE_ROUTED0(ViewMsg_Delete) IPC_MESSAGE_ROUTED0(ViewMsg_SelectAll) // Copies the image at location x, y to the clipboard (if there indeed is an // image at that location). IPC_MESSAGE_ROUTED2(ViewMsg_CopyImageAt, int /* x */, int /* y */) // Tells the renderer to perform the given action on the media player // located at the given point. IPC_MESSAGE_ROUTED2(ViewMsg_MediaPlayerActionAt, gfx::Point, /* location */ WebKit::WebMediaPlayerAction) // Request for the renderer to evaluate an xpath to a frame and execute a // javascript: url in that frame's context. The message is completely // asynchronous and no corresponding response message is sent back. // // frame_xpath contains the modified xpath notation to identify an inner // subframe (starting from the root frame). It is a concatenation of // number of smaller xpaths delimited by '\n'. Each chunk in the string can // be evaluated to a frame in its parent-frame's context. // // Example: /html/body/iframe/\n/html/body/div/iframe/\n/frameset/frame[0] // can be broken into 3 xpaths // /html/body/iframe evaluates to an iframe within the root frame // /html/body/div/iframe evaluates to an iframe within the level-1 iframe // /frameset/frame[0] evaluates to first frame within the level-2 iframe // // jscript_url is the string containing the javascript: url to be executed // in the target frame's context. The string should start with "javascript:" // and continue with a valid JS text. // // If the fourth parameter is true the result is sent back to the renderer // using the message ViewHostMsg_ScriptEvalResponse. // ViewHostMsg_ScriptEvalResponse is passed the ID parameter so that the // client can uniquely identify the request. IPC_MESSAGE_ROUTED4(ViewMsg_ScriptEvalRequest, string16, /* frame_xpath */ string16, /* jscript_url */ int, /* ID */ bool /* If true, result is sent back. */) // Request for the renderer to evaluate an xpath to a frame and insert css // into that frame's document. See ViewMsg_ScriptEvalRequest for details on // allowed xpath expressions. IPC_MESSAGE_ROUTED3(ViewMsg_CSSInsertRequest, std::wstring, /* frame_xpath */ std::string, /* css string */ std::string /* element id */) // External popup menus. IPC_MESSAGE_ROUTED1(ViewMsg_SelectPopupMenuItem, int /* selected index, -1 means no selection */) // Change the zoom level for the current main frame. If the level actually // changes, a ViewHostMsg_DidZoomURL message will be sent back to the browser // telling it what url got zoomed and what its current zoom level is. IPC_MESSAGE_ROUTED1(ViewMsg_Zoom, PageZoom::Function /* function */) // Set the zoom level for the current main frame. If the level actually // changes, a ViewHostMsg_DidZoomURL message will be sent back to the browser // telling it what url got zoomed and what its current zoom level is. IPC_MESSAGE_ROUTED1(ViewMsg_SetZoomLevel, double /* zoom_level */) // Set the zoom level for a particular url that the renderer is in the // process of loading. This will be stored, to be used if the load commits // and ignored otherwise. IPC_MESSAGE_ROUTED2(ViewMsg_SetZoomLevelForLoadingURL, GURL /* url */, double /* zoom_level */) // Set the zoom level for a particular url, so all render views // displaying this url can update their zoom levels to match. IPC_MESSAGE_CONTROL2(ViewMsg_SetZoomLevelForCurrentURL, GURL /* url */, double /* zoom_level */) // Change encoding of page in the renderer. IPC_MESSAGE_ROUTED1(ViewMsg_SetPageEncoding, std::string /*new encoding name*/) // Reset encoding of page in the renderer back to default. IPC_MESSAGE_ROUTED0(ViewMsg_ResetPageEncodingToDefault) // Requests the renderer to reserve a range of page ids. IPC_MESSAGE_ROUTED1(ViewMsg_ReservePageIDRange, int /* size_of_range */) // Used to tell a render view whether it should expose various bindings // that allow JS content extended privileges. See BindingsPolicy for valid // flag values. IPC_MESSAGE_ROUTED1(ViewMsg_AllowBindings, int /* enabled_bindings_flags */) // Tell the renderer to add a property to the WebUI binding object. This // only works if we allowed WebUI bindings. IPC_MESSAGE_ROUTED2(ViewMsg_SetWebUIProperty, std::string /* property_name */, std::string /* property_value_json */) // This message starts/stop monitoring the input method status of the focused // edit control of a renderer process. // Parameters // * is_active (bool) // Indicates if an input method is active in the browser process. // The possible actions when a renderer process receives this message are // listed below: // Value Action // true Start sending IPC message ViewHostMsg_ImeUpdateTextInputState // to notify the input method status of the focused edit control. // false Stop sending IPC message ViewHostMsg_ImeUpdateTextInputState. IPC_MESSAGE_ROUTED1(ViewMsg_SetInputMethodActive, bool /* is_active */) // This message sends a string being composed with an input method. IPC_MESSAGE_ROUTED4( ViewMsg_ImeSetComposition, string16, /* text */ std::vector<WebKit::WebCompositionUnderline>, /* underlines */ int, /* selectiont_start */ int /* selection_end */) // This message confirms an ongoing composition. IPC_MESSAGE_ROUTED1(ViewMsg_ImeConfirmComposition, string16 /* text */) // Used to notify the render-view that we have received a target URL. Used // to prevent target URLs spamming the browser. IPC_MESSAGE_ROUTED0(ViewMsg_UpdateTargetURL_ACK) // Sets the alternate error page URL (link doctor) for the renderer process. IPC_MESSAGE_ROUTED1(ViewMsg_SetAltErrorPageURL, GURL) IPC_MESSAGE_ROUTED1(ViewMsg_RunFileChooserResponse, std::vector<FilePath> /* selected files */) // Provides the results of directory enumeration. IPC_MESSAGE_ROUTED2(ViewMsg_EnumerateDirectoryResponse, int /* request_id */, std::vector<FilePath> /* files_in_directory */) // When a renderer sends a ViewHostMsg_Focus to the browser process, // the browser has the option of sending a ViewMsg_CantFocus back to // the renderer. IPC_MESSAGE_ROUTED0(ViewMsg_CantFocus) // Instructs the renderer to invoke the frame's shouldClose method, which // runs the onbeforeunload event handler. Expects the result to be returned // via ViewHostMsg_ShouldClose. IPC_MESSAGE_ROUTED0(ViewMsg_ShouldClose) // Instructs the renderer to close the current page, including running the // onunload event handler. See the struct in render_messages.h for more. // // Expects a ClosePage_ACK message when finished, where the parameters are // echoed back. IPC_MESSAGE_ROUTED1(ViewMsg_ClosePage, ViewMsg_ClosePage_Params) // Notifies the renderer about ui theme changes IPC_MESSAGE_ROUTED0(ViewMsg_ThemeChanged) // Notifies the renderer that a paint is to be generated for the rectangle // passed in. IPC_MESSAGE_ROUTED1(ViewMsg_Repaint, gfx::Size /* The view size to be repainted */) // Notification that a move or resize renderer's containing window has // started. IPC_MESSAGE_ROUTED0(ViewMsg_MoveOrResizeStarted) // Reply to ViewHostMsg_RequestMove, ViewHostMsg_ShowView, and // ViewHostMsg_ShowWidget to inform the renderer that the browser has // processed the move. The browser may have ignored the move, but it finished // processing. This is used because the renderer keeps a temporary cache of // the widget position while these asynchronous operations are in progress. IPC_MESSAGE_ROUTED0(ViewMsg_Move_ACK) // Used to instruct the RenderView to send back updates to the preferred size. IPC_MESSAGE_ROUTED1(ViewMsg_EnablePreferredSizeChangedMode, int /*flags*/) // Changes the text direction of the currently selected input field (if any). IPC_MESSAGE_ROUTED1(ViewMsg_SetTextDirection, WebKit::WebTextDirection /* direction */) // Tells the renderer to clear the focused node (if any). IPC_MESSAGE_ROUTED0(ViewMsg_ClearFocusedNode) // Make the RenderView transparent and render it onto a custom background. The // background will be tiled in both directions if it is not large enough. IPC_MESSAGE_ROUTED1(ViewMsg_SetBackground, SkBitmap /* background */) // Used to tell the renderer not to add scrollbars with height and // width below a threshold. IPC_MESSAGE_ROUTED1(ViewMsg_DisableScrollbarsForSmallWindows, gfx::Size /* disable_scrollbar_size_limit */) // Activate/deactivate the RenderView (i.e., set its controls' tint // accordingly, etc.). IPC_MESSAGE_ROUTED1(ViewMsg_SetActive, bool /* active */) #if defined(OS_MACOSX) // Let the RenderView know its window has changed visibility. IPC_MESSAGE_ROUTED1(ViewMsg_SetWindowVisibility, bool /* visibile */) // Let the RenderView know its window's frame has changed. IPC_MESSAGE_ROUTED2(ViewMsg_WindowFrameChanged, gfx::Rect /* window frame */, gfx::Rect /* content view frame */) // Tell the renderer that plugin IME has completed. IPC_MESSAGE_ROUTED2(ViewMsg_PluginImeCompositionCompleted, string16 /* text */, int /* plugin_id */) #endif // Response message to ViewHostMsg_CreateShared/DedicatedWorker. // Sent when the worker has started. IPC_MESSAGE_ROUTED0(ViewMsg_WorkerCreated) // The response to ViewHostMsg_AsyncOpenFile. IPC_MESSAGE_ROUTED3(ViewMsg_AsyncOpenFile_ACK, base::PlatformFileError /* error_code */, IPC::PlatformFileForTransit /* file descriptor */, int /* message_id */) // Tells the renderer that the network state has changed and that // window.navigator.onLine should be updated for all WebViews. IPC_MESSAGE_ROUTED1(ViewMsg_NetworkStateChanged, bool /* online */) // Enable accessibility in the renderer process. IPC_MESSAGE_ROUTED0(ViewMsg_EnableAccessibility) // Relay a request from assistive technology to set focus to a given node. IPC_MESSAGE_ROUTED1(ViewMsg_SetAccessibilityFocus, int /* object id */) // Relay a request from assistive technology to perform the default action // on a given node. IPC_MESSAGE_ROUTED1(ViewMsg_AccessibilityDoDefaultAction, int /* object id */) // Tells the render view that a ViewHostMsg_AccessibilityNotifications // message was processed and it can send addition notifications. IPC_MESSAGE_ROUTED0(ViewMsg_AccessibilityNotifications_ACK) // Reply to ViewHostMsg_OpenChannelToPpapiBroker // Tells the renderer that the channel to the broker has been created. IPC_MESSAGE_ROUTED3(ViewMsg_PpapiBrokerChannelCreated, int /* request_id */, base::ProcessHandle /* broker_process_handle */, IPC::ChannelHandle /* handle */) // Tells the renderer to empty its plugin list cache, optional reloading // pages containing plugins. IPC_MESSAGE_CONTROL1(ViewMsg_PurgePluginListCache, bool /* reload_pages */) // Install the first missing pluign. IPC_MESSAGE_ROUTED0(ViewMsg_InstallMissingPlugin) // Sent to the renderer when a popup window should no longer count against // the current popup count (either because it's not a popup or because it was // a generated by a user action or because a constrained popup got turned // into a full window). IPC_MESSAGE_ROUTED0(ViewMsg_DisassociateFromPopupCount) // Tells the render view a prerendered page is about to be displayed. IPC_MESSAGE_ROUTED0(ViewMsg_DisplayPrerenderedPage) #if defined(PLUGIN_DIRECT_RENDERING) IPC_MESSAGE_ROUTED2(ViewMsg_DidPaintPluginWidget, unsigned int /* plugin id */, unsigned int /* ack */) #endif // Messages sent from the renderer to the browser. // Sent by the renderer when it is creating a new window. The browser creates // a tab for it and responds with a ViewMsg_CreatingNew_ACK. If route_id is // MSG_ROUTING_NONE, the view couldn't be created. IPC_SYNC_MESSAGE_CONTROL1_2(ViewHostMsg_CreateWindow, ViewHostMsg_CreateWindow_Params, int /* route_id */, int64 /* cloned_session_storage_namespace_id */) // Similar to ViewHostMsg_CreateWindow, except used for sub-widgets, like // <select> dropdowns. This message is sent to the TabContents that // contains the widget being created. IPC_SYNC_MESSAGE_CONTROL2_1(ViewHostMsg_CreateWidget, int /* opener_id */, WebKit::WebPopupType /* popup type */, int /* route_id */) // Similar to ViewHostMsg_CreateWidget except the widget is a full screen // window. IPC_SYNC_MESSAGE_CONTROL1_1(ViewHostMsg_CreateFullscreenWidget, int /* opener_id */, int /* route_id */) // These three messages are sent to the parent RenderViewHost to display the // page/widget that was created by // CreateWindow/CreateWidget/CreateFullscreenWidget. routing_id // refers to the id that was returned from the Create message above. // The initial_position parameter is a rectangle in screen coordinates. // // FUTURE: there will probably be flags here to control if the result is // in a new window. IPC_MESSAGE_ROUTED4(ViewHostMsg_ShowView, int /* route_id */, WindowOpenDisposition /* disposition */, gfx::Rect /* initial_pos */, bool /* opened_by_user_gesture */) IPC_MESSAGE_ROUTED2(ViewHostMsg_ShowWidget, int /* route_id */, gfx::Rect /* initial_pos */) // Message to show a full screen widget. IPC_MESSAGE_ROUTED1(ViewHostMsg_ShowFullscreenWidget, int /* route_id */) // This message is sent after ViewHostMsg_ShowView to cause the RenderView // to run in a modal fashion until it is closed. IPC_SYNC_MESSAGE_ROUTED0_0(ViewHostMsg_RunModal) // Indicates the renderer is ready in response to a ViewMsg_New or // a ViewMsg_CreatingNew_ACK. IPC_MESSAGE_ROUTED0(ViewHostMsg_RenderViewReady) // Indicates the renderer process is gone. This actually is sent by the // browser process to itself, but keeps the interface cleaner. IPC_MESSAGE_ROUTED2(ViewHostMsg_RenderViewGone, int, /* this really is base::TerminationStatus */ int /* exit_code */) // Sent by the renderer process to request that the browser close the view. // This corresponds to the window.close() API, and the browser may ignore // this message. Otherwise, the browser will generates a ViewMsg_Close // message to close the view. IPC_MESSAGE_ROUTED0(ViewHostMsg_Close) // Sent by the renderer process to request that the browser move the view. // This corresponds to the window.resizeTo() and window.moveTo() APIs, and // the browser may ignore this message. IPC_MESSAGE_ROUTED1(ViewHostMsg_RequestMove, gfx::Rect /* position */) // Notifies the browser that a frame in the view has changed. This message // has a lot of parameters and is packed/unpacked by functions defined in // render_messages.h. IPC_MESSAGE_ROUTED1(ViewHostMsg_FrameNavigate, ViewHostMsg_FrameNavigate_Params) // Used to tell the parent that the user right clicked on an area of the // content area, and a context menu should be shown for it. The params // object contains information about the node(s) that were selected when the // user right clicked. IPC_MESSAGE_ROUTED1(ViewHostMsg_ContextMenu, ContextMenuParams) // Message to show a popup menu using native cocoa controls (Mac only). IPC_MESSAGE_ROUTED1(ViewHostMsg_ShowPopup, ViewHostMsg_ShowPopup_Params) // Response from ViewMsg_ScriptEvalRequest. The ID is the parameter supplied // to ViewMsg_ScriptEvalRequest. The result has the value returned by the // script as it's only element, one of Null, Boolean, Integer, Real, Date, or // String. IPC_MESSAGE_ROUTED2(ViewHostMsg_ScriptEvalResponse, int /* id */, ListValue /* result */) // Sent by the renderer process to acknowledge receipt of a // ViewMsg_CSSInsertRequest message and css has been inserted into the frame. IPC_MESSAGE_ROUTED0(ViewHostMsg_OnCSSInserted) // Result of string search in the page. // Response to ViewMsg_Find with the results of the requested find-in-page // search, the number of matches found and the selection rect (in screen // coordinates) for the string found. If |final_update| is false, it signals // that this is not the last Find_Reply message - more will be sent as the // scoping effort continues. IPC_MESSAGE_ROUTED5(ViewHostMsg_Find_Reply, int /* request_id */, int /* number of matches */, gfx::Rect /* selection_rect */, int /* active_match_ordinal */, bool /* final_update */) // Provides the result from running OnMsgShouldClose. |proceed| matches the // return value of the the frame's shouldClose method (which includes the // onbeforeunload handler): true if the user decided to proceed with leaving // the page. IPC_MESSAGE_ROUTED1(ViewHostMsg_ShouldClose_ACK, bool /* proceed */) // Indicates that the current page has been closed, after a ClosePage // message. The parameters are just echoed from the ClosePage request. IPC_MESSAGE_ROUTED1(ViewHostMsg_ClosePage_ACK, ViewMsg_ClosePage_Params) // Notifies the browser that we have session history information. // page_id: unique ID that allows us to distinguish between history entries. IPC_MESSAGE_ROUTED2(ViewHostMsg_UpdateState, int32 /* page_id */, std::string /* state */) // Notifies the browser that a document has been loaded in a frame. IPC_MESSAGE_ROUTED1(ViewHostMsg_DocumentLoadedInFrame, int64 /* frame_id */) // Notifies the browser that a frame finished loading. IPC_MESSAGE_ROUTED1(ViewHostMsg_DidFinishLoad, int64 /* frame_id */) // Changes the title for the page in the UI when the page is navigated or the // title changes. // TODO(darin): use a UTF-8 string to reduce data size IPC_MESSAGE_ROUTED2(ViewHostMsg_UpdateTitle, int32, std::wstring) // Changes the icon url for the page in the UI. IPC_MESSAGE_ROUTED2(ViewHostMsg_UpdateIconURL, int32, GURL) // Change the encoding name of the page in UI when the page has detected // proper encoding name. IPC_MESSAGE_ROUTED1(ViewHostMsg_UpdateEncoding, std::string /* new encoding name */) // Notifies the browser that we want to show a destination url for a potential // action (e.g. when the user is hovering over a link). IPC_MESSAGE_ROUTED2(ViewHostMsg_UpdateTargetURL, int32, GURL) // Sent when the renderer starts loading the page. This corresponds to // WebKit's notion of the throbber starting. Note that sometimes you may get // duplicates of these during a single load. IPC_MESSAGE_ROUTED0(ViewHostMsg_DidStartLoading) // Sent when the renderer is done loading a page. This corresponds to WebKit's // notion of the throbber stopping. IPC_MESSAGE_ROUTED0(ViewHostMsg_DidStopLoading) // Sent when the renderer main frame has made progress loading. IPC_MESSAGE_ROUTED1(ViewHostMsg_DidChangeLoadProgress, double /* load_progress */) // Sent when the document element is available for the toplevel frame. This // happens after the page starts loading, but before all resources are // finished. IPC_MESSAGE_ROUTED0(ViewHostMsg_DocumentAvailableInMainFrame) // Sent when after the onload handler has been invoked for the document // in the toplevel frame. IPC_MESSAGE_ROUTED1(ViewHostMsg_DocumentOnLoadCompletedInMainFrame, int32 /* page_id */) // Sent when the renderer loads a resource from its memory cache. // The security info is non empty if the resource was originally loaded over // a secure connection. // Note: May only be sent once per URL per frame per committed load. IPC_MESSAGE_ROUTED2(ViewHostMsg_DidLoadResourceFromMemoryCache, GURL /* url */, std::string /* security info */) // Sent when the renderer displays insecure content in a secure page. IPC_MESSAGE_ROUTED0(ViewHostMsg_DidDisplayInsecureContent) // Sent when the renderer runs insecure content in a secure origin. IPC_MESSAGE_ROUTED2(ViewHostMsg_DidRunInsecureContent, std::string /* security_origin */, GURL /* target URL */) // Sent when the renderer starts a provisional load for a frame. IPC_MESSAGE_ROUTED3(ViewHostMsg_DidStartProvisionalLoadForFrame, int64 /* frame_id */, bool /* true if it is the main frame */, GURL /* url */) // Sent when the renderer fails a provisional load with an error. IPC_MESSAGE_ROUTED5(ViewHostMsg_DidFailProvisionalLoadWithError, int64 /* frame_id */, bool /* true if it is the main frame */, int /* error_code */, GURL /* url */, bool /* true if the failure is the result of navigating to a POST again and we're going to show the POST interstitial */) // Tells the render view that a ViewHostMsg_PaintAtSize message was // processed, and the DIB is ready for use. |tag| has the same value that // the tag sent along with ViewMsg_PaintAtSize. IPC_MESSAGE_ROUTED2(ViewHostMsg_PaintAtSize_ACK, int /* tag */, gfx::Size /* size */) // Sent to update part of the view. In response to this message, the host // generates a ViewMsg_UpdateRect_ACK message. IPC_MESSAGE_ROUTED2(ViewHostMsg_UpdateRect, unsigned int /* seq */, ViewHostMsg_UpdateRect_Params) // Sent by the renderer when accelerated compositing is enabled or disabled to // notify the browser whether or not is should do painting. IPC_MESSAGE_ROUTED1(ViewHostMsg_DidActivateAcceleratedCompositing, bool /* true if the accelerated compositor is actve */) // Acknowledges receipt of a ViewMsg_HandleInputEvent message. // Payload is a WebInputEvent::Type which is the type of the event, followed // by an optional WebInputEvent which is provided only if the event was not // processed. IPC_MESSAGE_ROUTED0(ViewHostMsg_HandleInputEvent_ACK) IPC_MESSAGE_ROUTED0(ViewHostMsg_Focus) IPC_MESSAGE_ROUTED0(ViewHostMsg_Blur) // Message sent from renderer to the browser when focus changes inside the // webpage. The parameter says whether the newly focused element needs // keyboard input (true for textfields, text areas and content editable divs). IPC_MESSAGE_ROUTED1(ViewHostMsg_FocusedNodeChanged, bool /* is_editable_node */) // Returns the window location of the given window. // TODO(shess): Provide a mapping from reply_msg->routing_id() to // HWND so that we can eliminate the NativeViewId parameter. IPC_SYNC_MESSAGE_ROUTED1_1(ViewHostMsg_GetWindowRect, gfx::NativeViewId /* window */, gfx::Rect /* Out: Window location */) IPC_SYNC_MESSAGE_ROUTED0_1(ViewHostMsg_GetFSPluginWinSize, gfx::Size /* Out: Window size */) IPC_MESSAGE_ROUTED1(ViewHostMsg_SetCursor, WebCursor) // Used to set a cookie. The cookie is set asynchronously, but will be // available to a subsequent ViewHostMsg_GetCookies request. IPC_MESSAGE_ROUTED3(ViewHostMsg_SetCookie, GURL /* url */, GURL /* first_party_for_cookies */, std::string /* cookie */) // Used to get cookies for the given URL. This may block waiting for a // previous SetCookie message to be processed. IPC_SYNC_MESSAGE_ROUTED2_1(ViewHostMsg_GetCookies, GURL /* url */, GURL /* first_party_for_cookies */, std::string /* cookies */) // Used to get raw cookie information for the given URL. This may block // waiting for a previous SetCookie message to be processed. IPC_SYNC_MESSAGE_ROUTED2_1(ViewHostMsg_GetRawCookies, GURL /* url */, GURL /* first_party_for_cookies */, std::vector<webkit_glue::WebCookie> /* raw_cookies */) // Used to delete cookie for the given URL and name IPC_SYNC_MESSAGE_CONTROL2_0(ViewHostMsg_DeleteCookie, GURL /* url */, std::string /* cookie_name */) // Used to check if cookies are enabled for the given URL. This may block // waiting for a previous SetCookie message to be processed. IPC_SYNC_MESSAGE_ROUTED2_1(ViewHostMsg_CookiesEnabled, GURL /* url */, GURL /* first_party_for_cookies */, bool /* cookies_enabled */) // Used to get the list of plugins IPC_SYNC_MESSAGE_CONTROL1_1(ViewHostMsg_GetPlugins, bool /* refresh*/, std::vector<webkit::npapi::WebPluginInfo> /* plugins */) // Return information about a plugin for the given URL and MIME // type. If there is no matching plugin, |found| is false. If // |enabled| in the WebPluginInfo struct is false, the plug-in is // treated as if it was not installed at all. // // TODO(jam): until we get ContentSetting out of content completely, sending it // as int temporarily so we can move these messages to content. // // If |setting| is set to CONTENT_SETTING_BLOCK, the plug-in is // blocked by the content settings for |policy_url|. It still // appears in navigator.plugins in Javascript though, and can be // loaded via click-to-play. // // If |setting| is set to CONTENT_SETTING_ALLOW, the domain is // explicitly white-listed for the plug-in, or the user has chosen // not to block nonsandboxed plugins. // // If |setting| is set to CONTENT_SETTING_DEFAULT, the plug-in is // neither blocked nor white-listed, which means that it's allowed // by default and can still be blocked if it's non-sandboxed. // // |actual_mime_type| is the actual mime type supported by the // plugin found that match the URL given (one for each item in // |info|). IPC_SYNC_MESSAGE_CONTROL4_4(ViewHostMsg_GetPluginInfo, int /* routing_id */, GURL /* url */, GURL /* policy_url */, std::string /* mime_type */, bool /* found */, webkit::npapi::WebPluginInfo /* plugin info */, int /* setting */, std::string /* actual_mime_type */) // A renderer sends this to the browser process when it wants to // create a plugin. The browser will create the plugin process if // necessary, and will return a handle to the channel on success. // On error an empty string is returned. IPC_SYNC_MESSAGE_CONTROL3_2(ViewHostMsg_OpenChannelToPlugin, int /* routing_id */, GURL /* url */, std::string /* mime_type */, IPC::ChannelHandle /* channel_handle */, webkit::npapi::WebPluginInfo /* info */) // A renderer sends this to the browser process when it wants to create a // worker. The browser will create the worker process if necessary, and // will return the route id on success. On error returns MSG_ROUTING_NONE. IPC_SYNC_MESSAGE_CONTROL1_1(ViewHostMsg_CreateWorker, ViewHostMsg_CreateWorker_Params, int /* route_id */) // This message is sent to the browser to see if an instance of this shared // worker already exists. If so, it returns exists == true. If a // non-empty name is passed, also validates that the url matches the url of // the existing worker. If a matching worker is found, the passed-in // document_id is associated with that worker, to ensure that the worker // stays alive until the document is detached. // The route_id returned can be used to forward messages to the worker via // ForwardToWorker if it exists, otherwise it should be passed in to any // future call to CreateWorker to avoid creating duplicate workers. IPC_SYNC_MESSAGE_CONTROL1_3(ViewHostMsg_LookupSharedWorker, ViewHostMsg_CreateWorker_Params, bool /* exists */, int /* route_id */, bool /* url_mismatch */) // A renderer sends this to the browser process when a document has been // detached. The browser will use this to constrain the lifecycle of worker // processes (SharedWorkers are shut down when their last associated document // is detached). IPC_MESSAGE_CONTROL1(ViewHostMsg_DocumentDetached, uint64 /* document_id */) // Wraps an IPC message that's destined to the worker on the renderer->browser // hop. IPC_MESSAGE_CONTROL1(ViewHostMsg_ForwardToWorker, IPC::Message /* message */) // Sent if the worker object has sent a ViewHostMsg_CreateDedicatedWorker // message and not received a ViewMsg_WorkerCreated reply, but in the // mean time it's destroyed. This tells the browser to not create the queued // worker. IPC_MESSAGE_CONTROL1(ViewHostMsg_CancelCreateDedicatedWorker, int /* route_id */) // Tells the browser that a specific Appcache manifest in the current page // was accessed. IPC_MESSAGE_ROUTED2(ViewHostMsg_AppCacheAccessed, GURL /* manifest url */, bool /* blocked by policy */) // Tells the browser that a specific Web database in the current page was // accessed. IPC_MESSAGE_ROUTED5(ViewHostMsg_WebDatabaseAccessed, GURL /* origin url */, string16 /* database name */, string16 /* database display name */, unsigned long /* estimated size */, bool /* blocked by policy */) // Initiates a download based on user actions like 'ALT+click'. IPC_MESSAGE_ROUTED2(ViewHostMsg_DownloadUrl, GURL /* url */, GURL /* referrer */) // Used to go to the session history entry at the given offset (ie, -1 will // return the "back" item). IPC_MESSAGE_ROUTED1(ViewHostMsg_GoToEntryAtOffset, int /* offset (from current) of history item to get */) IPC_SYNC_MESSAGE_ROUTED4_2(ViewHostMsg_RunJavaScriptMessage, std::wstring /* in - alert message */, std::wstring /* in - default prompt */, GURL /* in - originating page URL */, int /* in - dialog flags */, bool /* out - success */, std::wstring /* out - prompt field */) // Requests that the given URL be opened in the specified manner. IPC_MESSAGE_ROUTED3(ViewHostMsg_OpenURL, GURL /* url */, GURL /* referrer */, WindowOpenDisposition /* disposition */) // Notifies that the preferred size of the content changed. IPC_MESSAGE_ROUTED1(ViewHostMsg_DidContentsPreferredSizeChange, gfx::Size /* pref_size */) // A message from HTML-based UI. When (trusted) Javascript calls // send(message, args), this message is sent to the browser. IPC_MESSAGE_ROUTED3(ViewHostMsg_WebUISend, GURL /* source_url */, std::string /* message */, std::string /* args (as a JSON string) */) // A renderer sends this to the browser process when it wants to // create a ppapi plugin. The browser will create the plugin process if // necessary, and will return a handle to the channel on success. // On error an empty string is returned. IPC_SYNC_MESSAGE_CONTROL1_2(ViewHostMsg_OpenChannelToPepperPlugin, FilePath /* path */, base::ProcessHandle /* plugin_process_handle */, IPC::ChannelHandle /* handle to channel */) // A renderer sends this to the browser process when it wants to // create a ppapi broker. The browser will create the broker process // if necessary, and will return a handle to the channel on success. // On error an empty string is returned. // The browser will respond with ViewMsg_PpapiBrokerChannelCreated. IPC_MESSAGE_CONTROL3(ViewHostMsg_OpenChannelToPpapiBroker, int /* routing_id */, int /* request_id */, FilePath /* path */) #if defined(USE_X11) // A renderer sends this when it needs a browser-side widget for // hosting a windowed plugin. id is the XID of the plugin window, for which // the container is created. IPC_SYNC_MESSAGE_ROUTED1_0(ViewHostMsg_CreatePluginContainer, gfx::PluginWindowHandle /* id */) // Destroy a plugin container previously created using CreatePluginContainer. // id is the XID of the plugin window corresponding to the container that is // to be destroyed. IPC_SYNC_MESSAGE_ROUTED1_0(ViewHostMsg_DestroyPluginContainer, gfx::PluginWindowHandle /* id */) #endif #if defined(PLUGIN_DIRECT_RENDERING) IPC_MESSAGE_ROUTED4(ViewHostMsg_UpdatePluginWidget, unsigned int /* plugin id */, unsigned int /* pixmap id */, gfx::Rect /* rect */, unsigned int /* seq */) IPC_MESSAGE_ROUTED1(ViewHostMsg_DestroyPluginWidget, unsigned int /* plugin id */) #endif #if defined(OS_MACOSX) // Request that the browser load a font into shared memory for us. IPC_SYNC_MESSAGE_CONTROL1_2(ViewHostMsg_LoadFont, FontDescriptor /* font to load */, uint32 /* buffer size */, base::SharedMemoryHandle /* font data */) #endif #if defined(OS_WIN) // Request that the given font be loaded by the browser so it's cached by the // OS. Please see ChildProcessHost::PreCacheFont for details. IPC_SYNC_MESSAGE_CONTROL1_0(ViewHostMsg_PreCacheFont, LOGFONT /* font data */) #endif // defined(OS_WIN) // Returns WebScreenInfo corresponding to the view. // TODO(shess): Provide a mapping from reply_msg->routing_id() to // HWND so that we can eliminate the NativeViewId parameter. IPC_SYNC_MESSAGE_ROUTED1_1(ViewHostMsg_GetScreenInfo, gfx::NativeViewId /* view */, WebKit::WebScreenInfo /* results */) // Send the tooltip text for the current mouse position to the browser. IPC_MESSAGE_ROUTED2(ViewHostMsg_SetTooltipText, std::wstring /* tooltip text string */, WebKit::WebTextDirection /* text direction hint */) // Notification that the text selection has changed. IPC_MESSAGE_ROUTED1(ViewHostMsg_SelectionChanged, std::string /* currently selected text */) // Asks the browser to display the file chooser. The result is returned in a // ViewHost_RunFileChooserResponse message. IPC_MESSAGE_ROUTED1(ViewHostMsg_RunFileChooser, ViewHostMsg_RunFileChooser_Params) // Asks the browser to enumerate a directory. This is equivalent to running // the file chooser in directory-enumeration mode and having the user select // the given directory. The result is returned in a // ViewMsg_EnumerateDirectoryResponse message. IPC_MESSAGE_ROUTED2(ViewHostMsg_EnumerateDirectory, int /* request_id */, FilePath /* file_path */) // Tells the browser to move the focus to the next (previous if reverse is // true) focusable element. IPC_MESSAGE_ROUTED1(ViewHostMsg_TakeFocus, bool /* reverse */) // Returns the window location of the window this widget is embeded. // TODO(shess): Provide a mapping from reply_msg->routing_id() to // HWND so that we can eliminate the NativeViewId parameter. IPC_SYNC_MESSAGE_ROUTED1_1(ViewHostMsg_GetRootWindowRect, gfx::NativeViewId /* window */, gfx::Rect /* Out: Window location */) // Required for updating text input state. IPC_MESSAGE_ROUTED2(ViewHostMsg_ImeUpdateTextInputState, WebKit::WebTextInputType, /* text_input_type */ gfx::Rect /* caret_rect */) // Required for cancelling an ongoing input method composition. IPC_MESSAGE_ROUTED0(ViewHostMsg_ImeCancelComposition) // WebKit and JavaScript error messages to log to the console // or debugger UI. IPC_MESSAGE_ROUTED4(ViewHostMsg_AddMessageToConsole, int32, /* log level */ std::wstring, /* msg */ int32, /* line number */ std::wstring /* source id */) // Sent by the renderer process to indicate that a plugin instance has // crashed. IPC_MESSAGE_ROUTED1(ViewHostMsg_CrashedPlugin, FilePath /* plugin_path */) // Displays a box to confirm that the user wants to navigate away from the // page. Replies true if yes, false otherwise, the reply string is ignored, // but is included so that we can use OnJavaScriptMessageBoxClosed. IPC_SYNC_MESSAGE_ROUTED2_2(ViewHostMsg_RunBeforeUnloadConfirm, GURL, /* in - originating frame URL */ std::wstring /* in - alert message */, bool /* out - success */, std::wstring /* out - This is ignored.*/) // Sent when the renderer process is done processing a DataReceived // message. IPC_MESSAGE_ROUTED1(ViewHostMsg_DataReceived_ACK, int /* request_id */) IPC_MESSAGE_CONTROL1(ViewHostMsg_RevealFolderInOS, FilePath /* path */) // Sent when a provisional load on the main frame redirects. IPC_MESSAGE_ROUTED3(ViewHostMsg_DidRedirectProvisionalLoad, int /* page_id */, GURL /* last url */, GURL /* url redirected to */) // Sent when the renderer changes the zoom level for a particular url, so the // browser can update its records. If remember is true, then url is used to // update the zoom level for all pages in that site. Otherwise, the render // view's id is used so that only the menu is updated. IPC_MESSAGE_ROUTED3(ViewHostMsg_DidZoomURL, double /* zoom_level */, bool /* remember */, GURL /* url */) // Updates the minimum/maximum allowed zoom percent for this tab from the // default values. If |remember| is true, then the zoom setting is applied to // other pages in the site and is saved, otherwise it only applies to this // tab. IPC_MESSAGE_ROUTED3(ViewHostMsg_UpdateZoomLimits, int /* minimum_percent */, int /* maximum_percent */, bool /* remember */) // Asks the browser to create a block of shared memory for the renderer to // fill in and pass back to the browser. IPC_SYNC_MESSAGE_CONTROL1_1(ViewHostMsg_AllocateSharedMemoryBuffer, uint32 /* buffer size */, base::SharedMemoryHandle /* browser handle */) // Notify the browser that this render process can or can't be suddenly // terminated. IPC_MESSAGE_CONTROL1(ViewHostMsg_SuddenTerminationChanged, bool /* enabled */) #if defined(OS_MACOSX) // On OSX, we cannot allocated shared memory from within the sandbox, so // this call exists for the renderer to ask the browser to allocate memory // on its behalf. We return a file descriptor to the POSIX shared memory. // If the |cache_in_browser| flag is |true|, then a copy of the shmem is kept // by the browser, and it is the caller's repsonsibility to send a // ViewHostMsg_FreeTransportDIB message in order to release the cached shmem. // In all cases, the caller is responsible for deleting the resulting // TransportDIB. IPC_SYNC_MESSAGE_CONTROL2_1(ViewHostMsg_AllocTransportDIB, size_t, /* bytes requested */ bool, /* cache in the browser */ TransportDIB::Handle /* DIB */) // Since the browser keeps handles to the allocated transport DIBs, this // message is sent to tell the browser that it may release them when the // renderer is finished with them. IPC_MESSAGE_CONTROL1(ViewHostMsg_FreeTransportDIB, TransportDIB::Id /* DIB id */) // Informs the browser that a plugin has gained or lost focus. IPC_MESSAGE_ROUTED2(ViewHostMsg_PluginFocusChanged, bool, /* focused */ int /* plugin_id */) // Instructs the browser to start plugin IME. IPC_MESSAGE_ROUTED0(ViewHostMsg_StartPluginIme) //--------------------------------------------------------------------------- // Messages related to accelerated plugins // This is sent from the renderer to the browser to allocate a fake // PluginWindowHandle on the browser side which is used to identify // the plugin to the browser later when backing store is allocated // or reallocated. |opaque| indicates whether the plugin's output is // considered to be opaque, as opposed to translucent. This message // is reused for rendering the accelerated compositor's output. // |root| indicates whether the output is supposed to cover the // entire window. IPC_SYNC_MESSAGE_ROUTED2_1(ViewHostMsg_AllocateFakePluginWindowHandle, bool /* opaque */, bool /* root */, gfx::PluginWindowHandle /* id */) // Destroys a fake window handle previously allocated using // AllocateFakePluginWindowHandle. IPC_MESSAGE_ROUTED1(ViewHostMsg_DestroyFakePluginWindowHandle, gfx::PluginWindowHandle /* id */) // This message, used on Mac OS X 10.5 and earlier (no IOSurface support), // is sent from the renderer to the browser on behalf of the plug-in // to indicate that a new backing store was allocated for that plug-in // instance. IPC_MESSAGE_ROUTED4(ViewHostMsg_AcceleratedSurfaceSetTransportDIB, gfx::PluginWindowHandle /* window */, int32 /* width */, int32 /* height */, TransportDIB::Handle /* handle for the DIB */) // This message, used on Mac OS X 10.6 and later (where IOSurface is // supported), is sent from the renderer to the browser on behalf of the // plug-in to indicate that a new backing store was allocated for that // plug-in instance. // // NOTE: the original intent was to pass a mach port as the IOSurface // identifier but it looks like that will be a lot of work. For now we pass an // ID from IOSurfaceGetID. IPC_MESSAGE_ROUTED4(ViewHostMsg_AcceleratedSurfaceSetIOSurface, gfx::PluginWindowHandle /* window */, int32 /* width */, int32 /* height */, uint64 /* surface_id */) // This message notifies the browser process that the plug-in // swapped the buffers associated with the given "window", which // should cause the browser to redraw the various plug-ins' // contents. IPC_MESSAGE_ROUTED2(ViewHostMsg_AcceleratedSurfaceBuffersSwapped, gfx::PluginWindowHandle /* window */, uint64 /* surface_id */) #endif // Sent to notify the browser about renderer accessibility notifications. // The browser responds with a ViewMsg_AccessibilityNotifications_ACK. IPC_MESSAGE_ROUTED1( ViewHostMsg_AccessibilityNotifications, std::vector<ViewHostMsg_AccessibilityNotification_Params>) // Opens a file asynchronously. The response returns a file descriptor // and an error code from base/platform_file.h. IPC_MESSAGE_ROUTED3(ViewHostMsg_AsyncOpenFile, FilePath /* file path */, int /* flags */, int /* message_id */) //--------------------------------------------------------------------------- // Request for cryptographic operation messages: // These are messages from the renderer to the browser to perform a // cryptographic operation. // Asks the browser process to generate a keypair for grabbing a client // certificate from a CA (<keygen> tag), and returns the signed public // key and challenge string. IPC_SYNC_MESSAGE_CONTROL3_1(ViewHostMsg_Keygen, uint32 /* key size index */, std::string /* challenge string */, GURL /* URL of requestor */, std::string /* signed public key and challenge */) // Message sent from the renderer to the browser to request that the browser // close all sockets. Used for debugging/testing. IPC_MESSAGE_CONTROL0(ViewHostMsg_CloseCurrentConnections) // Message sent from the renderer to the browser to request that the browser // enable or disable the cache. Used for debugging/testing. IPC_MESSAGE_CONTROL1(ViewHostMsg_SetCacheMode, bool /* enabled */) // Message sent from the renderer to the browser to request that the browser // clear the cache. Used for debugging/testing. // |preserve_ssl_host_info| controls whether clearing the cache will preserve // persisted SSL information stored in the cache. // |result| is the returned status from the operation. IPC_SYNC_MESSAGE_CONTROL1_1(ViewHostMsg_ClearCache, bool /* preserve_ssl_host_info */, int /* result */) // Message sent from the renderer to the browser to request that the browser // clear the host cache. Used for debugging/testing. // |result| is the returned status from the operation. IPC_SYNC_MESSAGE_CONTROL0_1(ViewHostMsg_ClearHostResolverCache, int /* result */) // Message sent from the renderer to the browser to request that the browser // clear the predictor cache. Used for debugging/testing. // |result| is the returned status from the operation. IPC_SYNC_MESSAGE_CONTROL0_1(ViewHostMsg_ClearPredictorCache, int /* result */) // Message sent from the renderer to the browser to request that the browser // enable or disable spdy. Used for debugging/testing/benchmarking. IPC_MESSAGE_CONTROL1(ViewHostMsg_EnableSpdy, bool /* enable */) // Message sent from the renderer to the browser to request that the browser // cache |data| associated with |url|. IPC_MESSAGE_CONTROL3(ViewHostMsg_DidGenerateCacheableMetadata, GURL /* url */, double /* expected_response_time */, std::vector<char> /* data */) // Updates the content restrictions, i.e. to disable print/copy. IPC_MESSAGE_ROUTED1(ViewHostMsg_UpdateContentRestrictions, int /* restrictions */) // The currently displayed PDF has an unsupported feature. IPC_MESSAGE_ROUTED0(ViewHostMsg_PDFHasUnsupportedFeature) // Brings up SaveAs... dialog to save specified URL. IPC_MESSAGE_ROUTED1(ViewHostMsg_SaveURLAs, GURL /* url */) // Notifies when default plugin updates status of the missing plugin. IPC_MESSAGE_ROUTED1(ViewHostMsg_MissingPluginStatus, int /* status */) // Displays a JavaScript out-of-memory message in the infobar. IPC_MESSAGE_ROUTED0(ViewHostMsg_JSOutOfMemory) // Register a new handler for URL requests with the given scheme. IPC_MESSAGE_ROUTED3(ViewHostMsg_RegisterProtocolHandler, std::string /* scheme */, GURL /* url */, string16 /* title */) // Stores new inspector setting in the profile. // TODO(jam): this should be in the chrome module IPC_MESSAGE_ROUTED2(ViewHostMsg_UpdateInspectorSetting, std::string, /* key */ std::string /* value */) // Message sent from the renderer to the browser to notify it of events which // may lead to the cancellation of a prerender. The message is sent only when // the renderer is in prerender mode. IPC_MESSAGE_ROUTED0(ViewHostMsg_MaybeCancelPrerenderForHTML5Media)
42.276104
85
0.724499
4fff4ec8acaaedcec339d5d9183a57664c115cf9
65
c
C
rts/sm/Evac_thr.c
AntonXue/ghc-8.2.2-base-dumper
02cb9dd92a5e209ec775ed940f73a7f8eb3508a1
[ "BSD-3-Clause" ]
null
null
null
rts/sm/Evac_thr.c
AntonXue/ghc-8.2.2-base-dumper
02cb9dd92a5e209ec775ed940f73a7f8eb3508a1
[ "BSD-3-Clause" ]
null
null
null
rts/sm/Evac_thr.c
AntonXue/ghc-8.2.2-base-dumper
02cb9dd92a5e209ec775ed940f73a7f8eb3508a1
[ "BSD-3-Clause" ]
null
null
null
#ifdef THREADED_RTS #define PARALLEL_GC #include "Evac.c" #endif
13
19
0.784615
539db7f2ab72b7fef2ce6282b57cb706546894d6
9,975
c
C
libMx/mx_time.c
nbeaver/mx-trunk
8f9305f42cc5b12b77ba0354680bb317d779165d
[ "X11", "MIT" ]
null
null
null
libMx/mx_time.c
nbeaver/mx-trunk
8f9305f42cc5b12b77ba0354680bb317d779165d
[ "X11", "MIT" ]
null
null
null
libMx/mx_time.c
nbeaver/mx-trunk
8f9305f42cc5b12b77ba0354680bb317d779165d
[ "X11", "MIT" ]
2
2016-11-21T05:10:10.000Z
2019-11-14T11:35:45.000Z
/* * Name: mx_time.c * * Purpose: This file provides thread-safe Posix time functions for * those platforms that do not have them and also adds * some MX-specific functions. * * Author: William Lavender * *------------------------------------------------------------------------ * * Copyright 2010, 2015-2018, 2021 Illinois Institute of Technology * * See the file "LICENSE" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * */ #define MX_NO_POISON #include <stdio.h> #include <errno.h> #include "mx_osdef.h" #include "mx_util.h" #include "mx_time.h" #if defined(OS_UNIX) || defined(OS_CYGWIN) #include <sys/time.h> #endif #if defined(OS_WIN32) #include <windows.h> #endif /* 26 is a magic number from the asctime_r and ctime_r man pages on Linux. */ #define MX_TIME_BUFFER_LENGTH 26 /*-------------------------------------------------------------------------*/ #if defined(OS_UNIX) || defined(OS_CYGWIN) || defined(OS_VMS) \ || defined(OS_RTEMS) || defined(OS_VXWORKS) || defined(OS_ANDROID) \ || defined(OS_MINIX) /* These platforms already provide the thread-safe Posix time functions. */ #define MX_USE_LOCALTIME_R /*- - - -*/ #elif defined(OS_WIN32) #if defined(_MSC_VER) #if (_MSC_VER >= 1400) #define MX_USE_LOCALTIME_S #else /* Apparently the msvcrt.dll DLLs used by Visual C++ 2003 and before * use thread local storage for the internal buffers of the functions, * which makes the functions thread safe on this platform. */ #define MX_USE_LOCALTIME #endif #elif defined(__BORLANDC__) || defined(__GNUC__) /* Apparently the msvcrt.dll DLLs used by Borland and Mingw use thread * local storage for the internal buffers of the functions, which makes * the functions thread safe on these platforms. */ #define MX_USE_LOCALTIME #else #error Unrecognized Win32 compiler. #endif /*- - - -*/ #elif defined(OS_DJGPP) #define MX_USE_LOCALTIME /*- - - -*/ #else #error Thread-safe time functions have not been defined for this platform. #endif /*-------------------------------------------------------------------------*/ #if defined(MX_USE_LOCALTIME_R) /* We do not need to do anything for this case, since the thread-safe * Posix time functions are already defined. */ /*-------------------------------------------------------------------------*/ #elif defined(MX_USE_LOCALTIME_S) MX_EXPORT char * asctime_r( const struct tm *tm_struct, char *buffer ) { errno_t os_status; os_status = asctime_s( buffer, MX_TIME_BUFFER_LENGTH, tm_struct ); if ( os_status == 0 ) { return buffer; } else { errno = os_status; return NULL; } } MX_EXPORT char * ctime_r( const time_t *time_struct, char *buffer ) { errno_t os_status; os_status = ctime_s( buffer, MX_TIME_BUFFER_LENGTH, time_struct ); if ( os_status == 0 ) { return buffer; } else { errno = os_status; return NULL; } } MX_EXPORT struct tm * gmtime_r( const time_t *time_struct, struct tm *tm_struct ) { errno_t os_status; os_status = gmtime_s( tm_struct, time_struct ); if ( os_status == 0 ) { return tm_struct; } else { errno = os_status; return NULL; } } MX_EXPORT struct tm * localtime_r( const time_t *time_struct, struct tm *tm_struct ) { errno_t os_status; os_status = localtime_s( tm_struct, time_struct ); if ( os_status == 0 ) { return tm_struct; } else { errno = os_status; return NULL; } } /*-------------------------------------------------------------------------*/ #elif defined(MX_USE_LOCALTIME) MX_EXPORT char * asctime_r( const struct tm *tm_struct, char *buffer ) { char *ptr; if ( tm_struct == NULL ) { errno = EINVAL; return NULL; } ptr = asctime( tm_struct ); if ( buffer != NULL ) { memcpy( buffer, ptr, MX_TIME_BUFFER_LENGTH ); } return ptr; } MX_EXPORT char * ctime_r( const time_t *time_struct, char *buffer ) { char *ptr; if ( time_struct == NULL ) { errno = EINVAL; return NULL; } ptr = ctime( time_struct ); if ( buffer != NULL ) { memcpy( buffer, ptr, MX_TIME_BUFFER_LENGTH ); } return ptr; } MX_EXPORT struct tm * gmtime_r( const time_t *time_struct, struct tm *tm_struct ) { struct tm *ptr; if ( time_struct == NULL ) { errno = EINVAL; return NULL; } ptr = gmtime( time_struct ); if ( tm_struct != NULL ) { memcpy( tm_struct, ptr, sizeof(struct tm) ); } return ptr; } MX_EXPORT struct tm * localtime_r( const time_t *time_struct, struct tm *tm_struct ) { struct tm *ptr; if ( time_struct == NULL ) { errno = EINVAL; return NULL; } ptr = localtime( time_struct ); if ( tm_struct != NULL ) { memcpy( tm_struct, ptr, sizeof(struct tm) ); } return ptr; } /*-------------------------------------------------------------------------*/ #else #error Thread-safe time functions have not been defined for this platform. #endif /*=========================================================================*/ /*------------ MX OS time reporting functions. ------------*/ #if 0 MX_EXPORT struct timespec mx_current_os_time( void ) { struct timespec result; result.tv_sec = 0; result.tv_nsec = 0; return result; } #elif defined(OS_WIN32) MX_EXPORT struct timespec mx_current_os_time( void ) { DWORD os_time; struct timespec result; os_time = timeGetTime(); result.tv_sec = os_time / 1000L; result.tv_nsec = ( os_time % 1000L ) * 1000000L; return result; } #elif defined(OS_ECOS) || defined(OS_VXWORKS) MX_EXPORT struct timespec mx_current_os_time( void ) { static const char fname[] = "mx_current_os_time()"; struct timespec result; int os_status, saved_errno; os_status = clock_gettime(CLOCK_REALTIME, &result); if ( os_status == -1 ) { saved_errno = errno; (void) mx_error( MXE_OPERATING_SYSTEM_ERROR, fname, "The call to clock_gettime() failed. " "Errno = %d, error message = '%s'", saved_errno, strerror(saved_errno) ); } return result; } #else #if defined(OS_RTEMS) # include <sys/time.h> # include <unistd.h> #endif MX_EXPORT struct timespec mx_current_os_time( void ) { static const char fname[] = "mx_current_os_time()"; struct timespec result; struct timeval os_timeofday; int os_status, saved_errno; os_status = gettimeofday( &os_timeofday, NULL ); if ( os_status != 0 ) { saved_errno = errno; result.tv_sec = 0; result.tv_nsec = 0; (void) mx_error( MXE_OPERATING_SYSTEM_ERROR, fname, "A call to gettimeofday() failed. " "Errno = %d, error message = '%s'", saved_errno, strerror(saved_errno) ); } else { result.tv_sec = os_timeofday.tv_sec; result.tv_nsec = 1000L * os_timeofday.tv_usec; } return result; } #endif MX_EXPORT char * mx_os_time_string( struct timespec os_time, char *buffer, size_t buffer_length ) { static const char fname[] = "mx_os_time_string()"; time_t time_in_seconds; struct tm tm_struct; char *ptr; char local_buffer[20]; double nsec_in_seconds; if ( buffer == NULL ) { (void) mx_error( MXE_NULL_ARGUMENT, fname, "The string buffer pointer passed was NULL." ); return NULL; } time_in_seconds = os_time.tv_sec; localtime_r( &time_in_seconds, &tm_struct ); strftime( buffer, buffer_length, "%a %b %d %Y %H:%M:%S", &tm_struct ); nsec_in_seconds = 1.0e-9 * (double) os_time.tv_nsec; snprintf( local_buffer, sizeof(local_buffer), "%f", nsec_in_seconds ); ptr = strchr( local_buffer, '.' ); if ( ptr == NULL ) { return buffer; } strlcat( buffer, ptr, buffer_length ); return buffer; } /*-------------------------------------------------------------------------*/ MX_EXPORT char * mx_ctime_string( void ) { char *ptr; size_t length; time_t seconds_since_1970_started; seconds_since_1970_started = time(NULL); ptr = ctime( &seconds_since_1970_started ); /* Zap the newline at the end of the string returned by ctime(). */ length = strlen(ptr); ptr[length - 1] = '\0'; return ptr; } MX_EXPORT char * mx_ctime_tz_string( char *buffer, size_t buffer_length ) { /* This format generates a string that looks like the string * generated with ctime(), but with timezone information as well. */ #if ( defined( MX_GNUC_VERSION ) && ( MX_GNUC_VERSION < 3004000L ) ) static const char format[] = "%a %b %d %H:%M:%S %Y"; #else static const char format[] = "%c %Z"; #endif time_t now; struct tm tm_struct; memset( &tm_struct, 0, sizeof(tm_struct) ); now = time( NULL ); localtime_r( &now, &tm_struct ); strftime( buffer, buffer_length, format, &tm_struct ); return buffer; } MX_EXPORT char * mx_current_time_string( char *buffer, size_t buffer_length ) { time_t time_struct; struct tm *current_time; static char local_buffer[200]; char *ptr; if ( buffer == NULL ) { ptr = &local_buffer[0]; buffer_length = sizeof(local_buffer); } else { ptr = buffer; } time( &time_struct ); current_time = localtime( &time_struct ); strftime( ptr, buffer_length, "%a %b %d %Y %H:%M:%S", current_time ); return ptr; } /*-------------------------------------------------------------------------*/ /* FIXME: The time() system call does not return a 64-bit time on 32-bit * platforms. We need to find a way to get the correct 64-bit time * relative to the Posix epoch on such platforms to avoid the * Y-2038 problem. */ #if defined(OS_WIN32) || defined(OS_LINUX) || defined(OS_MACOSX) \ || defined(OS_SOLARIS) || defined(OS_BSD) || defined(OS_CYGWIN) \ || defined(OS_VMS) || defined(OS_UNIXWARE) || defined(OS_DJGPP) \ || defined(OS_QNX) || defined(OS_RTEMS) || defined(OS_VXWORKS) \ || defined(OS_HURD) || defined(OS_ANDROID) || defined(OS_MINIX) MX_EXPORT uint64_t mx_posix_time( void ) { uint64_t posix_time; posix_time = time( NULL ); return posix_time; } #else #error mx_posix_time() is not yet defined for this platform. #endif /*-------------------------------------------------------------------------*/
20.233266
77
0.630376
5b4e8026b4fd18a13e9e92b67c0e7d01a985132f
426
c
C
code/8-5.c
Adiao1973/C
d30b377c7ff5d5b664c1543010705d35a89be526
[ "MIT" ]
null
null
null
code/8-5.c
Adiao1973/C
d30b377c7ff5d5b664c1543010705d35a89be526
[ "MIT" ]
null
null
null
code/8-5.c
Adiao1973/C
d30b377c7ff5d5b664c1543010705d35a89be526
[ "MIT" ]
null
null
null
#include <stdio.h> int main() { /* 局部变量定义 */ char grade = 'B'; switch (grade) { case 'A': printf("很棒!\n"); break; case 'B': case 'C': printf("做得好\n"); break; case 'D': printf("您通过了\n"); break; case 'F': printf("最好再试一下\n"); default: printf("无效的成绩\n"); break; } printf("您的成绩是 %c\n", grade); return 0; }
15.214286
32
0.420188
85dc06fc39dee165088e7dda4725c0bb0c7d731c
2,266
h
C
dbms/src/Client/InterruptListener.h
SevaCode/ClickHouse
08cb8e506b49aef6ae2086be8947f728450c4d73
[ "Apache-2.0" ]
1
2017-01-17T17:29:05.000Z
2017-01-17T17:29:05.000Z
dbms/src/Client/InterruptListener.h
SevaCode/ClickHouse
08cb8e506b49aef6ae2086be8947f728450c4d73
[ "Apache-2.0" ]
1
2017-01-13T21:29:36.000Z
2017-01-16T18:29:08.000Z
dbms/src/Client/InterruptListener.h
jbfavre/clickhouse-debian
3806e3370decb40066f15627a3bca4063b992bfb
[ "Apache-2.0" ]
null
null
null
#pragma once #include <signal.h> #include <DB/Common/Exception.h> namespace DB { namespace ErrorCodes { extern const int CANNOT_MANIPULATE_SIGSET; extern const int CANNOT_WAIT_FOR_SIGNAL; extern const int CANNOT_BLOCK_SIGNAL; extern const int CANNOT_UNBLOCK_SIGNAL; } #ifdef __APPLE__ // We only need to support timeout = {0, 0} at this moment static int sigtimedwait(const sigset_t *set, siginfo_t *info, const struct timespec *timeout) { sigset_t pending; int signo; sigpending(&pending); for (signo = 1; signo < NSIG; signo++) { if (sigismember(set, signo) && sigismember(&pending, signo)) { sigwait(set, &signo); if (info) { memset(info, 0, sizeof *info); info->si_signo = signo; } return signo; } } errno = EAGAIN; return -1; } #endif /** Пока существует объект этого класса - блокирует сигнал INT, при этом позволяет узнать, не пришёл ли он. * Это нужно, чтобы можно было прервать выполнение запроса с помощью Ctrl+C. * В один момент времени используйте только один экземпляр этого класса. * Если метод check вернул true (пришёл сигнал), то следующие вызовы будут ждать следующий сигнал. */ class InterruptListener { private: bool active; sigset_t sig_set; public: InterruptListener() : active(false) { if (sigemptyset(&sig_set) || sigaddset(&sig_set, SIGINT)) throwFromErrno("Cannot manipulate with signal set.", ErrorCodes::CANNOT_MANIPULATE_SIGSET); block(); } ~InterruptListener() { unblock(); } bool check() { if (!active) return false; timespec timeout = { 0, 0 }; if (-1 == sigtimedwait(&sig_set, nullptr, &timeout)) { if (errno == EAGAIN) return false; else throwFromErrno("Cannot poll signal (sigtimedwait).", ErrorCodes::CANNOT_WAIT_FOR_SIGNAL); } return true; } void block() { if (!active) { if (pthread_sigmask(SIG_BLOCK, &sig_set, nullptr)) throwFromErrno("Cannot block signal.", ErrorCodes::CANNOT_BLOCK_SIGNAL); active = true; } } /// Можно прекратить блокировать сигнал раньше, чем в деструкторе. void unblock() { if (active) { if (pthread_sigmask(SIG_UNBLOCK, &sig_set, nullptr)) throwFromErrno("Cannot unblock signal.", ErrorCodes::CANNOT_UNBLOCK_SIGNAL); active = false; } } }; }
20.414414
107
0.695499
1291a5205717c973644ca0b4b1c5471747bdba56
76,298
h
C
demo_drivers/heat_transfer_and_melting/two_d_unsteady_heat_melt/contact_elements.h
pkeuchel/oomph-lib
37c1c61425d6b9ea1c2ddceef63a68a228af6fa4
[ "RSA-MD" ]
4
2020-11-16T12:25:09.000Z
2021-06-29T08:53:25.000Z
demo_drivers/heat_transfer_and_melting/two_d_unsteady_heat_melt/contact_elements.h
pkeuchel/oomph-lib
37c1c61425d6b9ea1c2ddceef63a68a228af6fa4
[ "RSA-MD" ]
2
2020-05-05T22:41:37.000Z
2020-05-10T14:14:17.000Z
demo_drivers/heat_transfer_and_melting/two_d_unsteady_heat_melt/contact_elements.h
pkeuchel/oomph-lib
37c1c61425d6b9ea1c2ddceef63a68a228af6fa4
[ "RSA-MD" ]
3
2021-01-31T14:09:20.000Z
2021-06-07T07:20:51.000Z
//LIC// ==================================================================== //LIC// This file forms part of oomph-lib, the object-oriented, //LIC// multi-physics finite-element library, available //LIC// at http://www.oomph-lib.org. //LIC// //LIC// Copyright (C) 2006-2021 Matthias Heil and Andrew Hazel //LIC// //LIC// This library is free software; you can redistribute it and/or //LIC// modify it under the terms of the GNU Lesser General Public //LIC// License as published by the Free Software Foundation; either //LIC// version 2.1 of the License, or (at your option) any later version. //LIC// //LIC// This library is distributed in the hope that it will be useful, //LIC// but WITHOUT ANY WARRANTY; without even the implied warranty of //LIC// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //LIC// Lesser General Public License for more details. //LIC// //LIC// You should have received a copy of the GNU Lesser General Public //LIC// License along with this library; if not, write to the Free Software //LIC// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA //LIC// 02110-1301 USA. //LIC// //LIC// The authors may be contacted at oomph-lib@maths.man.ac.uk. //LIC// //LIC//==================================================================== // Header file for elements that enforce solid contact #ifndef OOMPH_CONTACT_ELEMENTS_HEADER #define OOMPH_CONTACT_ELEMENTS_HEADER // Config header generated by autoconfig #ifdef HAVE_CONFIG_H #include <oomph-lib-config.h> #endif //Standard libray headers #include <cmath> // oomph-lib includes #include "generic.h" // ../generic/Qelements.h" namespace oomph { //========================================================= /// Piecewise Gauss integration rule. Uses /// Gauss rules of specified order in three sub-intervals /// of element. //========================================================= template <unsigned DIM, unsigned NPTS_1D> class PiecewiseGauss : public Gauss<DIM,NPTS_1D> { private: /// Store for the lower and upper limits of integration and the range double Lower, Upper, Range; public: /// Constructor: Pass in lower and upper limits of 1D coordinate /// over which we're integrating PiecewiseGauss(const double& lower, const double& upper) : Lower(lower), Upper(upper) { //Set the range of integration Range = upper - lower; } /// Broken copy constructor PiecewiseGauss(const PiecewiseGauss& dummy) { BrokenCopy::broken_copy("PiecewiseGauss"); } /// Return the number of integration points of the scheme. virtual unsigned nweight() const { return 3*Gauss<DIM,NPTS_1D>::nweight(); } /// Return the rescaled knot values s[j] at integration point i double knot(const unsigned &i, const unsigned &j) const { if (i<Gauss<DIM,NPTS_1D>::nweight()) { double range=0.25*Range; double lower=Lower+0.0; //double upper=Lower+0.25*Range; unsigned ii=i; return (lower+(0.5*(1.0+Gauss<DIM,NPTS_1D>::knot(ii,j))*range)); } else if (i<2*Gauss<DIM,NPTS_1D>::nweight()) { double range=0.5*Range; double lower=Lower+0.25*Range; //double upper=Lower+0.75*Range; unsigned ii=i-Gauss<DIM,NPTS_1D>::nweight(); return (lower+(0.5*(1.0+Gauss<DIM,NPTS_1D>::knot(ii,j))*range)); } else { double range=0.25*Range; double lower=Lower+0.75*Range; //double upper=Upper; unsigned ii=i-2*Gauss<DIM,NPTS_1D>::nweight(); return (lower+(0.5*(1.0+Gauss<DIM,NPTS_1D>::knot(ii,j))*range)); } } /// Return the rescaled weight at integration point i double weight(const unsigned &i) const { if (i<Gauss<DIM,NPTS_1D>::nweight()) { double range=0.25*Range; unsigned ii=i; return Gauss<DIM,NPTS_1D>::weight(ii)* pow(0.5*range,static_cast<int>(DIM)); } else if (i<2*Gauss<DIM,NPTS_1D>::nweight()) { double range=0.5*Range; unsigned ii=i-Gauss<DIM,NPTS_1D>::nweight(); return Gauss<DIM,NPTS_1D>::weight(ii)* pow(0.5*range,static_cast<int>(DIM)); } else { double range=0.25*Range; unsigned ii=i-2*Gauss<DIM,NPTS_1D>::nweight(); return Gauss<DIM,NPTS_1D>::weight(ii)* pow(0.5*range,static_cast<int>(DIM)); } } }; /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// //====================================================================== /// Base class for penetrator. Must be able to compute /// the penetration with another body, based on the position vector, x, /// to, and the outer unit normal, n, on that other body. //====================================================================== class Penetrator { public: /// Constructor Penetrator(){}; /// Destructor virtual ~Penetrator(){}; /// Get penetration for given point x with outer unit normal n. /// Should return the negative distance along outer unit normal to the /// closest point on the penetrator, so that minus values imply no /// penetration and positive ones imply penetration. If the ray from the /// unit normal never crosses the penetrator,set intersection to false /// In this case, d can be set to anything, as it should be ignored anway. /// Returning a bool moves the problem of deciding what to do with /// non-intersection to each individual method virtual void penetration(const Vector<double>& x, const Vector<double>& n, double& d, bool& intersection) const = 0; /// Output coordinates of penetrator at nplot plot points virtual void output(std::ostream &outfile, const unsigned& nplot) const =0; /// Get rigid body displacement of reference point in penetrator. /// Broken virtual, so you don't really have to imlement this... virtual Vector<double> rigid_body_displacement() const { throw OomphLibError( "This is a broken virtual function. Please implement/overload. ", OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } /// Vector of pairs identifying values (via a pair of pointer to /// Data object and index within it) that correspond to the Data values /// that are determined by the horizontal/vertical/... equilibrium of force /// equations. Empty by default, indicating that the penetrator is in a /// prescribed position (i.e. a position that is not determined as part /// of the solution!) virtual Vector<std::pair<Data*,unsigned> > equilibrium_data() { Vector<std::pair<Data*,unsigned> > dummy; return dummy; } /// Get surface coordinate along penetrator for given point x; /// implies some sort of "projection"-type relation between /// point x and the parametrisation of the surface (e.g. polar /// angle). virtual void surface_coordinate(const Vector<double>& x, Vector<double>& zeta) const { throw OomphLibError( "This is a broken virtual function. Please implement/overload. ", OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } }; //====================================================================== /// Base class for "heated" penetrator. //====================================================================== class HeatedPenetrator : public virtual Penetrator { public: /// Constructor HeatedPenetrator(){}; /// Destructor virtual ~HeatedPenetrator(){}; /// Get penetrator temperature at surface for given point x. Specific /// implementation of penetetrator has do decide how to relate /// these two points. virtual double temperature(const Vector<double>& x) const=0; }; /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// //====================================================================== /// Penetrator -- here implemented as a circle //====================================================================== class CircularPenetrator : public virtual Penetrator { public: /// Constructor: Pass pointer to centre and radius CircularPenetrator(Vector<double>* r_c_pt, const double& r) { Centre_pt=r_c_pt; Radius=r; // Back up original centre unsigned n=r_c_pt->size(); Orig_centre.resize(n); for (unsigned i=0;i<n;i++) { Orig_centre[i]=(*r_c_pt)[i]; } } /// Destructor virtual ~CircularPenetrator(){} /// Get penetration for given point x void penetration(const Vector<double>& x, const Vector<double>& n, double& d, bool& intersection)const { // Vector from potential contact point to centre of penetrator Vector<double> l(2); l[0]=(*Centre_pt)[0]-x[0]; l[1]=(*Centre_pt)[1]-x[1]; // Distance from potential contact point to centre of penetrator double ll=sqrt(l[0]*l[0]+l[1]*l[1]); // Projection of vector from potential contact point to centre of penetrator // onto outer unit normal on potential contact point double project=n[0]*l[0]+n[1]*l[1]; double project_squared=project*project; // Final term in square root double b_squared=ll*ll-Radius*Radius; // Is square root negative? In this case we have no intersection if (project_squared<b_squared) { d = 0.0; intersection = false; //return -10*std::numeric_limits<double>::min(); } else { double sqr=sqrt(project_squared-b_squared); d = -std::min(project-sqr,project+sqr); intersection = true; } } /// Output coordinates of penetrator at nplot plot points void output(std::ostream &outfile, const unsigned& nplot) const { for (unsigned j=0;j<nplot;j++) { double phi=2.0*MathematicalConstants::Pi*double(j)/double(nplot-1); outfile << (*Centre_pt)[0]+Radius*cos(phi) << " " << (*Centre_pt)[1]+Radius*sin(phi) << std::endl; } } /// Get position to surface, r, in terms of surface coordinate zeta. void position_from_zeta(const Vector<double>& zeta, Vector<double>& r) const { double phi=zeta[0]; r[0]=(*Centre_pt)[0]+Radius*cos(phi); r[1]=(*Centre_pt)[1]+Radius*sin(phi); } /// Get surface coordinate along penetrator for given point x. /// We assume that point on the surface and given point share the /// same polar angle and return that polar angle void surface_coordinate(const Vector<double>& x, Vector<double>& zeta) const { zeta[0]=atan2(x[1]-(*Centre_pt)[1],x[0]-(*Centre_pt)[0]); } /// Get rigid body displacement of reference point in penetrator. Vector<double> rigid_body_displacement() const { unsigned n=Orig_centre.size(); Vector<double> displ(n); for (unsigned i=0;i<n;i++) { displ[i]=(*Centre_pt)[i]-Orig_centre[i]; } return displ; } /// Set original centre of penetrator (for computation of rigid body /// displacement void set_original_centre(const Vector<double>& orig_centre) { Orig_centre=orig_centre; } protected: /// Pointer to centre of penetrator (origin for cylindrical polar /// coordinate system) Vector<double>* Centre_pt; /// Original centre of penetrator (origin for cylindrical polar /// coordinate system) Vector<double> Orig_centre; /// Radius of penetrator double Radius; }; /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// //====================================================================== /// Heated circular penetrator //====================================================================== class HeatedCircularPenetrator : public virtual HeatedPenetrator, public virtual CircularPenetrator { public: /// Constructor: Pass pointer to centre and radius HeatedCircularPenetrator(Vector<double>* r_c_pt, const double& r) : CircularPenetrator(r_c_pt,r) {} /// Destructor virtual ~HeatedCircularPenetrator(){} /// Get temperature on penetrator at point "associated" with /// point x using the same logic as for the position function). Here /// we assume that both points shrare the same polar angle relative /// to the centre of (circular!) penetrator double temperature(const Vector<double>& x) const { double phi=atan2(x[1]-(*Centre_pt)[1],x[0]-(*Centre_pt)[0]); return cos(phi-0.5*MathematicalConstants::Pi); } }; /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// //==================================================================== /// Namespace with helper function for polygons //==================================================================== namespace PolygonHelper { /// Check if point in inside polygon. /// Reference: http://paulbourke.net/geometry/insidepoly/ bool point_is_in_polygon(const Vector<double>& point, const Vector<Vector<double> >& polygon_vertex) { // Total number of vertices unsigned nvertex=polygon_vertex.size(); // faire: obviously polygons should ALWAYS be designed to be closed, so // such testing should only need to be done once upon implementation of // the polygon, not everytime we want to check number of intersections // hierher #ifdef PARANOID // Make sure the polygon closes exactly: double d0=polygon_vertex[nvertex-1][0]-polygon_vertex[0][0]; double d1=polygon_vertex[nvertex-1][1]-polygon_vertex[0][1]; if (sqrt(d0*d0+d1*d1)>0.0) { std::stringstream junk; junk << "First and last point of polygon don't coincide!\n" << "First point at: " << polygon_vertex[0][0] << " " << polygon_vertex[0][1] << "\n" << "Last point at: " << polygon_vertex[nvertex-1][0] << " " << polygon_vertex[nvertex-1][1] << "\n"; throw OomphLibError( junk.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } // #endif // Counter for number of intersections unsigned intersect_counter=0; //Get first vertex Vector<double> p1=polygon_vertex[0]; for (unsigned i=1;i<=nvertex;i++) { // Get second vertex by wrap-around Vector<double> p2 = polygon_vertex[i%nvertex]; if (point[1] > std::min(p1[1],p2[1])) { if (point[1] <= std::max(p1[1],p2[1])) { if (point[0] <= std::max(p1[0],p2[0])) { if (p1[1] != p2[1]) { double xintersect = (point[1]-p1[1])*(p2[0]-p1[0])/ (p2[1]-p1[1])+p1[0]; if ( (p1[0] == p2[0]) || (point[0] <= xintersect) ) { intersect_counter++; } } } } } p1 = p2; } // Even number of intersections: outside if (intersect_counter%2==0) { return false; } return true; } } /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// //====================================================================== /// Template-free base class for contact elements //====================================================================== class TemplateFreeContactElementBase : public virtual FiniteElement { public: //Constructor null pointer for traction TemplateFreeContactElementBase() : Traction_fct_pt(0), Use_isoparametric_flag_pt(0), Use_collocated_penetration_flag_pt(0), Use_collocated_contact_pressure_flag_pt(0) {} /// Destructor virtual ~TemplateFreeContactElementBase(){} /// Resulting contact force virtual void resulting_contact_force(Vector<double> &contact_force)=0; //typedef for traction function pointer, passed in from driver code typedef void (*TractionFctPt)(const double& t, const Vector<double>& x, Vector<double>& p); //Refer to this in the residuals, instead of worrying about pointers //and nullity void traction_fct(const Vector<double>& x, Vector<double>& p) { //p will be same size as x as tractions are same dim unsigned n = x.size(); if (Traction_fct_pt==0) { p.assign(n,0.0); } else { // Get time from timestepper of first node double time=node_pt(0)->time_stepper_pt()->time_pt()->time(); (*Traction_fct_pt)(time,x,p); } } /// Determine whether or not the contact pressure (p_c) should be /// represented isoparametrically (true) or with a hat function (false) bool use_isoparametric_flag() const { if (Use_isoparametric_flag_pt==0) { return true; } else { return *Use_isoparametric_flag_pt; } } /// Determine which method to use to discretise contact pressure, /// collocation (true) or integrated using the hat function (false) bool use_collocated_penetration_flag() { if (Use_collocated_penetration_flag_pt==0) { return true; } else { return *Use_collocated_penetration_flag_pt; } } /// Determine which method to use to discretise contact pressure, /// collocation (true) or integrated using the hat function (false) bool use_collocated_contact_pressure_flag() { if (Use_collocated_contact_pressure_flag_pt==0) { return true; } else { return *Use_collocated_contact_pressure_flag_pt; } } /// Access function: Pointer to body force function TractionFctPt& traction_fct_pt() {return Traction_fct_pt;} /// Access function: Pointer to body force function (const version) TractionFctPt traction_fct_pt() const {return Traction_fct_pt;} /// Access function: Pointer to flag to use isoparametric bool*& use_isoparametric_flag_pt() {return Use_isoparametric_flag_pt;} /// Access function: Pointer to flag to use isoparametric /// (const version) bool* use_isoparametric_flag_pt() const {return Use_isoparametric_flag_pt;} /// Access function: Pointer to flag to use collocated penetration bool*& use_collocated_penetration_flag_pt() {return Use_collocated_penetration_flag_pt;} /// Access function: Pointer to flag to use collocated penetration /// (const version) bool* use_collocated_penetration_flag_pt() const {return Use_collocated_penetration_flag_pt;} /// Access function: Pointer to flag to use collocated contact pressure bool*& use_collocated_contact_pressure_flag_pt() {return Use_collocated_contact_pressure_flag_pt;} /// Access function: Pointer to flag to use collocated contact pressure /// (const version) bool* use_collocated_contact_pressure_flag_pt() const {return Use_collocated_contact_pressure_flag_pt;} protected: /// Enumeration for type of penetrator data enum{Nodal_data, Nodal_position_data, External_data}; //create an instance of a traction pointer TractionFctPt Traction_fct_pt; /// Set whether or not to use isoparametric basis function for pressure bool* Use_isoparametric_flag_pt; /// Set options for basis/test functions for penetration and pressure bool* Use_collocated_penetration_flag_pt; /// Set options for basis/test functions for penetration and pressure bool* Use_collocated_contact_pressure_flag_pt; }; /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// //====================================================================== /// Base class for elements that impose contact boundary conditions /// either enforcing non-penetration (but "without stick"; default) or /// permament contact (in which case contact force can be /// positive or negative. Uses Lagrange-multiplier-like pressure /// to enforce contact/non-penetration. Almost certainly works only with /// 2D Penetrator at the moment. Specific implementation required for /// linear or nonlinear elasticity. //====================================================================== template <class ELEMENT> class SurfaceContactElementBase : public virtual FaceGeometry<ELEMENT>, //public virtual SolidFaceElement, public virtual FaceElement, public virtual TemplateFreeContactElementBase { public: /// Constructor, which takes a "bulk" element and the /// value of the index and its limit SurfaceContactElementBase(FiniteElement* const &element_pt, const int &face_index, const unsigned &id=0, const bool& called_from_refineable_constructor= false) : FaceGeometry<ELEMENT>(), FaceElement() { // By default we only to proper non-penetration (without "stick", i.e. // we don't allow negative contact pressures) Enable_stick=false; // Initialise pointer to penetrator Penetrator_pt=0; //Attach the geometrical information to the element. N.B. This function //also assigns nbulk_value from the required_nvalue of the bulk element element_pt->build_face_element(face_index,this); #ifdef PARANOID { //Check that the bulk element is not a refineable 3d element if (!called_from_refineable_constructor) { if(element_pt->dim()==3) { //Is it refineable RefineableElement* ref_el_pt= dynamic_cast<RefineableElement*>(element_pt); if(ref_el_pt!=0) { if (this->has_hanging_nodes()) { throw OomphLibError( "This face element will not work correctly if nodes are hanging.\nUse the refineable version instead. ", OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } } } } } #endif // Store the ID of the FaceElement -- this is used to distinguish // it from any others Contact_id=id; // We need one additional value for each FaceElement node: // the normal traction (Lagrange multiplier) to be // exerted onto the solid unsigned n_nod=nnode(); Vector<unsigned> n_additional_values(n_nod,1); // Now add storage for Lagrange multipliers and set the map containing // the position of the first entry of this face element's // additional values. add_additional_values(n_additional_values,id); #ifdef PARANOID // Check spatial dimension if (element_pt->dim()!=2) { //Issue a warning throw OomphLibError( "This element will almost certainly not work in non-2D problems, though it should be easy enough to upgrade... Volunteers?\n", OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif // Always use piecewise Gauss -- it "over-integrates" for isoparametric formulations // but is likely to be better for discontinuous basis fcts. //Only implemented for 1,3 (1 is from surface of 2D bulk) (3 for quadratic elements) #ifdef PARANOID // Bit hacky... Only really works for three-noded 1D elements if (n_nod!=3) { //Issue a warning throw OomphLibError( "Piecwise Gauss used here isn't appropriate for non-3-node elements.\n", OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } #endif set_integration_scheme(new PiecewiseGauss<1,3>(this->s_min(),this->s_max())); } /// Default constructor SurfaceContactElementBase(){} /// Enforce permanent contact with penetrator, allowing /// for negative contact pressures. void enable_stick() { Enable_stick=true; } // final overrider double zeta_nodal(const unsigned &n, const unsigned &k, const unsigned &i) const { return oomph::FiniteElement::zeta_nodal(n,k,i); } //Explicit overload for s_min double s_min() const { return FaceGeometry<ELEMENT>::s_min(); } double s_max() const { return FaceGeometry<ELEMENT>::s_max(); } /// Allow only proper non-penetration (without "stick", i.e. /// we don't allow negative contact pressures) void disable_stick() { Enable_stick=false; } /// Do we allow only proper non-penetration (without "stick", i.e. /// no negative contact pressures)? bool is_stick_enabled() { return Enable_stick; } /// Return the residuals void fill_in_contribution_to_residuals(Vector<double> &residuals) { fill_in_contribution_to_residuals_surface_contact(residuals); } // fiare: we are currently using FD, but this may be useful if that ever changes // some parts of the jacobian are known a priori // hierher FD the lot for now // /// Fill in contribution from Jacobian // void fill_in_contribution_to_jacobian(Vector<double> &residuals, // DenseMatrix<double> &jacobian) // { // //Call the residuals // fill_in_contribution_to_residuals_surface_contact(residuals); // //Call the generic FD jacobian calculation // FaceGeometry<ELEMENT>::fill_in_jacobian_from_solid_position_by_fd(jacobian); // //Derivs w.r.t. to any external data (e.g. during displacement control) // this->fill_in_jacobian_from_external_by_fd(residuals,jacobian); // } /// Pointer to penetrator Penetrator* penetrator_pt() const { return Penetrator_pt; } /// Set pointer to penetrator void set_penetrator_pt(Penetrator* penetrator_pt) { Penetrator_pt=penetrator_pt; Vector<std::pair<Data*,unsigned> > eq_data(Penetrator_pt->equilibrium_data()); unsigned n=eq_data.size(); Penetrator_eq_data_data_index.resize(n,-1); Penetrator_eq_data_index.resize(n,-1); Penetrator_eq_data_type.resize(n,-1); for (unsigned i=0;i<n;i++) { if (eq_data[i].first!=0) { bool is_duplicate=false; unsigned nnod=nnode(); for (unsigned j=0;j<nnod;j++) { if (eq_data[i].first==node_pt(j)) { Penetrator_eq_data_type[i]=Nodal_data; Penetrator_eq_data_data_index[i]=j; Penetrator_eq_data_index[i]=eq_data[i].second; is_duplicate=true; break; } if (eq_data[i].first== dynamic_cast<SolidNode*>(node_pt(j))->variable_position_pt()) { Penetrator_eq_data_type[i]=Nodal_position_data; Penetrator_eq_data_data_index[i]=j; Penetrator_eq_data_index[i]=eq_data[i].second; is_duplicate=true; break; } } if (!is_duplicate) { Penetrator_eq_data_type[i]=External_data; Penetrator_eq_data_data_index[i]= this->add_external_data(eq_data[i].first); Penetrator_eq_data_index[i]=eq_data[i].second; } } } } /// C_style output function void output(FILE* file_pt) {FiniteElement::output(file_pt);} /// C-style output function void output(FILE* file_pt, const unsigned &n_plot) {FiniteElement::output(file_pt,n_plot);} /// Output function void output(std::ostream &outfile) { unsigned n_plot=5; FiniteElement::output(outfile,n_plot); } /// Output function void output(std::ostream &outfile, const unsigned &n_plot) { FiniteElement::output(outfile,n_plot); } /// Shape fct for lagrange multiplier void shape_p(const Vector<double>& s, Shape &psi) const { if (this->use_isoparametric_flag()) { FaceGeometry<ELEMENT>::shape(s,psi); } else { const double smin=this->s_min(); const double smax=this->s_max(); const double sl=smin+0.25*(smax-smin); const double sr=smin+0.75*(smax-smin); if (s[0]<=sl) { psi[0]=1.0; psi[1]=0.0; psi[2]=0.0; } else if (s[0]<=sr) { psi[0]=0.0; psi[1]=1.0; psi[2]=0.0; } else { psi[0]=0.0; psi[1]=0.0; psi[2]=1.0; } } } /// Top hat function used in discretising either penetration /// or the contact pressure void shape_i(const Vector<double>& s, Shape &psi) const { const double smin=this->s_min(); const double smax=this->s_max(); const double sl=smin+0.25*(smax-smin); const double sr=smin+0.75*(smax-smin); if (s[0]<=sl) { psi[0]=1.0; psi[1]=0.0; psi[2]=0.0; } else if (s[0]<=sr) { psi[0]=0.0; psi[1]=1.0; psi[2]=0.0; } else { psi[0]=0.0; psi[1]=0.0; psi[2]=1.0; } } protected: /// Get interpolated pressure (essentially a Lagrange multiplier /// that enforces the imposed boundary motion to ensure /// non-penetration or contact) double get_interpolated_lagrange_p(const Vector<double>& s) { // Initialise pressure double p=0; //Find out how many nodes there are unsigned n_node = nnode(); //Set up memory for the shape functions Shape psi(n_node); // Evaluate shape function shape_p(s,psi); // Build up Lagrange multiplier (pressure) for (unsigned j=0;j<n_node;j++) { // Cast to a boundary node BoundaryNodeBase *bnod_pt = dynamic_cast<BoundaryNodeBase*>(node_pt(j)); // Get the index of the first nodal value associated with // this FaceElement unsigned first_index= bnod_pt->index_of_first_value_assigned_by_face_element(Contact_id); // Pressure (Lagrange multiplier) is the first (and only) additional // value created by this face element p+=node_pt(j)->value(first_index)*psi[j]; } return p; } /// Helper function that actually calculates the residuals /// This small level of indirection is required to avoid calling /// fill_in_contribution_to_residuals in fill_in_contribution_to_jacobian /// which causes all kinds of pain if overloading later on virtual void fill_in_contribution_to_residuals_surface_contact( Vector<double>& residuals)=0; /// Work out penetration of point void penetration(const Vector<double>& x, const Vector<double>& n, double& d, bool& intersection) const { Penetrator_pt->penetration(x,n,d,intersection); } /// Pointer to penetrator Penetrator* Penetrator_pt; /// ID of the contact constraint (used for the identification of /// the nodal value that corresponds to the pressure-like /// Lagrange multipliers. unsigned Contact_id; /// Do we allow only proper non-penetration (without "stick", i.e. /// no negative contact pressures)? bool Enable_stick; /// Vector containing the type of Data (labeled by the /// class' private enumeration) that is determined (via pseudo-hijacking) /// from the Penetrator's i-th equilibrium of forces equation. -1 if /// this relevant equilibrium equation is not employed to determine /// an unknown that's associated with the current element. Vector<int> Penetrator_eq_data_type; /// Vector containing the index of the Data object (e.g. the /// node number in the current element) that stores the unknown /// that is determined from the Penetrator's /// i-th equilibrium of forces equation. -1 if the relevant /// equilibrium equation is not employed to determine /// an unknown that's associated with the current element. Vector<int> Penetrator_eq_data_index; /// Vector containing the index of the value in the Data /// object (e.g. the node number in the current element) that /// stores the unknown that is determined from the Penetrator's /// i-th equilibrium of forces equation. -1 if the relevant /// equilibrium equation is not employed to determine /// an unknown that's associated with the current element. Vector<int> Penetrator_eq_data_data_index; }; /// //////////////////////////////////////////////////////////////////// /// //////////////////////////////////////////////////////////////////// /// //////////////////////////////////////////////////////////////////// //====================================================================== /// Class for elements that impose contact boundary conditions /// either enforcing non-penetration (but "without stick"; default) or /// permament contact (in which case contact force can be /// positive or negative. Uses Lagrange-multiplier-like pressure /// to enforce contact/non-penetration. Almost certainly works only with /// 2D Penetrator at the moment. Specific implementation for /// nonlinear elasticity. //====================================================================== template <class ELEMENT> class NonlinearSurfaceContactElement : public virtual SurfaceContactElementBase<ELEMENT> { public: /// Constructor, which takes a "bulk" element and the /// value of the index and its limit NonlinearSurfaceContactElement(FiniteElement* const &element_pt, const int &face_index, const unsigned &id=0, const bool& called_from_refineable_constructor= false) : // FaceGeometry<ELEMENT>(), FaceElement(), SurfaceContactElementBase<ELEMENT>(element_pt, face_index, id, called_from_refineable_constructor) {} /// Return the residuals for the SurfaceContactElement equations void fill_in_contribution_to_residuals_surface_contact(Vector<double> &residuals); /// Output function void output(std::ostream &outfile) { unsigned n_plot=5; this->output(outfile,n_plot); } /// Output function void output(std::ostream &outfile, const unsigned &n_plot) { unsigned n_dim = this->nodal_dimension(); Vector<double> x(n_dim); Vector<double> xi(n_dim); Vector<double> s(n_dim-1); Vector<double> r_pen(n_dim); Vector<double> unit_normal(n_dim); // Tecplot header info outfile << this->tecplot_zone_string(n_plot); // Loop over plot points unsigned num_plot_points=this->nplot_points(n_plot); for (unsigned iplot=0;iplot<num_plot_points;iplot++) { // Get local coordinates of plot point this->get_s_plot(iplot,n_plot,s); // Get Eulerian and Lagrangian coordinates and outer unit normal this->interpolated_x(s,x); this->interpolated_xi(s,xi); this->outer_unit_normal(s,unit_normal); // Get penetration double d=0.0; bool intersection = false; this->penetration(x,unit_normal,d,intersection); //Output the x,y,.. for(unsigned i=0;i<n_dim;i++) {outfile << x[i] << " ";}//1,2 // Penetration outfile << std::max(d,-100.0) << " ";//3 // Lagrange multiplier-like pressure double p=this->get_interpolated_lagrange_p(s); outfile << p << " "; //4 // Plot Lagrange multiplier like pressure outfile << -unit_normal[0]*p << " ";//5 outfile << -unit_normal[1]*p << " ";//6 // Plot vector from current point to boundary of penetrator double d_tmp=d; if (!intersection) d_tmp=0.0; outfile << -d_tmp*unit_normal[0] << " "; outfile << -d_tmp*unit_normal[1] << " "; // Output normal for(unsigned i=0;i<n_dim;i++) {outfile << unit_normal[i] << " ";} //Output the displacements for(unsigned i=0;i<n_dim;i++) {outfile << x[i]-xi[i] << " ";} outfile << std::endl; } // Write tecplot footer (e.g. FE connectivity lists) this->write_tecplot_zone_footer(outfile,n_plot); } /// Resulting contact force void resulting_contact_force(Vector<double> &contact_force); }; /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// //===================================================================== /// Return the residuals for the SurfaceContactElement equations //===================================================================== template<class ELEMENT> void NonlinearSurfaceContactElement<ELEMENT>:: fill_in_contribution_to_residuals_surface_contact(Vector<double> &residuals) { // Spatial dimension of problem unsigned n_dim = this->nodal_dimension(); // Contribution to contact force Vector<double> contact_force(n_dim,0.0); // Create vector of local residuals (start assembling contributions // from zero -- necessary so we can over-write pseudo-hijacked // contributions at the end. unsigned n_dof=this->ndof(); Vector<double> local_residuals(n_dof,0.0); { //Find out how many nodes there are unsigned n_node = this->nnode(); //Find out how many positional dofs there are unsigned n_position_type = this->nnodal_position_type(); //Integer to hold the local equation number int local_eqn=0; //Set up memory for the shape functions //Note that in this case, the number of lagrangian coordinates is always //equal to the dimension of the nodes Shape psi(n_node,n_position_type); DShape dpsids(n_node,n_position_type,n_dim-1); // Separate shape functions for Lagrange multiplier Shape psi_p(n_node); Vector<double> s(n_dim-1); //Seperate shape for top hat function Shape psi_i(n_node); // Contribution to integrated pressure Vector<double> pressure_integral(n_node,0.0); // Contribution to weighted penetration integral Vector<double> penetration_integral(n_node,0.0); //Set the value of n_intpt unsigned n_intpt = this->integral_pt()->nweight(); //Loop over the integration points for(unsigned ipt=0;ipt<n_intpt;ipt++) { //Get the integral weight double w = this->integral_pt()->weight(ipt); //Only need to call the local derivatives this->dshape_local_at_knot(ipt,psi,dpsids); // Separate shape function for Lagrange multiplier for(unsigned i=0;i<n_dim-1;i++) { s[i] = this->integral_pt()->knot(ipt,i); } this->shape_p(s,psi_p); //If we are using collocation for both, then we don't need to set up the integration shape if(!(this->use_collocated_penetration_flag() && this->use_collocated_contact_pressure_flag())) { this->shape_i(s,psi_i); } // Interpolated Lagrange multiplier (pressure acting on solid // to enforce melting) double interpolated_lambda_p=0.0; //Calculate the Eulerian and Lagrangian coordinates Vector<double> interpolated_x(n_dim,0.0); //Also calculate the surface Vectors (derivatives wrt local coordinates) DenseMatrix<double> interpolated_A(n_dim-1,n_dim,0.0); //Calculate displacements and derivatives for(unsigned l=0;l<n_node;l++) { // Cast to a boundary node BoundaryNodeBase *bnod_pt = dynamic_cast<BoundaryNodeBase*>(this->node_pt(l)); // Get the index of the nodal value associated with // this FaceElement unsigned first_index= bnod_pt->index_of_first_value_assigned_by_face_element(this->Contact_id); // Add to Lagrange multiplier (acting as pressure on solid // to enforce motion to ensure non-penetration) interpolated_lambda_p+=this->node_pt(l)->value(first_index)*psi_p[l]; //Loop over positional dofs for(unsigned k=0;k<n_position_type;k++) { //Loop over displacement components (deformed position) for(unsigned i=0;i<n_dim;i++) { //Calculate the Eulerian and Lagrangian positions interpolated_x[i] += this->nodal_position_gen(l,this->bulk_position_type(k),i)*psi(l,k); //Loop over LOCAL derivative directions, to calculate the tangent(s) for(unsigned j=0;j<n_dim-1;j++) { interpolated_A(j,i) += this->nodal_position_gen(l,this->bulk_position_type(k),i)*dpsids(l,k,j); } } } } //Now find the local deformed metric tensor from the tangent Vectors DenseMatrix<double> A(n_dim-1); for(unsigned i=0;i<n_dim-1;i++) { for(unsigned j=0;j<n_dim-1;j++) { //Initialise surface metric tensor to zero A(i,j) = 0.0; //Take the dot product for(unsigned k=0;k<n_dim;k++) { A(i,j) += interpolated_A(i,k)*interpolated_A(j,k); } } } //Get the outer unit normal Vector<double> interpolated_normal(n_dim); this->outer_unit_normal(ipt,interpolated_normal); //Find the determinant of the metric tensor double Adet =0.0; switch(n_dim) { case 2: Adet = A(0,0); break; case 3: Adet = A(0,0)*A(1,1) - A(0,1)*A(1,0); break; default: throw OomphLibError( "Wrong dimension in SurfaceContactElement", "SurfaceContactElement::fill_in_contribution_to_residuals()", OOMPH_EXCEPTION_LOCATION); } //Premultiply the weights and the square-root of the determinant of //the metric tensor double W = w*sqrt(Adet); // Calculate the "load" -- Lagrange multiplier acts as traction to // to enforce required surface displacement Vector<double> traction(n_dim); for (unsigned i=0;i<n_dim;i++) { traction[i]=-interpolated_lambda_p*interpolated_normal[i]; } // Accumulate contribution to total contact force for(unsigned i=0;i<n_dim;i++) { contact_force[i]+=traction[i]*W; } //=====LOAD TERMS FROM PRINCIPLE OF VIRTUAL DISPLACEMENTS======== //Loop over the test functions, nodes of the element for(unsigned l=0;l<n_node;l++) { //Loop of types of dofs for(unsigned k=0;k<n_position_type;k++) { //Loop over the displacement components for(unsigned i=0;i<n_dim;i++) { local_eqn = this->position_local_eqn(l,this->bulk_position_type(k),i); /*IF it's not a boundary condition*/ if(local_eqn >= 0) { //Add the loading terms to the residuals local_residuals[local_eqn] -= traction[i]*psi(l,k)*W; } } } //End of if not boundary condition } //End of loop over shape functions //faire!!!! //=====CONTRIBUTION TO CONTACT PRESSURE/LAGRANGE MULTIPLIER EQNS ======== if(!this->use_collocated_contact_pressure_flag()) { //Loop over the nodes for(unsigned l=0;l<n_node;l++) { // Contribution to integrated pressure pressure_integral[l]+=interpolated_lambda_p*psi_i[l]*W; } } if(!this->use_collocated_penetration_flag()) { //Get local penetration double d = 0.0; bool intersection = false; this->penetration(interpolated_x,interpolated_normal,d,intersection); if(!intersection) { //if there is no intersection then we set d as -infinity d = -DBL_MAX; } //Loop over the nodes for(unsigned l=0;l<n_node;l++) { // Contribution to integrated penetration penetration_integral[l]+=d*psi_i[l]*W; } } } //End of loop over integration points // Determine contact pressure/Lagrange multiplier: //------------------------------------------------ // Storage for nodal coordinate Vector<double> x(n_dim); //Loop over the nodes for(unsigned l=0;l<n_node;l++) { // get the node pt Node* nod_pt = this->node_pt(l); // Cast to a boundary node BoundaryNodeBase *bnod_pt = dynamic_cast<BoundaryNodeBase*>(nod_pt); // Get the index of the first nodal value associated with // this FaceElement unsigned first_index= bnod_pt->index_of_first_value_assigned_by_face_element(this->Contact_id); // Equation for Lagrange multiplier local_eqn = this->nodal_local_eqn(l,first_index); /*IF it's not a boundary condition*/ if(local_eqn >= 0) { //Set to integrated discretisations for now double d=penetration_integral[l]; double contact_pressure=pressure_integral[l]; //overwrite appropriate measure if using collocation if(this->use_collocated_penetration_flag() || this->use_collocated_contact_pressure_flag()) {//If so, we are gonna need information about the node // Nodal position x[0]=nod_pt->x(0); x[1]=nod_pt->x(1); // Get outer unit normal Vector<double> s(1); this->local_coordinate_of_node(l,s); Vector<double> unit_normal(2); this->outer_unit_normal(s,unit_normal); if(this->use_collocated_penetration_flag()) { // Get penetration bool intersection = false; this->penetration(x,unit_normal,d,intersection); //If there is no intersection, d = -max, ie the penetrator is infinitely far away if(!intersection) { d = -DBL_MAX; } } if(this->use_collocated_contact_pressure_flag()) { contact_pressure=nod_pt->value(first_index); } } //Now that we have the appropriate discretisations of penetration and contact pressure, //use the semi-smooth residual scheme // Contact/non-penetration residual if (this->Enable_stick) { // Enforce contact local_residuals[local_eqn]-=d; } else { // Piecewise linear variation for non-penetration constraint if (-d>contact_pressure) { local_residuals[local_eqn]+=contact_pressure; } else { local_residuals[local_eqn]-=d; } } } } } // faire: we need to go through this // Now deal with the penetrator equilibrium equations (if any!) unsigned n=this->Penetrator_eq_data_type.size(); for (unsigned i=0;i<n;i++) { if (this->Penetrator_eq_data_type[i]>=0) { switch(unsigned(this->Penetrator_eq_data_type[i])) { case TemplateFreeContactElementBase::External_data: { int local_eqn=this->external_local_eqn( this->Penetrator_eq_data_data_index[i], this->Penetrator_eq_data_index[i]); if (local_eqn>=0) { local_residuals[local_eqn]+=contact_force[i]; } } break; case TemplateFreeContactElementBase::Nodal_position_data: { // position type (dummy -- hierher paranoid check) unsigned k=0; int local_eqn=this->position_local_eqn( this->Penetrator_eq_data_data_index[i],k, this->Penetrator_eq_data_index[i]); if (local_eqn>=0) { local_residuals[local_eqn]+=contact_force[i]; } } break; case TemplateFreeContactElementBase::Nodal_data: { int local_eqn=this->nodal_local_eqn( this->Penetrator_eq_data_data_index[i], this->Penetrator_eq_data_index[i]); if (local_eqn>=0) { local_residuals[local_eqn]+=contact_force[i]; } } break; default: std::stringstream junk; junk << "Never get here: " << "unsigned(Penetrator_eq_data_type[i]) = " << unsigned(this->Penetrator_eq_data_type[i]); throw OomphLibError( junk.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } } } // Now add local contribution to existing entries for (unsigned j=0;j<n_dof;j++) { residuals[j]+=local_residuals[j]; } } //===================================================================== /// Resulting contact force //===================================================================== template<class ELEMENT> void NonlinearSurfaceContactElement<ELEMENT>::resulting_contact_force( Vector<double> &contact_force) { //Find out how many nodes there are unsigned n_node = this->nnode(); //Find out how many positional dofs there are unsigned n_position_type = this->nnodal_position_type(); //Find out the dimension of the node unsigned n_dim = this->nodal_dimension(); // Initialise for (unsigned i=0;i<n_dim;i++) { contact_force[i]=0.0; } //Set up memory for the shape functions //Note that in this case, the number of lagrangian coordinates is always //equal to the dimension of the nodes Shape psi(n_node,n_position_type); DShape dpsids(n_node,n_position_type,n_dim-1); // Separate shape functions for Lagrange multiplier Shape psi_p(n_node); Vector<double> s(n_dim-1); //Set the value of n_intpt unsigned n_intpt = this->integral_pt()->nweight(); //Loop over the integration points for(unsigned ipt=0;ipt<n_intpt;ipt++) { //Get the integral weight double w = this->integral_pt()->weight(ipt); //Only need to call the local derivatives this->dshape_local_at_knot(ipt,psi,dpsids); // Separate shape function for Lagrange multiplier for(unsigned i=0;i<n_dim-1;i++) { s[i] = this->integral_pt()->knot(ipt,i); } this->shape_p(s,psi_p); // Interpolated Lagrange multiplier (pressure acting on solid // to enforce melting) double interpolated_lambda_p=0.0; //Calculate the Eulerian and Lagrangian coordinates Vector<double> interpolated_x(n_dim,0.0); //Also calculate the surface Vectors (derivatives wrt local coordinates) DenseMatrix<double> interpolated_A(n_dim-1,n_dim,0.0); //Calculate displacements and derivatives for(unsigned l=0;l<n_node;l++) { // Cast to a boundary node BoundaryNodeBase *bnod_pt = dynamic_cast<BoundaryNodeBase*>(this->node_pt(l)); // Get the index of the nodal value associated with // this FaceElement unsigned first_index= bnod_pt->index_of_first_value_assigned_by_face_element(this->Contact_id); // Add to Lagrange multiplier (acting as pressure on solid // to enforce motion to ensure non-penetration) interpolated_lambda_p+=this->node_pt(l)->value(first_index)*psi_p[l]; //Loop over positional dofs for(unsigned k=0;k<n_position_type;k++) { //Loop over displacement components (deformed position) for(unsigned i=0;i<n_dim;i++) { //Calculate the Eulerian and Lagrangian positions interpolated_x[i] += this->nodal_position_gen(l,this->bulk_position_type(k),i)*psi(l,k); //Loop over LOCAL derivative directions, to calculate the tangent(s) for(unsigned j=0;j<n_dim-1;j++) { interpolated_A(j,i) += this->nodal_position_gen(l,this->bulk_position_type(k),i)*dpsids(l,k,j); } } } } //Now find the local deformed metric tensor from the tangent Vectors DenseMatrix<double> A(n_dim-1); for(unsigned i=0;i<n_dim-1;i++) { for(unsigned j=0;j<n_dim-1;j++) { //Initialise surface metric tensor to zero A(i,j) = 0.0; //Take the dot product for(unsigned k=0;k<n_dim;k++) { A(i,j) += interpolated_A(i,k)*interpolated_A(j,k); } } } //Get the outer unit normal Vector<double> interpolated_normal(n_dim); this->outer_unit_normal(ipt,interpolated_normal); //Find the determinant of the metric tensor double Adet =0.0; switch(n_dim) { case 2: Adet = A(0,0); break; case 3: Adet = A(0,0)*A(1,1) - A(0,1)*A(1,0); break; default: throw OomphLibError( "Wrong dimension in SurfaceContactElement", "SurfaceContactElement::contact_force()", OOMPH_EXCEPTION_LOCATION); } //Premultiply the weights and the square-root of the determinant of //the metric tensor double W = w*sqrt(Adet); // Calculate the "load" -- Lagrange multiplier acts as traction to // to enforce required surface displacement Vector<double> traction(n_dim); for (unsigned i=0;i<n_dim;i++) { traction[i]=-interpolated_lambda_p*interpolated_normal[i]; } // Add to resulting force for (unsigned i=0;i<n_dim;i++) { contact_force[i]+=traction[i]*W; } } } /// //////////////////////////////////////////////////////////////////// /// //////////////////////////////////////////////////////////////////// /// //////////////////////////////////////////////////////////////////// //====================================================================== /// Class for elements that impose contact boundary conditions /// either enforcing non-penetration (but "without stick"; default) or /// permament contact (in which case contact force can be /// positive or negative. Uses Lagrange-multiplier-like pressure /// to enforce contact/non-penetration. Almost certainly works only with /// 2D Penetrator at the moment. Specific implementation for /// linear elasticity. //====================================================================== template <class ELEMENT> class LinearSurfaceContactElement : public virtual SurfaceContactElementBase<ELEMENT> { public: /// Constructor, which takes a "bulk" element and the /// value of the index and its limit LinearSurfaceContactElement(FiniteElement* const &element_pt, const int &face_index, const unsigned &id=0, const bool& called_from_refineable_constructor= false) : // FaceGeometry<ELEMENT>(), FaceElement(), SurfaceContactElementBase<ELEMENT>(element_pt, face_index, id, called_from_refineable_constructor) { //Find the dimension of the problem unsigned n_dim = element_pt->nodal_dimension(); //Find the index at which the displacemenet unknowns are stored ELEMENT* cast_element_pt = dynamic_cast<ELEMENT*>(element_pt); this->U_index_linear_elasticity_traction.resize(n_dim); for(unsigned i=0;i<n_dim;i++) { this->U_index_linear_elasticity_traction[i] = cast_element_pt->u_index_linear_elasticity(i); } } /// Default constructor LinearSurfaceContactElement(){} /// Return the residuals for the SurfaceContactElement equations void fill_in_contribution_to_residuals_surface_contact(Vector<double>& residuals); /// Output function void output(std::ostream &outfile) { unsigned n_plot=5; this->output(outfile,n_plot); } /// Output function void output(std::ostream &outfile, const unsigned &n_plot) { unsigned n_dim = this->nodal_dimension(); Vector<double> x(n_dim); Vector<double> disp(n_dim); Vector<double> x_def(n_dim); Vector<double> s(n_dim-1); Vector<double> r_pen(n_dim); Vector<double> unit_normal(n_dim); // Tecplot header info outfile << this->tecplot_zone_string(n_plot); // Loop over plot points unsigned num_plot_points=this->nplot_points(n_plot); for (unsigned iplot=0;iplot<num_plot_points;iplot++) { // Get local coordinates of plot point this->get_s_plot(iplot,n_plot,s); // Get coordinates and outer unit normal this->interpolated_x(s,x); this->outer_unit_normal(s,unit_normal); // Displacement this->interpolated_u_linear_elasticity(s,disp); // Deformed position for(unsigned i=0;i<n_dim;i++) { x_def[i]=x[i]+disp[i]; } // Get penetration based on deformed position double d= 0.0; bool intersection = false; this->penetration(x_def,unit_normal,d,intersection); //Output the x,y,.. for(unsigned i=0;i<n_dim;i++) {outfile << x[i] << " ";} // col 1,2 // Penetration outfile << std::max(d,-100.0) << " "; // col 3 // Lagrange multiplier-like pressure double p=this->get_interpolated_lagrange_p(s); outfile << p << " "; // col 4 // Plot Lagrange multiplier like pressure outfile << -unit_normal[0]*p << " "; // col 5 outfile << -unit_normal[1]*p << " "; // col 6 // Plot vector from current point to boundary of penetrator double d_tmp=d; if (!intersection) d_tmp=0.0; outfile << -d_tmp*unit_normal[0] << " "; // col 7 outfile << -d_tmp*unit_normal[1] << " "; // col 8 // Output normal for(unsigned i=0;i<n_dim;i++) {outfile << unit_normal[i] << " ";} // col 9, 10 //Output the displacements for(unsigned i=0;i<n_dim;i++) { outfile << disp[i] << " "; // col 11, 12 } //Output the deformed position for(unsigned i=0;i<n_dim;i++) { outfile << x_def[i] << " "; // col 13, 14 } outfile << std::endl; } // Write tecplot footer (e.g. FE connectivity lists) this->write_tecplot_zone_footer(outfile,n_plot); } /// Resulting contact force void resulting_contact_force(Vector<double> &contact_force); protected: /// Compute vector of FE interpolated displacement u at local coordinate s void interpolated_u_linear_elasticity(const Vector<double> &s, Vector<double>& disp) const { //Find the dimension of the problem unsigned n_dim = this->nodal_dimension(); //Find number of nodes unsigned n_node = this->nnode(); //Local shape function Shape psi(n_node); //Find values of shape function this->shape(s,psi); // Get displacements for (unsigned i=0;i<n_dim;i++) { //Index at which the nodal value is stored unsigned u_nodal_index = this->U_index_linear_elasticity_traction[i]; //Initialise value of u disp[i] = 0.0; //Loop over the local nodes and sum for(unsigned l=0;l<n_node;l++) { disp[i] += this->nodal_value(l,u_nodal_index)*psi[l]; } } } /// Index at which the i-th displacement component is stored Vector<unsigned> U_index_linear_elasticity_traction; }; /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// //===================================================================== /// Return the residuals for the LinearSurfaceContactElement equations //===================================================================== template<class ELEMENT> void LinearSurfaceContactElement<ELEMENT>:: fill_in_contribution_to_residuals_surface_contact(Vector<double> &residuals) { // Spatial dimension of problem unsigned n_dim = this->nodal_dimension(); // Contribution to contact force Vector<double> contact_force(n_dim,0.0); // Create vector of local residuals (start assembling contributions // from zero -- necessary so we can over-write pseudo-hijacked // contributions at the end. unsigned n_dof=this->ndof(); Vector<double> local_residuals(n_dof,0.0); { //Find out how many nodes there are unsigned n_node = this->nnode(); //Integer to hold the local equation number int local_eqn=0; //Set up memory for the shape functions Shape psi(n_node); DShape dpsids(n_node,n_dim-1); // Separate shape functions for Lagrange multiplier Shape psi_p(n_node); Vector<double> s(n_dim-1); //Seperate shape for top hat function Shape psi_i(n_node); // Contribution to integrated pressure Vector<double> pressure_integral(n_node,0.0); // Contribution to weighted penetration integral Vector<double> penetration_integral(n_node,0.0); // Deformed position Vector<double> x_def(n_dim,0.0); //Set the value of n_intpt unsigned n_intpt = this->integral_pt()->nweight(); //Loop over the integration points for(unsigned ipt=0;ipt<n_intpt;ipt++) { //Get the integral weight double w = this->integral_pt()->weight(ipt); //Only need to call the local derivatives this->dshape_local_at_knot(ipt,psi,dpsids); // Separate shape function for Lagrange multiplier for(unsigned i=0;i<n_dim-1;i++) { s[i] = this->integral_pt()->knot(ipt,i); } this->shape_p(s,psi_p); //If we are using collocation for both, then we don't need to set up the integration shape if(!(this->use_collocated_penetration_flag() && this->use_collocated_contact_pressure_flag())){ this->shape_i(s,psi_i); } // Interpolated Lagrange multiplier (pressure acting on solid) double interpolated_lambda_p=0.0; // Displacement Vector<double> disp(n_dim,0.0); //Calculate the coordinates Vector<double> interpolated_x(n_dim,0.0); //Also calculate the surface Vectors (derivatives wrt local coordinates) DenseMatrix<double> interpolated_A(n_dim-1,n_dim,0.0); //Calculate displacements and derivatives for(unsigned l=0;l<n_node;l++) { // Cast to a boundary node BoundaryNodeBase *bnod_pt = dynamic_cast<BoundaryNodeBase*>(this->node_pt(l)); // Get the index of the nodal value associated with // this FaceElement unsigned first_index= bnod_pt->index_of_first_value_assigned_by_face_element(this->Contact_id); // Add to Lagrange multiplier (acting as pressure on solid // to enforce motion to ensure non-penetration) interpolated_lambda_p+=this->node_pt(l)->value(first_index)*psi_p[l]; //Loop over displacement components for(unsigned i=0;i<n_dim;i++) { //Calculate the positions interpolated_x[i]+=this->nodal_position(l,i)*psi(l); //Index at which the displacement nodal value is stored unsigned u_nodal_index=this->U_index_linear_elasticity_traction[i]; disp[i] += this->nodal_value(l,u_nodal_index)*psi(l); // Loop over LOCAL derivative directions, to calculate the // tangent(s) for(unsigned j=0;j<n_dim-1;j++) { interpolated_A(j,i)+=this->nodal_position(l,i)*dpsids(l,j); } } //std::cout<<interpolated_lambda_p; //test for no contact } //Now find the local deformed metric tensor from the tangent Vectors DenseMatrix<double> A(n_dim-1); for(unsigned i=0;i<n_dim-1;i++) { for(unsigned j=0;j<n_dim-1;j++) { //Initialise surface metric tensor to zero A(i,j) = 0.0; //Take the dot product for(unsigned k=0;k<n_dim;k++) { A(i,j) += interpolated_A(i,k)*interpolated_A(j,k); } } } //Get the outer unit normal Vector<double> interpolated_normal(n_dim); this->outer_unit_normal(ipt,interpolated_normal); //Find the determinant of the metric tensor double Adet =0.0; switch(n_dim) { case 2: Adet = A(0,0); break; case 3: Adet = A(0,0)*A(1,1) - A(0,1)*A(1,0); break; default: throw OomphLibError( "Wrong dimension in SurfaceContactElement", "LinearSurfaceContactElement::fill_in_contribution_to_residuals()", OOMPH_EXCEPTION_LOCATION); } //Premultiply the weights and the square-root of the determinant of //the metric tensor double W = w*sqrt(Adet); // Calculate the "load" -- Lagrange multiplier acts as traction to // to enforce required surface displacement and the // deformed position Vector<double> traction(n_dim); for (unsigned i=0;i<n_dim;i++) { traction[i]=-interpolated_lambda_p*interpolated_normal[i]; x_def[i]=interpolated_x[i]+disp[i]; } // Accumulate contribution to total contact force for(unsigned i=0;i<n_dim;i++) { contact_force[i]+=traction[i]*W; } //=====LOAD TERMS FROM PRINCIPLE OF VIRTUAL DISPLACEMENTS AND BOUNDARY CONDITIONS======== //holder for externally imposed traction Vector<double> p(n_dim,0.0); //Get vector of traction from the function which has been passed in this->traction_fct(interpolated_x,p); //Loop over the test functions, nodes of the element for(unsigned l=0;l<n_node;l++) { //Loop over the displacement components for(unsigned i=0;i<n_dim;i++) { local_eqn = this->nodal_local_eqn(l,i); /*IF it's not a boundary condition*/ if(local_eqn >= 0) { //Add the loading terms from penetrator and imposed externally to the residuals local_residuals[local_eqn] -= (traction[i]+p[i])*psi(l)*W; } //End of if not boundary condition } } //End of loop over shape functions //=====CONTRIBUTION TO CONTACT PRESSURE/LAGRANGE MULTIPLIER EQNS ======== if(!this->use_collocated_contact_pressure_flag()) { //Loop over the nodes for(unsigned l=0;l<n_node;l++) { // Contribution to integrated pressure pressure_integral[l]+=interpolated_lambda_p*psi_i[l]*W; } } if(!this->use_collocated_penetration_flag()) { //Get local penetration double d = 0.0; bool intersection = false; this->penetration(x_def,interpolated_normal,d,intersection); if(!intersection) { //if there is no intersection then we set d as -infinity d = -DBL_MAX; } //Loop over the nodes for(unsigned l=0;l<n_node;l++) { // Contribution to integrated penetration penetration_integral[l]+=d*psi_i[l]*W; } } } //End of loop over integration points // Determine contact pressure/Lagrange multiplier //----------------------------------------------- // Storage for nodal coordinate Vector<double> x(n_dim); //Loop over the nodes for(unsigned l=0;l<n_node;l++) { // get the node pt Node* nod_pt = this->node_pt(l); // Cast to a boundary node BoundaryNodeBase *bnod_pt = dynamic_cast<BoundaryNodeBase*>(nod_pt); // Get the index of the first nodal value associated with // this FaceElement unsigned first_index= bnod_pt->index_of_first_value_assigned_by_face_element(this->Contact_id); // Equation for Lagrange multiplier local_eqn = this->nodal_local_eqn(l,first_index); /*IF it's not a boundary condition*/ if(local_eqn >= 0) { //Set to integrated discretisations for now double d=penetration_integral[l]; double contact_pressure=pressure_integral[l]; //overwrite appropriate measure if using collocation if(this->use_collocated_penetration_flag() || this->use_collocated_contact_pressure_flag()) {//If so, we are gonna need information about the node // Nodal position x[0]=nod_pt->x(0); x[1]=nod_pt->x(1); // Get outer unit normal Vector<double> s(1); this->local_coordinate_of_node(l,s); Vector<double> unit_normal(2); this->outer_unit_normal(s,unit_normal); // Displacement Vector<double> disp(2); this->interpolated_u_linear_elasticity(s,disp); // Deformed position Vector<double> x_def(2); x_def[0]=x[0]+disp[0]; x_def[1]=x[1]+disp[1]; if(this->use_collocated_penetration_flag()) { // Get penetration bool intersection = false; this->penetration(x_def,unit_normal,d,intersection); //If there is no intersection, d = -max, ie the penetrator is infinitely far away if(!intersection) { d = -DBL_MAX; } } if(this->use_collocated_contact_pressure_flag()) { contact_pressure=nod_pt->value(first_index); } } //Now that we have the appropriate discretisations of penetration and contact pressure, //use the semi-smooth residual scheme // Contact/non-penetration residual if (this->Enable_stick) { // Enforce contact local_residuals[local_eqn]-=d; } else { // Piecewise linear variation for non-penetration constraint if (-d>contact_pressure) { local_residuals[local_eqn]+=contact_pressure; } else { local_residuals[local_eqn]-=d; } } } } } //faire: equilibrium again // Now deal with the penetrator equilibrium equations (if any!) unsigned n=this->Penetrator_eq_data_type.size(); for (unsigned i=0;i<n;i++) { if (this->Penetrator_eq_data_type[i]>=0) { switch(unsigned(this->Penetrator_eq_data_type[i])) { case TemplateFreeContactElementBase::External_data: { int local_eqn=this->external_local_eqn( this->Penetrator_eq_data_data_index[i], this->Penetrator_eq_data_index[i]); if (local_eqn>=0) { local_residuals[local_eqn]+=contact_force[i]; } } break; // hierher this case should not arise because the nodal positions // will not be affected by the force balance. /* case TemplateFreeContactElementBase::Nodal_position_data: */ /* { */ /* // position type (dummy -- hierher paranoid check) */ /* unsigned k=0; */ /* int local_eqn=position_local_eqn( */ /* this->Penetrator_eq_data_data_index[i],k, */ /* this->Penetrator_eq_data_index[i]); */ /* if (local_eqn>=0) */ /* { */ /* local_residuals[local_eqn]=contact_force[i]; */ /* } */ /* } */ /* break; */ case TemplateFreeContactElementBase::Nodal_data: { int local_eqn=this->nodal_local_eqn( this->Penetrator_eq_data_data_index[i], this->Penetrator_eq_data_index[i]); if (local_eqn>=0) { local_residuals[local_eqn]+=contact_force[i]; } } break; default: std::stringstream junk; junk << "Never get here: " << "unsigned(Penetrator_eq_data_type[i]) = " << unsigned(this->Penetrator_eq_data_type[i]); throw OomphLibError( junk.str(), OOMPH_CURRENT_FUNCTION, OOMPH_EXCEPTION_LOCATION); } } } // Now add local contribution to existing entries for (unsigned j=0;j<n_dof;j++) { residuals[j]+=local_residuals[j]; } } //===================================================================== /// Resulting contact force //===================================================================== template<class ELEMENT> void LinearSurfaceContactElement<ELEMENT>::resulting_contact_force( Vector<double> &contact_force) { //Find out how many nodes there are unsigned n_node = this->nnode(); //Find out the dimension of the node unsigned n_dim = this->nodal_dimension(); // Initialise for (unsigned i=0;i<n_dim;i++) { contact_force[i]=0.0; } //Set up memory for the shape functions Shape psi(n_node); DShape dpsids(n_node,n_dim-1); // Separate shape functions for Lagrange multiplier Shape psi_p(n_node); Vector<double> s(n_dim-1); //Set the value of n_intpt unsigned n_intpt = this->integral_pt()->nweight(); //Loop over the integration points for(unsigned ipt=0;ipt<n_intpt;ipt++) { //Get the integral weight double w = this->integral_pt()->weight(ipt); //Only need to call the local derivatives this->dshape_local_at_knot(ipt,psi,dpsids); // Separate shape function for Lagrange multiplier for(unsigned i=0;i<n_dim-1;i++) { s[i] = this->integral_pt()->knot(ipt,i); } this->shape_p(s,psi_p); // Interpolated Lagrange multiplier (pressure acting on solid // to enforce melting) double interpolated_lambda_p=0.0; //Calculate the coordinates Vector<double> interpolated_x(n_dim,0.0); // Displacement Vector<double> disp(n_dim,0.0); //Also calculate the surface Vectors (derivatives wrt local coordinates) DenseMatrix<double> interpolated_A(n_dim-1,n_dim,0.0); //Calculate displacements and derivatives for(unsigned l=0;l<n_node;l++) { // Cast to a boundary node BoundaryNodeBase *bnod_pt = dynamic_cast<BoundaryNodeBase*>(this->node_pt(l)); // Get the index of the nodal value associated with // this FaceElement unsigned first_index= bnod_pt->index_of_first_value_assigned_by_face_element(this->Contact_id); // Add to Lagrange multiplier (acting as pressure on solid // to enforce motion to ensure non-penetration) interpolated_lambda_p+=this->node_pt(l)->value(first_index)*psi_p[l]; //Loop over displacement components for(unsigned i=0;i<n_dim;i++) { //Calculate the positions interpolated_x[i] += this->nodal_position(l,i)*psi(l); //Index at which the displacement nodal value is stored unsigned u_nodal_index=this->U_index_linear_elasticity_traction[i]; disp[i] += this->nodal_value(l,u_nodal_index)*psi(l); //Loop over LOCAL derivative directions, to calculate the tangent(s) for(unsigned j=0;j<n_dim-1;j++) { interpolated_A(j,i) += this->nodal_position(l,i)*dpsids(l,j); } } } //Now find the local deformed metric tensor from the tangent Vectors DenseMatrix<double> A(n_dim-1); for(unsigned i=0;i<n_dim-1;i++) { for(unsigned j=0;j<n_dim-1;j++) { //Initialise surface metric tensor to zero A(i,j) = 0.0; //Take the dot product for(unsigned k=0;k<n_dim;k++) { A(i,j) += interpolated_A(i,k)*interpolated_A(j,k); } } } //Get the outer unit normal Vector<double> interpolated_normal(n_dim); this->outer_unit_normal(ipt,interpolated_normal); //Find the determinant of the metric tensor double Adet =0.0; switch(n_dim) { case 2: Adet = A(0,0); break; case 3: Adet = A(0,0)*A(1,1) - A(0,1)*A(1,0); break; default: throw OomphLibError( "Wrong dimension in SurfaceContactElement", "SurfaceContactElement::contact_force()", OOMPH_EXCEPTION_LOCATION); } //Premultiply the weights and the square-root of the determinant of //the metric tensor double W = w*sqrt(Adet); // Calculate the "load" -- Lagrange multiplier acts as traction to // to enforce required surface displacement Vector<double> traction(n_dim); for (unsigned i=0;i<n_dim;i++) { traction[i]=-interpolated_lambda_p*interpolated_normal[i]; } // Add to resulting force for (unsigned i=0;i<n_dim;i++) { contact_force[i]+=traction[i]*W; } } } /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// } #endif
30.157312
133
0.59898
6ab9145d4e85e201b8addff758599780508973e5
571
h
C
ios/CustomCode/Modules/Restore/Controller/OKFindFollowingWalletController.h
huazhouwang/electrum
3d7cf4aa05593ea71caec264065a1116b25324a6
[ "MIT" ]
null
null
null
ios/CustomCode/Modules/Restore/Controller/OKFindFollowingWalletController.h
huazhouwang/electrum
3d7cf4aa05593ea71caec264065a1116b25324a6
[ "MIT" ]
null
null
null
ios/CustomCode/Modules/Restore/Controller/OKFindFollowingWalletController.h
huazhouwang/electrum
3d7cf4aa05593ea71caec264065a1116b25324a6
[ "MIT" ]
null
null
null
// // OKFindFollowingWalletController.h // OneKey // // Created by xiaoliang on 2020/11/16. // Copyright © 2020 OneKey. All rights reserved.. // #import "BaseViewController.h" #import "OKCreateResultModel.h" #import "OKCreateResultWalletInfoModel.h" NS_ASSUME_NONNULL_BEGIN @interface OKFindFollowingWalletController : BaseViewController @property (nonatomic,strong)OKCreateResultModel *createResultModel; @property (nonatomic,copy)NSString *pwd; @property (nonatomic,assign)BOOL isInit; + (instancetype)findFollowingWalletController; @end NS_ASSUME_NONNULL_END
23.791667
67
0.803853
6ad412477f09c8886216c61fcc9c01fdc49d7124
3,208
h
C
hazelcast/include/hazelcast/client/topic/impl/reliable/ReliableTopicExecutor.h
yuce/hazelcast-cpp-client
027d56df46d770d8e2225693e4bbc91703451757
[ "Apache-2.0" ]
null
null
null
hazelcast/include/hazelcast/client/topic/impl/reliable/ReliableTopicExecutor.h
yuce/hazelcast-cpp-client
027d56df46d770d8e2225693e4bbc91703451757
[ "Apache-2.0" ]
null
null
null
hazelcast/include/hazelcast/client/topic/impl/reliable/ReliableTopicExecutor.h
yuce/hazelcast-cpp-client
027d56df46d770d8e2225693e4bbc91703451757
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <memory> #include <atomic> #include <stdint.h> #include <thread> #include "hazelcast/client/ringbuffer.h" #include "hazelcast/util/BlockingConcurrentQueue.h" #include "hazelcast/client/execution_callback.h" #include "hazelcast/client/topic/impl/reliable/ReliableTopicMessage.h" #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) #pragma warning(push) #pragma warning(disable: 4251) //for dll export #endif namespace hazelcast { namespace client { namespace topic { namespace impl { namespace reliable { class HAZELCAST_API ReliableTopicExecutor { public: enum message_type { GET_ONE_MESSAGE, CANCEL }; struct Message { message_type type; int64_t sequence; int32_t max_count; std::shared_ptr<execution_callback<rb::read_result_set>> callback; }; ReliableTopicExecutor(std::shared_ptr<ringbuffer> rb, logger &lg); virtual ~ReliableTopicExecutor(); /** * Not thread safe method */ void start(); bool stop(); void execute(Message m); private: class Task { public: Task(std::shared_ptr<ringbuffer> rb, util::BlockingConcurrentQueue<Message> &q, std::atomic<bool> &shutdown); virtual void run(); virtual std::string get_name() const; private: std::shared_ptr<ringbuffer> rb_; util::BlockingConcurrentQueue<Message> &q_; std::atomic<bool> &shutdown_; }; std::shared_ptr<ringbuffer> ringbuffer_; std::thread runner_thread_; util::BlockingConcurrentQueue<Message> q_; std::atomic<bool> shutdown_; }; } } } } } #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) #pragma warning(pop) #endif
32.734694
107
0.515898
591365a8701d133d3d23d619870096a5f6cc7ef1
1,701
h
C
util/system/pipe.h
jjzhang166/balancer
84addf52873d8814b8fd30289f2fcfcec570c151
[ "Unlicense" ]
39
2015-03-12T19:49:24.000Z
2020-11-11T09:58:15.000Z
util/system/pipe.h
jjzhang166/balancer
84addf52873d8814b8fd30289f2fcfcec570c151
[ "Unlicense" ]
null
null
null
util/system/pipe.h
jjzhang166/balancer
84addf52873d8814b8fd30289f2fcfcec570c151
[ "Unlicense" ]
11
2016-01-14T16:42:00.000Z
2022-01-17T11:47:33.000Z
#pragma once #include <util/system/defaults.h> #include <util/generic/ptr.h> #include <util/network/pair.h> #include <util/generic/noncopyable.h> typedef SOCKET PIPEHANDLE; #define INVALID_PIPEHANDLE INVALID_SOCKET /// Pipe-like object: pipe on POSIX and socket on windows class TPipeHandle: public TNonCopyable { public: inline TPipeHandle() throw () : Fd_(INVALID_PIPEHANDLE) { } inline TPipeHandle(PIPEHANDLE fd) throw () : Fd_(fd) { } inline ~TPipeHandle() throw () { Close(); } bool Close() throw (); inline PIPEHANDLE Release() throw () { PIPEHANDLE ret = Fd_; Fd_ = INVALID_PIPEHANDLE; return ret; } inline void Swap(TPipeHandle& r) throw () { DoSwap(Fd_, r.Fd_); } inline operator PIPEHANDLE() const throw () { return Fd_; } inline bool IsOpen() const throw () { return Fd_ != INVALID_PIPEHANDLE; } ssize_t Read(void* buffer, size_t byteCount) throw (); ssize_t Write(const void* buffer, size_t byteCount) throw (); static void Pipe(TPipeHandle& reader, TPipeHandle& writer); private: PIPEHANDLE Fd_; }; class TPipe { public: TPipe(); /// Takes ownership of handle, so closes it when the last holder of descriptor dies. explicit TPipe(PIPEHANDLE fd); ~TPipe() throw (); void Close(); bool IsOpen() const throw (); PIPEHANDLE GetHandle() const throw (); size_t Read(void* buf, size_t len); size_t Write(const void* buf, size_t len); static void Pipe(TPipe& reader, TPipe& writer); private: class TImpl; typedef TSimpleIntrusivePtr<TImpl> TImplRef; TImplRef Impl_; };
21.531646
88
0.6408
ce3ec8a66c70bf4d328811b8ec1e0f9c9526d210
7,426
h
C
external/TSP/mex/binTree.h
KnockKnock13/segmentation-track
bc43079a182fa736859dae24ffaa35aa06159830
[ "MIT" ]
1
2020-01-07T04:49:16.000Z
2020-01-07T04:49:16.000Z
external/TSP/mex/binTree.h
KnockKnock13/segmentation-track
bc43079a182fa736859dae24ffaa35aa06159830
[ "MIT" ]
null
null
null
external/TSP/mex/binTree.h
KnockKnock13/segmentation-track
bc43079a182fa736859dae24ffaa35aa06159830
[ "MIT" ]
null
null
null
// ============================================================================= // == binNode.h // == -------------------------------------------------------------------------- // == A Binary Tree Node class // == -------------------------------------------------------------------------- // == Written by Jason Chang 02-16-2008 // ============================================================================= #ifndef BINNODE_H #define BINNODE_H #include "assert.h" #include "string.h" template <typename T> class binNode { private: T data; binNode* parent; binNode* child1; binNode* child2; template <typename TT> friend class binTree; public: // -------------------------------------------------------------------------- // -- binNode // -- constructor; initializes the binary tree node to nothing // -------------------------------------------------------------------------- binNode(); // -------------------------------------------------------------------------- // -- binNode // -- constructor; initializes the binary tree node to contain the data // -- // -- parameters: // -- - new_data : the data to put in the new node // -------------------------------------------------------------------------- binNode(T new_data); binNode(const binNode &p); binNode& operator=(const binNode &p); // -------------------------------------------------------------------------- // -- clearNode // -- deletes dynamic data at node // -------------------------------------------------------------------------- void clearNode(); // -------------------------------------------------------------------------- // -- getData // -- retrieves the data at the node // -- // -- return_value: the data of the node // -------------------------------------------------------------------------- T getData(); }; #endif /* BINNODE_H */ // ============================================================================= // == binTree.h // == -------------------------------------------------------------------------- // == A Binary Tree class // == -------------------------------------------------------------------------- // == Written by Jason Chang 12-14-2007 // ============================================================================= #ifndef BINTREE_H #define BINTREE_H #include <cstdlib> #include <stdlib.h> #include <iostream> template <typename T> class binTree { private: binNode<T>* root; // -------------------------------------------------------------------------- // -- deleteSubTree // -- a helper function used to recursively delete the tree // -- // -- parameters: // -- - rootSubTree : the root of the subtree to delete // -------------------------------------------------------------------------- void deleteSubTree(binNode<T>* rootSubTree); // -------------------------------------------------------------------------- // -- findLeaf // -- finds a random leaf // -- // -- parameters: // -- - rootSubTree : the roof of the subtree to start looking from // -- // -- return_value: a pointer to a random binary tree leaf // -------------------------------------------------------------------------- binNode<T>* findLeafSubTree(binNode<T>* rootSubTree); // -------------------------------------------------------------------------- // -- swapData // -- a helper function that swaps the the parent and child // -- // -- parameters: // -- - orig_parent : the original parent // -- - orig_child : the original child // -------------------------------------------------------------------------- void swapData(binNode<T>* orig_parent, binNode<T>* orig_child); // -------------------------------------------------------------------------- // -- sortLeaf // -- sorts the tree from the new leaf given as a parameter // -- // -- parameters: // -- - new_leaf : the newly added leaf // -- // -- return_value : returns a pointer to the new root // -------------------------------------------------------------------------- void sortLeaf(binNode<T>* new_leaf); // -------------------------------------------------------------------------- // -- sortRoot // -- sorts the tree from the root (ignores the data in the actual root) // -- // -- parameters: // -- - new_root : the root to look from // -------------------------------------------------------------------------- binNode<T>* sortRoot(binNode<T>* new_root); // -------------------------------------------------------------------------- // -- printSubTree // -- prints the tree. used for debugging // -------------------------------------------------------------------------- void printSubTree(binNode<T>* rootSubTree); public: // -------------------------------------------------------------------------- // -- binTree // -- constructor; initializes the binary tree to nothing // -------------------------------------------------------------------------- binTree(); // -------------------------------------------------------------------------- // -- binTree // -- destructor // -------------------------------------------------------------------------- ~binTree(); // -------------------------------------------------------------------------- // -- addLeaf // -- adds a leaf at a random location to the end // -- // -- parameters: // -- - new_data : the data of the new leave // -- // -- return_value: a pointer to the newly added leaf // -------------------------------------------------------------------------- binNode<T>* addLeaf(T new_data); // -------------------------------------------------------------------------- // -- modifyLeaf // -- modifies a leaf's information and then resorts the tree // -- // -- parameters: // -- - nodePtr : a pointer to the node you want to modify // -- - new_data : the new_data to update the node with // -------------------------------------------------------------------------- void modifyLeaf(binNode<T>* nodePtr, T new_data); // -------------------------------------------------------------------------- // -- pickOffRoot // -- returns the root data, deletes it from the tree, and reorganizes so // -- that it stays sorted // -- // -- return_value: the data of the tree // -------------------------------------------------------------------------- T pickOffRoot(); void checkErrorsSubTree(binNode<T>* rootSubTree); // -------------------------------------------------------------------------- // -- treeNotEmpty // -- returns true if the tree has data, false if it is empty // -------------------------------------------------------------------------- bool treeNotEmpty(); // -------------------------------------------------------------------------- // -- printTree // -- prints the tree. used for debugging // -------------------------------------------------------------------------- void printTree(); }; #endif /* BINTREE_H */
37.316583
81
0.310396
ed2380889726c32400ec9e0bab15e59efdf66410
34,056
h
C
ports/aurix/tc397_bstep/0_Src/BaseSw/Infra/Sfr/TC39B/_Reg/IfxSbcu_regdef.h
bhsh/infineon_micropython
1f8561de224239bd9382714d0fe14bd8dc9b5212
[ "MIT" ]
3
2021-07-16T03:15:06.000Z
2022-03-20T09:53:51.000Z
ports/aurix/tc397_bstep/0_Src/BaseSw/Infra/Sfr/TC39B/_Reg/IfxSbcu_regdef.h
bhsh/infineon_micropython
1f8561de224239bd9382714d0fe14bd8dc9b5212
[ "MIT" ]
null
null
null
ports/aurix/tc397_bstep/0_Src/BaseSw/Infra/Sfr/TC39B/_Reg/IfxSbcu_regdef.h
bhsh/infineon_micropython
1f8561de224239bd9382714d0fe14bd8dc9b5212
[ "MIT" ]
1
2022-02-09T06:16:39.000Z
2022-02-09T06:16:39.000Z
/** * \file IfxSbcu_regdef.h * \brief * \copyright Copyright (c) 2018 Infineon Technologies AG. All rights reserved. * * * Version: TC39XB_UM_V1.0.0.R0 * Specification: TC3xx User Manual V1.0.0 * MAY BE CHANGED BY USER [yes/no]: No * * IMPORTANT NOTICE * * * Infineon Technologies AG (Infineon) is supplying this file for use * exclusively with Infineon's microcontroller products. This file can be freely * distributed within development tools that are supporting such microcontroller * products. * * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. * INFINEON SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, * OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. * * \defgroup IfxSfr_Sbcu_Registers Sbcu Registers * \ingroup IfxSfr * * \defgroup IfxSfr_Sbcu_Registers_Bitfields Bitfields * \ingroup IfxSfr_Sbcu_Registers * * \defgroup IfxSfr_Sbcu_Registers_union Register unions * \ingroup IfxSfr_Sbcu_Registers * * \defgroup IfxSfr_Sbcu_Registers_struct Memory map * \ingroup IfxSfr_Sbcu_Registers */ #ifndef IFXSBCU_REGDEF_H #define IFXSBCU_REGDEF_H 1 /******************************************************************************/ #include "Ifx_TypesReg.h" /******************************************************************************/ /******************************************************************************/ /******************************************************************************/ /** \addtogroup IfxSfr_Sbcu_Registers_Bitfields * \{ */ /** \brief Access Enable Register 0 */ typedef struct _Ifx_SBCU_ACCEN0_Bits { Ifx_UReg_32Bit EN0:1; /**< \brief [0:0] Access Enable for Master TAG ID 0 (rw) */ Ifx_UReg_32Bit EN1:1; /**< \brief [1:1] Access Enable for Master TAG ID 1 (rw) */ Ifx_UReg_32Bit EN2:1; /**< \brief [2:2] Access Enable for Master TAG ID 2 (rw) */ Ifx_UReg_32Bit EN3:1; /**< \brief [3:3] Access Enable for Master TAG ID 3 (rw) */ Ifx_UReg_32Bit EN4:1; /**< \brief [4:4] Access Enable for Master TAG ID 4 (rw) */ Ifx_UReg_32Bit EN5:1; /**< \brief [5:5] Access Enable for Master TAG ID 5 (rw) */ Ifx_UReg_32Bit EN6:1; /**< \brief [6:6] Access Enable for Master TAG ID 6 (rw) */ Ifx_UReg_32Bit EN7:1; /**< \brief [7:7] Access Enable for Master TAG ID 7 (rw) */ Ifx_UReg_32Bit EN8:1; /**< \brief [8:8] Access Enable for Master TAG ID 8 (rw) */ Ifx_UReg_32Bit EN9:1; /**< \brief [9:9] Access Enable for Master TAG ID 9 (rw) */ Ifx_UReg_32Bit EN10:1; /**< \brief [10:10] Access Enable for Master TAG ID 10 (rw) */ Ifx_UReg_32Bit EN11:1; /**< \brief [11:11] Access Enable for Master TAG ID 11 (rw) */ Ifx_UReg_32Bit EN12:1; /**< \brief [12:12] Access Enable for Master TAG ID 12 (rw) */ Ifx_UReg_32Bit EN13:1; /**< \brief [13:13] Access Enable for Master TAG ID 13 (rw) */ Ifx_UReg_32Bit EN14:1; /**< \brief [14:14] Access Enable for Master TAG ID 14 (rw) */ Ifx_UReg_32Bit EN15:1; /**< \brief [15:15] Access Enable for Master TAG ID 15 (rw) */ Ifx_UReg_32Bit EN16:1; /**< \brief [16:16] Access Enable for Master TAG ID 16 (rw) */ Ifx_UReg_32Bit EN17:1; /**< \brief [17:17] Access Enable for Master TAG ID 17 (rw) */ Ifx_UReg_32Bit EN18:1; /**< \brief [18:18] Access Enable for Master TAG ID 18 (rw) */ Ifx_UReg_32Bit EN19:1; /**< \brief [19:19] Access Enable for Master TAG ID 19 (rw) */ Ifx_UReg_32Bit EN20:1; /**< \brief [20:20] Access Enable for Master TAG ID 20 (rw) */ Ifx_UReg_32Bit EN21:1; /**< \brief [21:21] Access Enable for Master TAG ID 21 (rw) */ Ifx_UReg_32Bit EN22:1; /**< \brief [22:22] Access Enable for Master TAG ID 22 (rw) */ Ifx_UReg_32Bit EN23:1; /**< \brief [23:23] Access Enable for Master TAG ID 23 (rw) */ Ifx_UReg_32Bit EN24:1; /**< \brief [24:24] Access Enable for Master TAG ID 24 (rw) */ Ifx_UReg_32Bit EN25:1; /**< \brief [25:25] Access Enable for Master TAG ID 25 (rw) */ Ifx_UReg_32Bit EN26:1; /**< \brief [26:26] Access Enable for Master TAG ID 26 (rw) */ Ifx_UReg_32Bit EN27:1; /**< \brief [27:27] Access Enable for Master TAG ID 27 (rw) */ Ifx_UReg_32Bit EN28:1; /**< \brief [28:28] Access Enable for Master TAG ID 28 (rw) */ Ifx_UReg_32Bit EN29:1; /**< \brief [29:29] Access Enable for Master TAG ID 29 (rw) */ Ifx_UReg_32Bit EN30:1; /**< \brief [30:30] Access Enable for Master TAG ID 30 (rw) */ Ifx_UReg_32Bit EN31:1; /**< \brief [31:31] Access Enable for Master TAG ID 31 (rw) */ } Ifx_SBCU_ACCEN0_Bits; /** \brief Access Enable Register 1 */ typedef struct _Ifx_SBCU_ACCEN1_Bits { Ifx_UReg_32Bit reserved_0:32; /**< \brief [31:0] \internal Reserved */ } Ifx_SBCU_ACCEN1_Bits; /** \brief BCU EDC Alarm Clear Register ${x} */ typedef struct _Ifx_SBCU_ALCLR_Bits { Ifx_UReg_32Bit CLR00:1; /**< \brief [0:0] Clear alarm 0 (w) */ Ifx_UReg_32Bit CLR01:1; /**< \brief [1:1] Clear alarm 1 (w) */ Ifx_UReg_32Bit CLR02:1; /**< \brief [2:2] Clear alarm 2 (w) */ Ifx_UReg_32Bit CLR03:1; /**< \brief [3:3] Clear alarm 3 (w) */ Ifx_UReg_32Bit CLR04:1; /**< \brief [4:4] Clear alarm 4 (w) */ Ifx_UReg_32Bit CLR05:1; /**< \brief [5:5] Clear alarm 5 (w) */ Ifx_UReg_32Bit CLR06:1; /**< \brief [6:6] Clear alarm 6 (w) */ Ifx_UReg_32Bit CLR07:1; /**< \brief [7:7] Clear alarm 7 (w) */ Ifx_UReg_32Bit CLR08:1; /**< \brief [8:8] Clear alarm 8 (w) */ Ifx_UReg_32Bit CLR09:1; /**< \brief [9:9] Clear alarm 9 (w) */ Ifx_UReg_32Bit CLR10:1; /**< \brief [10:10] Clear alarm 10 (w) */ Ifx_UReg_32Bit CLR11:1; /**< \brief [11:11] Clear alarm 11 (w) */ Ifx_UReg_32Bit CLR12:1; /**< \brief [12:12] Clear alarm 12 (w) */ Ifx_UReg_32Bit CLR13:1; /**< \brief [13:13] Clear alarm 13 (w) */ Ifx_UReg_32Bit CLR14:1; /**< \brief [14:14] Clear alarm 14 (w) */ Ifx_UReg_32Bit CLR15:1; /**< \brief [15:15] Clear alarm 15 (w) */ Ifx_UReg_32Bit CLR16:1; /**< \brief [16:16] Clear alarm 16 (w) */ Ifx_UReg_32Bit CLR17:1; /**< \brief [17:17] Clear alarm 17 (w) */ Ifx_UReg_32Bit CLR18:1; /**< \brief [18:18] Clear alarm 18 (w) */ Ifx_UReg_32Bit CLR19:1; /**< \brief [19:19] Clear alarm 19 (w) */ Ifx_UReg_32Bit CLR20:1; /**< \brief [20:20] Clear alarm 20 (w) */ Ifx_UReg_32Bit CLR21:1; /**< \brief [21:21] Clear alarm 21 (w) */ Ifx_UReg_32Bit CLR22:1; /**< \brief [22:22] Clear alarm 22 (w) */ Ifx_UReg_32Bit CLR23:1; /**< \brief [23:23] Clear alarm 23 (w) */ Ifx_UReg_32Bit CLR24:1; /**< \brief [24:24] Clear alarm 24 (w) */ Ifx_UReg_32Bit CLR25:1; /**< \brief [25:25] Clear alarm 25 (w) */ Ifx_UReg_32Bit CLR26:1; /**< \brief [26:26] Clear alarm 26 (w) */ Ifx_UReg_32Bit CLR27:1; /**< \brief [27:27] Clear alarm 27 (w) */ Ifx_UReg_32Bit CLR28:1; /**< \brief [28:28] Clear alarm 28 (w) */ Ifx_UReg_32Bit CLR29:1; /**< \brief [29:29] Clear alarm 29 (w) */ Ifx_UReg_32Bit CLR30:1; /**< \brief [30:30] Clear alarm 30 (w) */ Ifx_UReg_32Bit CLR31:1; /**< \brief [31:31] Clear alarm 31 (w) */ } Ifx_SBCU_ALCLR_Bits; /** \brief BCU EDC Alarm Control Register */ typedef struct _Ifx_SBCU_ALCTRL_Bits { Ifx_UReg_32Bit ALOV:1; /**< \brief [0:0] Alarm Overflow (rh) */ Ifx_UReg_32Bit ALOVCLR:1; /**< \brief [1:1] Alarm Overflow Clear (w) */ Ifx_UReg_32Bit reserved_2:30; /**< \brief [31:2] \internal Reserved */ } Ifx_SBCU_ALCTRL_Bits; /** \brief BCU EDC Alarm Status Register ${x} */ typedef struct _Ifx_SBCU_ALSTAT_Bits { Ifx_UReg_32Bit AL00:1; /**< \brief [0:0] Alarm 0 (rh) */ Ifx_UReg_32Bit AL01:1; /**< \brief [1:1] Alarm 1 (rh) */ Ifx_UReg_32Bit AL02:1; /**< \brief [2:2] Alarm 2 (rh) */ Ifx_UReg_32Bit AL03:1; /**< \brief [3:3] Alarm 3 (rh) */ Ifx_UReg_32Bit AL04:1; /**< \brief [4:4] Alarm 4 (rh) */ Ifx_UReg_32Bit AL05:1; /**< \brief [5:5] Alarm 5 (rh) */ Ifx_UReg_32Bit AL06:1; /**< \brief [6:6] Alarm 6 (rh) */ Ifx_UReg_32Bit AL07:1; /**< \brief [7:7] Alarm 7 (rh) */ Ifx_UReg_32Bit AL08:1; /**< \brief [8:8] Alarm 8 (rh) */ Ifx_UReg_32Bit AL09:1; /**< \brief [9:9] Alarm 9 (rh) */ Ifx_UReg_32Bit AL10:1; /**< \brief [10:10] Alarm 10 (rh) */ Ifx_UReg_32Bit AL11:1; /**< \brief [11:11] Alarm 11 (rh) */ Ifx_UReg_32Bit AL12:1; /**< \brief [12:12] Alarm 12 (rh) */ Ifx_UReg_32Bit AL13:1; /**< \brief [13:13] Alarm 13 (rh) */ Ifx_UReg_32Bit AL14:1; /**< \brief [14:14] Alarm 14 (rh) */ Ifx_UReg_32Bit AL15:1; /**< \brief [15:15] Alarm 15 (rh) */ Ifx_UReg_32Bit AL16:1; /**< \brief [16:16] Alarm 16 (rh) */ Ifx_UReg_32Bit AL17:1; /**< \brief [17:17] Alarm 17 (rh) */ Ifx_UReg_32Bit AL18:1; /**< \brief [18:18] Alarm 18 (rh) */ Ifx_UReg_32Bit AL19:1; /**< \brief [19:19] Alarm 19 (rh) */ Ifx_UReg_32Bit AL20:1; /**< \brief [20:20] Alarm 20 (rh) */ Ifx_UReg_32Bit AL21:1; /**< \brief [21:21] Alarm 21 (rh) */ Ifx_UReg_32Bit AL22:1; /**< \brief [22:22] Alarm 22 (rh) */ Ifx_UReg_32Bit AL23:1; /**< \brief [23:23] Alarm 23 (rh) */ Ifx_UReg_32Bit AL24:1; /**< \brief [24:24] Alarm 24 (rh) */ Ifx_UReg_32Bit AL25:1; /**< \brief [25:25] Alarm 25 (rh) */ Ifx_UReg_32Bit AL26:1; /**< \brief [26:26] Alarm 26 (rh) */ Ifx_UReg_32Bit AL27:1; /**< \brief [27:27] Alarm 27 (rh) */ Ifx_UReg_32Bit AL28:1; /**< \brief [28:28] Alarm 28 (rh) */ Ifx_UReg_32Bit AL29:1; /**< \brief [29:29] Alarm 29 (rh) */ Ifx_UReg_32Bit AL30:1; /**< \brief [30:30] Alarm 30 (rh) */ Ifx_UReg_32Bit AL31:1; /**< \brief [31:31] Alarm 31 (rh) */ } Ifx_SBCU_ALSTAT_Bits; /** \brief BCU Control Register */ typedef struct _Ifx_SBCU_CON_Bits { Ifx_UReg_32Bit TOUT:16; /**< \brief [15:0] BCU Bus Time-Out Value (rw) */ Ifx_UReg_32Bit DBG:1; /**< \brief [16:16] BCU Debug Trace Enable (rw) */ Ifx_UReg_32Bit reserved_17:2; /**< \brief [18:17] \internal Reserved */ Ifx_UReg_32Bit reserved_19:1; /**< \brief [19:19] \internal Reserved */ Ifx_UReg_32Bit reserved_20:4; /**< \brief [23:20] \internal Reserved */ Ifx_UReg_32Bit SPC:8; /**< \brief [31:24] Starvation Period Control (rw) */ } Ifx_SBCU_CON_Bits; /** \brief BCU Debug Address 1 Register */ typedef struct _Ifx_SBCU_DBADR1_Bits { Ifx_UReg_32Bit ADR1:32; /**< \brief [31:0] Debug Trigger Address 1 (rw) */ } Ifx_SBCU_DBADR1_Bits; /** \brief BCU Debug Address 2 Register */ typedef struct _Ifx_SBCU_DBADR2_Bits { Ifx_UReg_32Bit ADR2:32; /**< \brief [31:0] Debug Trigger Address 2 (rw) */ } Ifx_SBCU_DBADR2_Bits; /** \brief BCU Debug Trapped Address Register */ typedef struct _Ifx_SBCU_DBADRT_Bits { Ifx_UReg_32Bit FPIADR:32; /**< \brief [31:0] FPI Bus Address Status (rh) */ } Ifx_SBCU_DBADRT_Bits; /** \brief BCU Debug Bus Operation Signals Register */ typedef struct _Ifx_SBCU_DBBOS_Bits { Ifx_UReg_32Bit OPC:4; /**< \brief [3:0] Opcode for Signal Status Debug Trigger (rw) */ Ifx_UReg_32Bit SVM:1; /**< \brief [4:4] SVM Signal for Status Debug Trigger (rw) */ Ifx_UReg_32Bit reserved_5:3; /**< \brief [7:5] \internal Reserved */ Ifx_UReg_32Bit WR:1; /**< \brief [8:8] Write Signal for Status Debug Trigger (rw) */ Ifx_UReg_32Bit reserved_9:3; /**< \brief [11:9] \internal Reserved */ Ifx_UReg_32Bit RD:1; /**< \brief [12:12] Write Signal for Status Debug Trigger (rw) */ Ifx_UReg_32Bit reserved_13:19; /**< \brief [31:13] \internal Reserved */ } Ifx_SBCU_DBBOS_Bits; /** \brief BCU Debug Trapped Bus Operation Signals Register */ typedef struct _Ifx_SBCU_DBBOST_Bits { Ifx_UReg_32Bit FPIOPC:4; /**< \brief [3:0] FPI Bus Opcode Status (rh) */ Ifx_UReg_32Bit FPISVM:1; /**< \brief [4:4] FPI Bus Supervisor Mode Status (rh) */ Ifx_UReg_32Bit FPIACK:2; /**< \brief [6:5] FPI Bus Acknowledge Status (rh) */ Ifx_UReg_32Bit FPIRDY:1; /**< \brief [7:7] FPI Bus Ready Status (rh) */ Ifx_UReg_32Bit FPIWR:1; /**< \brief [8:8] FPI Bus Write Indication Status (rh) */ Ifx_UReg_32Bit FPIRST:2; /**< \brief [10:9] FPI Bus Reset Status (rh) */ Ifx_UReg_32Bit FPIOPS:1; /**< \brief [11:11] FPI Bus OCDS Suspend Status (rh) */ Ifx_UReg_32Bit FPIRD:1; /**< \brief [12:12] FPI Bus Read Indication Status (rh) */ Ifx_UReg_32Bit FPIABORT:1; /**< \brief [13:13] FPI Bus Abort Status (rh) */ Ifx_UReg_32Bit FPITOUT:1; /**< \brief [14:14] FPI Bus Time-out Status (rh) */ Ifx_UReg_32Bit ENDINIT:1; /**< \brief [15:15] FPI Bus Endinit Status (rh) */ Ifx_UReg_32Bit FPITAG:6; /**< \brief [21:16] FPI Bus Master TAG Status (rh) */ Ifx_UReg_32Bit reserved_22:10; /**< \brief [31:22] \internal Reserved */ } Ifx_SBCU_DBBOST_Bits; /** \brief BCU Debug Control Register */ typedef struct _Ifx_SBCU_DBCNTL_Bits { Ifx_UReg_32Bit EO:1; /**< \brief [0:0] Status of BCU Debug Support Enable (r) */ Ifx_UReg_32Bit OA:1; /**< \brief [1:1] Status of BCU Breakpoint Logic (rh) */ Ifx_UReg_32Bit reserved_2:2; /**< \brief [3:2] \internal Reserved */ Ifx_UReg_32Bit RA:1; /**< \brief [4:4] Rearm BCU Breakpoint Logic (w) */ Ifx_UReg_32Bit HSMTRTREN:2; /**< \brief [6:5] Status of HSM Transaction Trace Logic (r) */ Ifx_UReg_32Bit HSMDBGEN:1; /**< \brief [7:7] Status of HSM Debug Mode (r) */ Ifx_UReg_32Bit reserved_8:4; /**< \brief [11:8] \internal Reserved */ Ifx_UReg_32Bit CONCOM0:1; /**< \brief [12:12] Grant and Address Trigger Relation (rw) */ Ifx_UReg_32Bit CONCOM1:1; /**< \brief [13:13] Address 1 and Address 2 Trigger Relation (rw) */ Ifx_UReg_32Bit CONCOM2:1; /**< \brief [14:14] Address and Signal Trigger Relation (rw) */ Ifx_UReg_32Bit reserved_15:1; /**< \brief [15:15] \internal Reserved */ Ifx_UReg_32Bit ONG:1; /**< \brief [16:16] Grant Trigger Enable (rw) */ Ifx_UReg_32Bit reserved_17:3; /**< \brief [19:17] \internal Reserved */ Ifx_UReg_32Bit ONA1:2; /**< \brief [21:20] Address 1 Trigger Control (rw) */ Ifx_UReg_32Bit reserved_22:2; /**< \brief [23:22] \internal Reserved */ Ifx_UReg_32Bit ONA2:2; /**< \brief [25:24] Address 2 Trigger Control (rw) */ Ifx_UReg_32Bit reserved_26:2; /**< \brief [27:26] \internal Reserved */ Ifx_UReg_32Bit ONBOS0:1; /**< \brief [28:28] Op code Signal Status Trigger Condition (rw) */ Ifx_UReg_32Bit ONBOS1:1; /**< \brief [29:29] Supervisor Mode Signal Trigger Condition (rw) */ Ifx_UReg_32Bit ONBOS2:1; /**< \brief [30:30] Write Signal Trigger Condition (rw) */ Ifx_UReg_32Bit ONBOS3:1; /**< \brief [31:31] Read Signal Trigger Condition (rw) */ } Ifx_SBCU_DBCNTL_Bits; /** \brief BCU Debug Data Status Register */ typedef struct _Ifx_SBCU_DBDAT_Bits { Ifx_UReg_32Bit FPIDATA:32; /**< \brief [31:0] FPI Bus Data Status (rh) */ } Ifx_SBCU_DBDAT_Bits; /** \brief SBCU Debug Trapped Master Register */ typedef struct _Ifx_SBCU_DBGNTT_Bits { Ifx_UReg_32Bit DMA:1; /**< \brief [0:0] DMA / Cerberus FPI Bus Master Status (rh) */ Ifx_UReg_32Bit reserved_1:1; /**< \brief [1:1] \internal Reserved */ Ifx_UReg_32Bit SDMMC:1; /**< \brief [2:2] SDMMC FPI Bus Master Status (rh) */ Ifx_UReg_32Bit HSSL0:1; /**< \brief [3:3] HSSL 0 FPI Bus Master Status (rh) */ Ifx_UReg_32Bit HSSL1:1; /**< \brief [4:4] HSSL 1 FPI Bus Master Status (rh) */ Ifx_UReg_32Bit reserved_5:1; /**< \brief [5:5] \internal Reserved */ Ifx_UReg_32Bit CPU0:1; /**< \brief [6:6] CPU0 FPI Bus Master Status (rh) */ Ifx_UReg_32Bit CPU1:1; /**< \brief [7:7] CPU1 FPI Bus Master Status (rh) */ Ifx_UReg_32Bit CPU2:1; /**< \brief [8:8] CPU2 Grant Trigger Enable (rh) */ Ifx_UReg_32Bit CPU3:1; /**< \brief [9:9] CPU3 Grant Trigger Enable (rh) */ Ifx_UReg_32Bit CPU4:1; /**< \brief [10:10] CPU4 Grant Trigger Enable (rh) */ Ifx_UReg_32Bit CPU5:1; /**< \brief [11:11] CPU5 Grant Trigger Enable (rh) */ Ifx_UReg_32Bit HSMRMI:1; /**< \brief [12:12] HSM Register FPI Bus Master Interface Status (rh) */ Ifx_UReg_32Bit HSMCMI:1; /**< \brief [13:13] HSM Cache FPI Bus Master Interface Status (rh) */ Ifx_UReg_32Bit reserved_14:1; /**< \brief [14:14] \internal Reserved */ Ifx_UReg_32Bit reserved_15:1; /**< \brief [15:15] \internal Reserved */ Ifx_UReg_32Bit reserved_16:16; /**< \brief [31:16] \internal Reserved */ } Ifx_SBCU_DBGNTT_Bits; /** \brief SBCU Debug Grant Mask Register */ typedef struct _Ifx_SBCU_DBGRNT_Bits { Ifx_UReg_32Bit DMA:1; /**< \brief [0:0] DMA / Cerberus Trigger Enable (rw) */ Ifx_UReg_32Bit reserved_1:1; /**< \brief [1:1] \internal Reserved */ Ifx_UReg_32Bit SDMMC:1; /**< \brief [2:2] SDMMC Trigger Enable (rw) */ Ifx_UReg_32Bit HSSL0:1; /**< \brief [3:3] HSSL0 Trigger Enable (rw) */ Ifx_UReg_32Bit HSSL1:1; /**< \brief [4:4] HSSL1 Trigger Enable (rw) */ Ifx_UReg_32Bit reserved_5:1; /**< \brief [5:5] \internal Reserved */ Ifx_UReg_32Bit CPU0:1; /**< \brief [6:6] CPU0 Grant Trigger Enable (rw) */ Ifx_UReg_32Bit CPU1:1; /**< \brief [7:7] CPU1 Grant Trigger Enable (rw) */ Ifx_UReg_32Bit CPU2:1; /**< \brief [8:8] CPU2 Grant Trigger Enable (rw) */ Ifx_UReg_32Bit CPU3:1; /**< \brief [9:9] CPU3 Grant Trigger Enable (rw) */ Ifx_UReg_32Bit CPU4:1; /**< \brief [10:10] CPU4 Grant Trigger Enable (rw) */ Ifx_UReg_32Bit CPU5:1; /**< \brief [11:11] CPU5 Grant Trigger Enable (rw) */ Ifx_UReg_32Bit HSMRMI:1; /**< \brief [12:12] HSM Register Master Interface Grant Trigger Enable (rw) */ Ifx_UReg_32Bit HSMCMI:1; /**< \brief [13:13] HSM Cache Master Interface Grant Trigger Enable (rw) */ Ifx_UReg_32Bit reserved_14:1; /**< \brief [14:14] \internal Reserved */ Ifx_UReg_32Bit reserved_15:1; /**< \brief [15:15] \internal Reserved */ Ifx_UReg_32Bit reserved_16:16; /**< \brief [31:16] \internal Reserved */ } Ifx_SBCU_DBGRNT_Bits; /** \brief BCU Error Address Capture Register */ typedef struct _Ifx_SBCU_EADD_Bits { Ifx_UReg_32Bit FPIADR:32; /**< \brief [31:0] Captured FPI Bus Address - FPIADR (rwh) */ } Ifx_SBCU_EADD_Bits; /** \brief BCU Error Control Capture Register */ typedef struct _Ifx_SBCU_ECON_Bits { Ifx_UReg_32Bit ERRCNT:14; /**< \brief [13:0] FPI Bus Error Counter (rwh) */ Ifx_UReg_32Bit TOUT:1; /**< \brief [14:14] State of FPI Bus Time-Out Signal (rwh) */ Ifx_UReg_32Bit RDY:1; /**< \brief [15:15] State of FPI Bus Ready Signal (rwh) */ Ifx_UReg_32Bit ABT:1; /**< \brief [16:16] State of FPI Bus Abort Signal (rwh) */ Ifx_UReg_32Bit ACK:2; /**< \brief [18:17] State of FPI Bus Acknowledge Signals (rwh) */ Ifx_UReg_32Bit SVM:1; /**< \brief [19:19] State of FPI Bus Supervisor Mode Signal (rwh) */ Ifx_UReg_32Bit WRN:1; /**< \brief [20:20] State of FPI Bus Write Signal (rwh) */ Ifx_UReg_32Bit RDN:1; /**< \brief [21:21] State of FPI Bus Read Signal (rwh) */ Ifx_UReg_32Bit TAG:6; /**< \brief [27:22] FPI Bus Master Tag Number Signals (rwh) */ Ifx_UReg_32Bit OPC:4; /**< \brief [31:28] FPI Bus Operation Code Signals (rwh) */ } Ifx_SBCU_ECON_Bits; /** \brief BCU Error Data Capture Register */ typedef struct _Ifx_SBCU_EDAT_Bits { Ifx_UReg_32Bit FPIDAT:32; /**< \brief [31:0] Captured FPI Bus Data - FPIDAT (rwh) */ } Ifx_SBCU_EDAT_Bits; /** \brief FPI Error Generation Control Register */ typedef struct _Ifx_SBCU_FEGEN_Bits { Ifx_UReg_32Bit SEDM:3; /**< \brief [2:0] SEDM (Slave Encoder) (rw) */ Ifx_UReg_32Bit reserved_3:5; /**< \brief [7:3] \internal Reserved */ Ifx_UReg_32Bit MEDM:3; /**< \brief [10:8] MEDM (Master Encoder) Type of Error (rw) */ Ifx_UReg_32Bit reserved_11:5; /**< \brief [15:11] \internal Reserved */ Ifx_UReg_32Bit EN:3; /**< \brief [18:16] Enable Signal Type of Error (rw) */ Ifx_UReg_32Bit reserved_19:5; /**< \brief [23:19] \internal Reserved */ Ifx_UReg_32Bit BCU:2; /**< \brief [25:24] BCU Type of Error (rw) */ Ifx_UReg_32Bit reserved_26:6; /**< \brief [31:26] \internal Reserved */ } Ifx_SBCU_FEGEN_Bits; /** \brief Module Identification Register */ typedef struct _Ifx_SBCU_ID_Bits { Ifx_UReg_32Bit MOD_REV:8; /**< \brief [7:0] Module Revision Number - MOD_REV (r) */ Ifx_UReg_32Bit MOD_NUMBER:8; /**< \brief [15:8] Module Number Value - MOD_NUMBER (r) */ Ifx_UReg_32Bit reserved_16:16; /**< \brief [31:16] \internal Reserved */ } Ifx_SBCU_ID_Bits; /** \brief Arbiter Priority Register High */ typedef struct _Ifx_SBCU_PRIOH_Bits { Ifx_UReg_32Bit CPU2:4; /**< \brief [3:0] CPU2 Priority (Index 8) (rw) */ Ifx_UReg_32Bit CPU3:4; /**< \brief [7:4] CPU3 Priority (Index 9) (rw) */ Ifx_UReg_32Bit CPU4:4; /**< \brief [11:8] CPU4 Priority (Index 10) (rw) */ Ifx_UReg_32Bit CPU5:4; /**< \brief [15:12] CPU5 11 Priority (Index 11) (rw) */ Ifx_UReg_32Bit HSMRMI:4; /**< \brief [19:16] HSMRMI Priority (Index 12) (rw) */ Ifx_UReg_32Bit HSMCMI:4; /**< \brief [23:20] HSMCMI Priority (Index 13) (rw) */ Ifx_UReg_32Bit reserved_24:4; /**< \brief [27:24] \internal Reserved */ Ifx_UReg_32Bit reserved_28:4; /**< \brief [31:28] \internal Reserved */ } Ifx_SBCU_PRIOH_Bits; /** \brief Arbiter Priority Register Low */ typedef struct _Ifx_SBCU_PRIOL_Bits { Ifx_UReg_32Bit DMA:4; /**< \brief [3:0] DMA / Cerberus Priority (Index 0) (rw) */ Ifx_UReg_32Bit reserved_4:4; /**< \brief [7:4] \internal Reserved */ Ifx_UReg_32Bit SDMMC:4; /**< \brief [11:8] SDMMC Priority (Index 2) (rw) */ Ifx_UReg_32Bit HSSL0:4; /**< \brief [15:12] HSSL0 Priority (Index 3) (rw) */ Ifx_UReg_32Bit HSSL1:4; /**< \brief [19:16] HSSL1 Priority (Index 4) (rw) */ Ifx_UReg_32Bit reserved_20:4; /**< \brief [23:20] \internal Reserved */ Ifx_UReg_32Bit CPU0:4; /**< \brief [27:24] CPU0 Priority (Index 6) (rw) */ Ifx_UReg_32Bit CPU1:4; /**< \brief [31:28] CPU1 Priority (Index 7) (rw) */ } Ifx_SBCU_PRIOL_Bits; /** \} */ /******************************************************************************/ /******************************************************************************/ /** \addtogroup IfxSfr_sbcu_Registers_union * \{ */ /** \brief Access Enable Register 0 */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_ACCEN0_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_ACCEN0; /** \brief Access Enable Register 1 */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_ACCEN1_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_ACCEN1; /** \brief BCU EDC Alarm Clear Register ${x} */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_ALCLR_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_ALCLR; /** \brief BCU EDC Alarm Control Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_ALCTRL_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_ALCTRL; /** \brief BCU EDC Alarm Status Register ${x} */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_ALSTAT_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_ALSTAT; /** \brief BCU Control Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_CON_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_CON; /** \brief BCU Debug Address 1 Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_DBADR1_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_DBADR1; /** \brief BCU Debug Address 2 Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_DBADR2_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_DBADR2; /** \brief BCU Debug Trapped Address Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_DBADRT_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_DBADRT; /** \brief BCU Debug Bus Operation Signals Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_DBBOS_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_DBBOS; /** \brief BCU Debug Trapped Bus Operation Signals Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_DBBOST_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_DBBOST; /** \brief BCU Debug Control Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_DBCNTL_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_DBCNTL; /** \brief BCU Debug Data Status Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_DBDAT_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_DBDAT; /** \brief SBCU Debug Trapped Master Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_DBGNTT_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_DBGNTT; /** \brief SBCU Debug Grant Mask Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_DBGRNT_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_DBGRNT; /** \brief BCU Error Address Capture Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_EADD_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_EADD; /** \brief BCU Error Control Capture Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_ECON_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_ECON; /** \brief BCU Error Data Capture Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_EDAT_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_EDAT; /** \brief FPI Error Generation Control Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_FEGEN_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_FEGEN; /** \brief Module Identification Register */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_ID_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_ID; /** \brief Arbiter Priority Register High */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_PRIOH_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_PRIOH; /** \brief Arbiter Priority Register Low */ typedef union { Ifx_UReg_32Bit U; /**< \brief Unsigned access */ Ifx_SReg_32Bit I; /**< \brief Signed access */ Ifx_SBCU_PRIOL_Bits B; /**< \brief Bitfield access */ } Ifx_SBCU_PRIOL; /** \} */ /******************************************************************************/ /** \addtogroup IfxSfr_Sbcu_Registers_struct * \{ */ /******************************************************************************/ /** \name Object L0 * \{ */ /** \brief SBCU object */ typedef volatile struct _Ifx_SBCU { Ifx_UReg_8Bit reserved_0[8]; /**< \brief 0, \internal Reserved */ Ifx_SBCU_ID ID; /**< \brief 8, Module Identification Register*/ Ifx_UReg_8Bit reserved_C[4]; /**< \brief C, \internal Reserved */ Ifx_SBCU_CON CON; /**< \brief 10, BCU Control Register*/ Ifx_SBCU_PRIOH PRIOH; /**< \brief 14, */ Ifx_SBCU_PRIOL PRIOL; /**< \brief 18, */ Ifx_UReg_8Bit reserved_1C[4]; /**< \brief 1C, \internal Reserved */ Ifx_SBCU_ECON ECON; /**< \brief 20, BCU Error Control Capture Register*/ Ifx_SBCU_EADD EADD; /**< \brief 24, BCU Error Address Capture Register*/ Ifx_SBCU_EDAT EDAT; /**< \brief 28, BCU Error Data Capture Register*/ Ifx_UReg_8Bit reserved_2C[4]; /**< \brief 2C, \internal Reserved */ Ifx_SBCU_DBCNTL DBCNTL; /**< \brief 30, BCU Debug Control Register*/ Ifx_SBCU_DBGRNT DBGRNT; /**< \brief 34, */ Ifx_SBCU_DBADR1 DBADR1; /**< \brief 38, BCU Debug Address 1 Register*/ Ifx_SBCU_DBADR2 DBADR2; /**< \brief 3C, BCU Debug Address 2 Register*/ Ifx_SBCU_DBBOS DBBOS; /**< \brief 40, BCU Debug Bus Operation Signals Register*/ Ifx_SBCU_DBGNTT DBGNTT; /**< \brief 44, */ Ifx_SBCU_DBADRT DBADRT; /**< \brief 48, BCU Debug Trapped Address Register*/ Ifx_SBCU_DBBOST DBBOST; /**< \brief 4C, BCU Debug Trapped Bus Operation Signals Register*/ Ifx_SBCU_DBDAT DBDAT; /**< \brief 50, BCU Debug Data Status Register*/ Ifx_UReg_8Bit reserved_54[12]; /**< \brief 54, \internal Reserved */ Ifx_SBCU_ALSTAT ALSTAT[4]; /**< \brief 60, BCU EDC Alarm Status Register ${x}*/ Ifx_SBCU_ALCLR ALCLR[4]; /**< \brief 70, BCU EDC Alarm Clear Register ${x}*/ Ifx_SBCU_ALCTRL ALCTRL; /**< \brief 80, BCU EDC Alarm Control Register*/ Ifx_SBCU_FEGEN FEGEN; /**< \brief 84, FPI Error Generation Control Register*/ Ifx_UReg_8Bit reserved_88[112]; /**< \brief 88, \internal Reserved */ Ifx_SBCU_ACCEN1 ACCEN1; /**< \brief F8, Access Enable Register 1*/ Ifx_SBCU_ACCEN0 ACCEN0; /**< \brief FC, Access Enable Register 0*/ } Ifx_SBCU; /** \} */ /******************************************************************************/ /** \} */ /******************************************************************************/ /******************************************************************************/ #endif /* IFXSBCU_REGDEF_H */
55.19611
133
0.559696
d44c8577f976b0cb86b570732c6d0c421aefbf52
2,427
h
C
mips-side/include/sys/stat.h
FlexingTiger/Supercard-API
d8294f85f6dd97100c0b4d598ee42a55993ccf61
[ "BSD-4-Clause", "Zlib", "BSD-3-Clause" ]
11
2017-03-25T21:25:51.000Z
2020-01-31T06:51:06.000Z
mips-side/include/sys/stat.h
FlexingTiger/Supercard-API
d8294f85f6dd97100c0b4d598ee42a55993ccf61
[ "BSD-4-Clause", "Zlib", "BSD-3-Clause" ]
1
2017-09-29T13:18:46.000Z
2017-09-29T13:18:46.000Z
mips-side/include/sys/stat.h
FlexingTiger/Supercard-API
d8294f85f6dd97100c0b4d598ee42a55993ccf61
[ "BSD-4-Clause", "Zlib", "BSD-3-Clause" ]
2
2017-09-28T16:43:32.000Z
2021-12-21T04:48:34.000Z
/* * This file is part of the C standard library for the Supercard DSTwo. * * Copyright 2017 Nebuleon Fumika <nebuleon.fumika@gmail.com> * * It 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. * * It 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 it. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __SYS_STAT_H__ #define __SYS_STAT_H__ #ifdef __cplusplus extern "C" { #endif #include <time.h> #include <sys/types.h> typedef unsigned int mode_t; struct stat { dev_t st_dev; /* device identifier */ ino_t st_ino; /* inode number */ mode_t st_mode; /* protection */ nlink_t st_nlink; /* number of hard links to the file */ uid_t st_uid; /* owner user ID */ gid_t st_gid; /* owner group ID */ dev_t st_rdev; /* device identifier for device files */ off_t st_size; /* total size, in bytes */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last write */ time_t st_ctime; /* time of creation */ blksize_t st_blksize; /* size of blocks on the filesystem */ blkcnt_t st_blocks; /* number of blocks allocated for the file */ }; #define S_IFDIR 1 #define S_IFREG 2 #define S_IRUSR 4 #define S_IRGRP 8 #define S_IROTH 16 #define S_IWUSR 32 #define S_IWGRP 64 #define S_IWOTH 128 #define S_IXUSR 256 #define S_IXGRP 512 #define S_IXOTH 1024 #define S_IRWXU (S_IRUSR | S_IWUSR | S_IXUSR) #define S_IRWXG (S_IRGRP | S_IWGRP | S_IXGRP) #define S_IRWXO (S_IROTH | S_IWOTH | S_IXOTH) #define S_ISREG(m) ((m) & S_IFREG) #define S_ISDIR(m) ((m) & S_IFDIR) extern int fstat(int fd, struct stat *buf); extern int mkdir(const char* path, mode_t mode); extern int stat(const char* restrict path, struct stat* restrict buf); #define lstat stat /* FAT does not support symbolic links */ #ifdef __cplusplus } #endif #endif /* !__SYS_STAT_H__ */
30.3375
72
0.669551
d45737b2769f515336320542bf27cecc0007b9a6
17,121
h
C
Plugins/RuntimeGeometryUtils/Source/RuntimeGeometryUtils/Public/GeneratedMesh.h
monizka/UnrealRuntimeToolsFrameworkDemo
07aac135dc975c4833ae081a69be9f725412ffa0
[ "MIT" ]
47
2021-01-20T16:52:07.000Z
2022-02-02T05:39:50.000Z
Plugins/RuntimeGeometryUtils/Source/RuntimeGeometryUtils/Public/GeneratedMesh.h
monizka/UnrealRuntimeToolsFrameworkDemo
07aac135dc975c4833ae081a69be9f725412ffa0
[ "MIT" ]
1
2022-02-10T01:21:23.000Z
2022-02-10T01:21:23.000Z
Plugins/RuntimeGeometryUtils/Source/RuntimeGeometryUtils/Public/GeneratedMesh.h
tomleetv/UnrealRuntimeToolsFrameworkDemo
e5702d55f45e580c932d99aaef1fd2b73479c636
[ "MIT" ]
17
2021-01-24T12:58:58.000Z
2022-03-13T10:55:12.000Z
#pragma once #include "CoreMinimal.h" #include "DynamicMesh3.h" #include "DynamicMeshAABBTree3.h" #include "Spatial/FastWinding.h" #include "GeneratedMesh.generated.h" class ADynamicMeshBaseActor; UENUM(BlueprintType) enum class EGeneratedMeshBooleanOperation : uint8 { Union = 0, Subtraction = 1, Intersection = 2 }; /** * UGeneratedMesh stores a "temporary mesh" and provides a set of operations to create * and manipulate the geometry of that mesh, run spatial queries against it, and so on. * The mesh does not have any visual representation or game functionality, this is * purely a data-storage container with modification operations. */ UCLASS(BlueprintType, Transient) class RUNTIMEGEOMETRYUTILS_API UGeneratedMesh : public UObject { GENERATED_BODY() public: UGeneratedMesh(); /** Clear the mesh and reset the Append Transform */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Initialization") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* ResetMesh(); /** Copy the SourceMesh from a MeshActor */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Initialization") UPARAM(DisplayName = "New Mesh") UGeneratedMesh* InitializeFrom(ADynamicMeshBaseActor* MeshActor); /** Copy the Mesh from another GeneratedMesh */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Initialization") UPARAM(DisplayName = "New Mesh") UGeneratedMesh* MakeDuplicate(UGeneratedMesh* Mesh); /** * Update SourceMesh by reading external mesh file at Path. Optionally flip orientation. * Note: Path may be relative to Content folder, otherwise it must be an absolute path. * @return false if mesh read failed */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Initialization") bool ReadMeshFromFile(FString Path, bool bFlipOrientation); /** * Set the Append Transform. This transform will be applied to any shapes created using the AppendX() functions (AppendBox, AppendSphere, etc) * before merging them into the accumulated mesh. */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|ShapeGenerators") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* SetAppendTransform(FTransform Transform); /** * Clear the current Append Transform */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|ShapeGenerators") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* ClearAppendTransform(); /** * Append an Axis-Aligned Box defined by the given Min and Max corners * @param StepsX number of subdivisions along X axis * @param StepsY number of subdivisions along Y axis * @param StepsZ number of subdivisions along Z axis */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|ShapeGenerators") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* AppendAxisBox(FVector Min = FVector(-50,-50,-50), FVector Max = FVector(50, 50, 50), int32 StepsX = 0, int32 StepsY = 0, int32 StepsZ = 0); /** * Append an Axis-Aligned Box defined by an FBox * @param StepsX number of subdivisions along X axis * @param StepsY number of subdivisions along Y axis * @param StepsZ number of subdivisions along Z axis */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|ShapeGenerators") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* AppendBox(FBox Box, int32 StepsX = 0, int32 StepsY = 0, int32 StepsZ = 0); /** * Append a Sphere centered at the Origin that has a standard polar triangulation * @param Radius radius of the sphere * @param Slices number of vertical sections of the sphere, ie if it were an orange * @param Stacks number of horizontal sections of the sphere */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|ShapeGenerators") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* AppendSphere(float Radius = 25.0, int32 Slices = 6, int32 Stacks = 6); /** * Append a Sphere centered at the Origin that has a normalized box triangulation * @param Radius radius of the sphere * @param Steps number of subdivisions along each box axis */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|ShapeGenerators") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* AppendSphereBox(float Radius = 25.0, int32 Steps = 6); /** * Append a Cylinder with base at the Origin and aligned up the +Z axis * @param Radius radius of the cylinder * @param Height height of the cylinder * @param Slices number of vertical sections of the cylinder, ie if it were an orange * @param Stacks number of horizontal sections of the cylinder * @param bCapped if true, the ends of the cylinder are filled */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|ShapeGenerators") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* AppendCylinder(float Radius = 25.0, float Height = 100.0, int32 Slices = 6, int32 Stacks = 2, bool bCapped = true); /** * Append a Cone with base at the Origin and aligned up the +Z axis * @param BaseRadius radius of the cone at it's base * @param TopRadius radius of the cone at it's top * @param Height height of the cone * @param Slices number of vertical sections of the cone, ie if it were an orange * @param Stacks number of horizontal sections of the cone * @param bCapped if true, the ends of the cone are closed */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|ShapeGenerators") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* AppendCone(float BaseRadius = 25.0, float TopRadius = 5.0, float Height = 100.0, int Slices = 6, int Stacks = 2, bool bCapped = true); /** * Append a Torus/Donut, with the major circle lying in the XY plane * @param Radius radius of XY-plane circle * @param SectionRadius radius of the vertical profile-curve circle swept around the XY circle * @param CircleSlices number of sample points on the XY-plane circle * @param SectionSlices number of sample points on the profile circle */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|ShapeGenerators") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* AppendTorus(float Radius = 50.0, float SectionRadius = 10.0, int CircleSlices = 6, int SectionSlices = 6); /** * Revolve a 2D polygon around the +Z axis to create a closed shape * @param Polygon points on the 2D polygon * @param Radius radius of XY-plane circle * @param RevolveSteps number of sample sample points on the circle of revolution */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|ShapeGenerators") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* AppendRevolvePolygon(TArray<FVector2D> Polygon, float Radius = 100.0, int RevolveSteps = 6); /** * Extrude a 2D polygon upwards from the Origin along the +Z axis * @param Polygon points on the 2D polygon * @param Height height of the extrusion * @param bCapped if true, endcaps of the extrusion are triangulated */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|ShapeGenerators") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* AppendExtrusion(TArray<FVector2D> Polygon, float Height = 10.0, bool bCapped = true); /** * Append another GeneratedMesh multiple times, applying a Transform to each repetition. * Note that the Append Transform is *not* applied in this case. * @param OtherMesh the mesh to append * @param Transform the transform to repeatedly apply at each iteration * @param RepeatCount the number of times to append the OtherMesh * @param bApplyBefore if true, we apply Transform to OtherMesh *before* each iteration, otherwise it is applied *after* */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|CompositionOps") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* AppendTiled(UGeneratedMesh* OtherMesh, FTransform Transform, int RepeatCount = 3, bool bApplyBefore = false); /** Compute the specified a Boolean operation with OtherMesh */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|CompositionOps") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* BooleanWith(UGeneratedMesh* OtherMesh, EGeneratedMeshBooleanOperation Operation); /** Compute the specified a Boolean operation with Transform(OtherMesh) */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|CompositionOps") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* BooleanWithTransformed(UGeneratedMesh* OtherMesh, FTransform Transform, EGeneratedMeshBooleanOperation Operation); /** * Cut the mesh with a 3D plane defined by the Origin and Normal. Positive side is kept. * @param bFillHole if true, any holes created by the cut are triangulated * @param bFlipSide reverse which side of the cut is kept */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|CuttingOps") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* CutWithPlane(FVector Origin, FVector Normal, bool bFillHole = true, bool bFlipSide = false); /** * Mirror the mesh across the 3D plane defined by the origin and normal * @param bApplyPlaneCut if true, mesh is cut before mirroring and stitched along cut loops */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|CuttingOps") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* Mirror(FVector Origin, FVector Normal, bool bApplyPlaneCut = true); /** Create a "solid" verison of Mesh by voxelizing with the fast winding number at the given grid resolution */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|RemeshingOps") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* SolidifyMesh(int VoxelResolution = 64, float WindingThreshold = 0.5); /** Simplify current Mesh to the target triangle count */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|RemeshingOps") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* SimplifyMeshToTriCount(int32 TargetTriangleCount, bool bDiscardAttributes = false); /** * Find NearestMeshWorldPoint on SourceMesh to WorldPoint, as well as NearestTriangle ID and barycentric coordinates of NearestMeshWorldPoint in triangle * @return distance to point */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|SpatialQueries") float DistanceToPoint(FVector WorldPoint, FVector& NearestMeshWorldPoint, int& NearestTriangle, FVector& TriBaryCoords); /** * @return nearest world-space point on SourceMesh to WorldPoint */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|SpatialQueries") FVector NearestPoint(FVector WorldPoint); /** * @return true if mesh contains WorldPoint, which is defined as the mesh winding number being >= WindingThreshold */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|SpatialQueries") bool ContainsPoint(FVector WorldPoint, float WindingThreshold = 0.5); /** * Calculate intersection of given 3D World-Space ray defined by (RayOrigin,RayDirection) with the SourceMesh. * If hit, returns WorldHitPoint position, distance along ray in HitDistance, NearestTriangle ID, and barycentric coordinates of hit point in triangle * Pass MaxDistance > 0 to limit the allowable ray-hit distance * @return true if hit is found */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|SpatialQueries") bool IntersectRay(FVector RayOrigin, FVector RayDirection, FVector& WorldHitPoint, float& HitDistance, int& NearestTriangle, FVector& TriBaryCoords, float MaxDistance = 0); /** Translate the vertices of the Mesh by the given 3D Translation */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Transforms") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* Translate(FVector Translation); /** Rotate the vertices of the Mesh around the Origin point using the given Rotation */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Transforms") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* Rotate(FRotator Rotation, FVector Origin = FVector(0, 0, 0)); /** Rotate the vertices of the Mesh around the Origin point using the given Rotation */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Transforms") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* RotateQuat(FQuat Rotation, FVector Origin = FVector(0,0,0)); /** Uniform-Scale the vertices of the Mesh relative to the Origin point using the given Scale */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Transforms") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* ScaleUniform(float Scale, FVector Origin = FVector(0,0,0)); /** Scale the vertices of the Mesh relative to the Origin point using the given Scale */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Transforms") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* Scale(FVector Scale, FVector Origin = FVector(0, 0, 0)); /** Apply the given Transform to the vertices of the Mesh */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Transforms") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* Transform(FTransform Transform); /** Set the normals of the mesh to Per-Triangle/Face Normals */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Normals") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* SetToFaceNormals(); /** Set the normals of the mesh to averaged Per-Vertex Normals */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Normals") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* SetToVertexNormals(); /** Set the normals of the mesh to hard normals when the edge opening angle exceeds the given Threshold, otherwise to averaged per-Vertex normals */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Normals") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* SetToAngleThresholdNormals(float AngleThresholdDeg = 180.0f); /** Recompute the averaged normals for the current hard-normal topology */ UFUNCTION(BlueprintCallable, Category = "GeneratedMesh|Normals") UPARAM(DisplayName = "Input Mesh") UGeneratedMesh* RecomputeNormals(); protected: FTransform3d AppendTransform; TUniquePtr<FDynamicMesh3> Mesh; TUniquePtr<FDynamicMeshAABBTree3> MeshAABBTree; TUniquePtr<TFastWindingTree<FDynamicMesh3>> FastWinding; public: const TUniquePtr<FDynamicMesh3>& GetMesh() const { return Mesh; } TUniquePtr<FDynamicMeshAABBTree3>& GetAABBTree(); // note: cannot return const because query functions are non-const const TUniquePtr<TFastWindingTree<FDynamicMesh3>>& GetFastWindingTree(); void SetMesh(const FDynamicMesh3& MeshIn) { *Mesh = MeshIn; OnMeshUpdated(); } void AppendMeshWithAppendTransform(FDynamicMesh3&& ToAppend, bool bPostMeshUpdate = true); void OnMeshUpdated(); // warning: not safe to use AABBTree or FastWindingTree during this function virtual void EditMeshInPlace(TFunctionRef<void(FDynamicMesh3&)> EditFunc) { EditFunc(*Mesh); OnMeshUpdated(); } }; /** * UGeneratedMeshPool manages a Pool of UGeneratedMesh objects. This allows * the meshes to be re-used instead of being garbage-collected. * * Usage is to call RequestMesh() to take ownership of an available UGeneratedMesh (which * will allocate a new one if the pool is empty) and ReturnMesh() to return it to the pool. * * ReturnAllMeshes() can be called to return all allocated meshes. * * In both cases, there is nothing preventing you from still holding on to the mesh. * So, be careful. * * FreeAllMeshes() calls ReturnAllMeshes() and then releases the pool's references to * the allocated meshes, so they can be Garbage Collected * * If you Request() more meshes than you Return(), the Pool will still be holding on to * references to those meshes, and they will never be Garbage Collected (ie memory leak). * As a failsafe, if the number of allocated meshes exceeds MeshCountSafetyThreshold, * the Pool will release all it's references and run garbage collection on the next call to RequestMesh(). * (Do not rely on this as a memory management strategy) * * An alternate strategy that could be employed here is for the Pool to not hold * references to meshes it has provided, only those that have been explicitly returned. * Then non-returned meshes would simply be garbage-collected, however it allows * potentially a large amount of memory to be consumed until that occurs. * * UGeneratedMesh::ResetMesh() is called on the object returned to the Pool, which clears * the internal FDynamicMesh3 (which uses normal C++ memory management, so no garbage collection involved) * So the Pool does not re-use mesh memory, only the UObject containers. */ UCLASS(Transient) class RUNTIMEGEOMETRYUTILS_API UGeneratedMeshPool : public UObject { GENERATED_BODY() public: /** @return an available GeneratedMesh from the pool (possibly allocating a new mesh) */ UFUNCTION(BlueprintCallable) UGeneratedMesh* RequestMesh(); /** Release a GeneratedMesh returned by RequestMesh() back to the pool */ UFUNCTION(BlueprintCallable) void ReturnMesh(UGeneratedMesh* Mesh); /** Release all GeneratedMeshes back to the pool */ UFUNCTION(BlueprintCallable) void ReturnAllMeshes(); /** Release all GeneratedMeshes back to the pool and allow them to be garbage collected */ UFUNCTION(BlueprintCallable) void FreeAllMeshes(); protected: UPROPERTY() int32 MeshCountSafetyThreshold = 1000; /** Meshes in the pool that are available */ UPROPERTY() TArray<UGeneratedMesh*> CachedMeshes; /** All meshes the pool has allocated */ UPROPERTY() TArray<UGeneratedMesh*> AllCreatedMeshes; };
45.900804
173
0.767303
0d0ba5efd142bfb4d1457920a46a06c634662cf6
122
h
C
include/proc.h
vladski-i/kalimba-hero
32be569ea3968501f2a7a9701feea6c6992a856a
[ "MIT" ]
1
2022-02-27T20:45:43.000Z
2022-02-27T20:45:43.000Z
include/proc.h
vladski-i/kalimba-hero
32be569ea3968501f2a7a9701feea6c6992a856a
[ "MIT" ]
3
2022-03-06T15:23:32.000Z
2022-03-06T15:25:06.000Z
include/proc.h
vladski-i/kalimba-hero
32be569ea3968501f2a7a9701feea6c6992a856a
[ "MIT" ]
null
null
null
#ifndef __PROC_H #define __PROC_H #include <stdint.h> void dft(uint32_t nframes, float *indata, float *outdata); #endif
15.25
58
0.754098
a6ce1110a79c92fd279189c407e95770912f53ab
427
h
C
LZBMVVMDemo/LZBMVVMDemo/Common/NetWork/BaseResquestModel.h
lzbgithubcode/LZBMVVMDemo
ead8f569680133fe8bd6e527b5cfc0fbe8e739e1
[ "Apache-2.0" ]
29
2017-03-19T11:08:41.000Z
2022-02-20T13:25:59.000Z
LZBMVVMDemo/LZBMVVMDemo/Common/NetWork/BaseResquestModel.h
lzbgithubcode/LZBMVVMDemo
ead8f569680133fe8bd6e527b5cfc0fbe8e739e1
[ "Apache-2.0" ]
null
null
null
LZBMVVMDemo/LZBMVVMDemo/Common/NetWork/BaseResquestModel.h
lzbgithubcode/LZBMVVMDemo
ead8f569680133fe8bd6e527b5cfc0fbe8e739e1
[ "Apache-2.0" ]
14
2016-08-30T05:36:46.000Z
2021-08-11T02:28:45.000Z
// // BaseResquestModel.h // LZBYKLive // // Created by zibin on 16/8/30. // Copyright © 2016年 刘子彬(更多项目源码分享平台“开发者源代码” 微信号:developerCode 作者简介:iOS开发者,喜爱交流分享). All rights reserved. // #import "BaseModel.h" #import "BaseHttpModel.h" #import "BaseResponseModel.h" @interface BaseResquestModel : BaseModel /** * 服务器需求地址url */ - (NSString *)url; /** * 网络请求模型参数转化为字典参数 */ - (NSDictionary *)modelToBaseResquestModel; @end
17.08
104
0.702576
813be4ce8ea4bdbb356ec120b3a2d57cad48c910
16,117
c
C
PVCJPEGDecode.c
liqi17thu/xv6-photo-viewer
a72af17a5856788a59fb26a430de52ebf7fcd410
[ "MIT-0" ]
null
null
null
PVCJPEGDecode.c
liqi17thu/xv6-photo-viewer
a72af17a5856788a59fb26a430de52ebf7fcd410
[ "MIT-0" ]
null
null
null
PVCJPEGDecode.c
liqi17thu/xv6-photo-viewer
a72af17a5856788a59fb26a430de52ebf7fcd410
[ "MIT-0" ]
null
null
null
#include "PVCJPEGDecode.h" uchar* GetImage(Context* ctx){ return (ctx->compNum == 1) ? ctx->comp[0].pixels : ctx->rgb; } int GetWidth(Context* ctx){ return ctx->width; } int GetHeight(Context* ctx){ return ctx->height; } uint GetImageSize(Context* ctx){ return ctx->width * ctx->height * ctx->compNum; } uchar _Clip(const int x){ return x < 0 ? 0: ((x > 0xFF) ? 0xFF : (uchar)x); } void _Skip(Context* ctx, int c){ ctx->pos += c; ctx->size -= c; ctx->length -= c; if(ctx->size < 0) ctx->result = SyntaxError; } int _DecodeLength(Context* ctx){ if(ctx->size < 2) ERROR_RETURN(SyntaxError); ctx->length = _Decode2Bytes(ctx->pos); if(ctx->length > ctx->size) ERROR_RETURN(SyntaxError); _Skip(ctx, 2); } int _Decode2Bytes(const uchar* pos){ return (pos[0] << 8) | pos[1]; } int _DecodeJPEG(Context* ctx, char* ZZ, const uchar* jpeg, const int size){ ctx->pos = jpeg; ctx->size = size & 0x7FFFFFFF; if( (ctx->size < 2) || ((ctx->pos[0] != 0xFF) || (ctx->pos[1] != 0xD8)) ) return NotJPEG; _Skip(ctx, 2); while(!ctx->result){ if(ctx->size < 0 || ctx->pos[0] != 0xFF) return SyntaxError; _Skip(ctx, 2); switch(ctx->pos[-1]){ case 0xC0: _DecodeSOF(ctx); break; case 0xC4: _DecodeDHT(ctx); break; case 0xDB: _DecodeDQT(ctx); break; case 0xDD: _DecodeDRI(ctx); break; case 0xDA: _DecodeSOS(ctx, ZZ); break; case 0xFE: _SkipMarker(ctx); break; default: if( (ctx->pos[-1] & 0xF0) == 0xE0) _SkipMarker(ctx); else return Unsupported; } } if(ctx->result != InternalFinished) return ctx->result; ctx->result = OK; _Convert(ctx); return ctx->result; } void _DecodeSOF(Context* ctx){ _DecodeLength(ctx); if(ctx->result)return; if(ctx->length < 9) ERROR_RETURN(SyntaxError); if(ctx->pos[0] != 8) ERROR_RETURN(Unsupported); ctx->height = _Decode2Bytes(ctx->pos + 1); ctx->width = _Decode2Bytes(ctx->pos + 3); ctx->compNum = ctx->pos[5]; _Skip(ctx, 6); switch(ctx->compNum){ case 1: case 3:break; default: ERROR_RETURN(Unsupported); } if(ctx->length < (ctx->compNum * 3)) ERROR_RETURN(SyntaxError); int i, Vmax=0, Hmax=0; Component* c; for(i=0, c=ctx->comp; i<ctx->compNum; ++i, ++c){ c->cid = ctx->pos[0]; if(!(c->ssx = ctx->pos[1] >> 4)) ERROR_RETURN(SyntaxError); if(!(c->ssy = ctx->pos[1] & 0xF)) ERROR_RETURN(SyntaxError); //ssx, ssy must be 1, 2, 4, 8... if(c->ssx & (c->ssx - 1)) ERROR_RETURN(Unsupported); if(c->ssy & (c->ssy - 1)) ERROR_RETURN(Unsupported); if((c->qtselect = ctx->pos[2]) & 0xFC) ERROR_RETURN(SyntaxError); _Skip(ctx, 3); ctx->qtused |= 1 << c->qtselect; if(c->ssx > Hmax) Hmax =c->ssx; if(c->ssy > Vmax) Vmax =c->ssy; } ctx->MCUsizex = Hmax << 3; ctx->MCUsizey = Vmax << 3; ctx->MCUwidth = (ctx->width + ctx->MCUsizex - 1) / ctx->MCUsizex; ctx->MCUheight = (ctx->height + ctx->MCUsizey - 1) / ctx->MCUsizey; for(i=0, c=ctx->comp; i< ctx->compNum; ++i, ++c){ c->width = (ctx->width * c->ssx + Hmax - 1) / Hmax; c->height = (ctx->height * c->ssy + Vmax - 1) / Vmax; c->stride = ctx->MCUwidth * ctx->MCUsizex * c->ssx / Hmax; if(((c->width < 3) && (c->ssx != Hmax)) || (c->height < 3) && (c->ssy != Vmax)) ERROR_RETURN(Unsupported); if(!(c->pixels = (uchar*)malloc(c->stride * (ctx->MCUheight * ctx->MCUsizey * c->ssy / Vmax)))) ERROR_RETURN(OutOfMemory); } if(ctx->compNum == 3){ ctx->rgb = (uchar*)malloc(ctx->width * ctx->height * ctx->compNum); if(!ctx->rgb) ERROR_RETURN(OutOfMemory); } _Skip(ctx, ctx->length); } void _DecodeDHT(Context* ctx){ int i, codelen, remain, spread, curcount; uchar counts[16]; _DecodeLength(ctx); if(ctx->result) return; while(ctx->length >= 17){ i = ctx->pos[0]; if(i & 0xEC) ERROR_RETURN(SyntaxError); if(i & 0x02) ERROR_RETURN(Unsupported); i =(i | (i >> 3)) & 3; for(codelen = 1; codelen <= 16; ++codelen){ counts[codelen - 1] = ctx->pos[codelen]; } _Skip(ctx, 17); VlcCode* vlc = &ctx->vlctable[i][0]; remain = spread = 65536; for(codelen = 1; codelen <= 16; ++codelen){ spread >>= 1; curcount = counts[codelen - 1]; if(!curcount) continue; if(ctx->length < curcount) ERROR_RETURN(SyntaxError); remain -= curcount << (16 - codelen); if(remain < 0) ERROR_RETURN(SyntaxError); for(i=0; i<curcount; ++i){ register uchar code = ctx->pos[i]; register int j = spread; while(j--){ vlc->bits = (uchar)codelen; vlc->code = code; ++vlc; } } _Skip(ctx, curcount); } while(remain--){ vlc->bits = 0; ++vlc; } } if(ctx->length) ERROR_RETURN(SyntaxError); } void _DecodeDQT(Context* ctx){ int i; uchar* t; _DecodeLength(ctx); if(ctx->result) return; while(ctx->length >= 65){ i = ctx->pos[0]; if(i & 0xEC) ERROR_RETURN(SyntaxError); if(i & 0x10) ERROR_RETURN(Unsupported); ctx->qtavail |= 1 << i; t =&ctx->qtable[i][0]; for(i=0; i<64; ++i) t[i] = ctx->pos[i + 1]; _Skip(ctx, 65); } if(ctx->length) ERROR_RETURN(SyntaxError); } void _DecodeDRI(Context* ctx){ _DecodeLength(ctx); if(ctx->result) return; if(ctx->length < 2) ERROR_RETURN(SyntaxError); ctx->rstInterval = _Decode2Bytes(ctx->pos); _Skip(ctx, ctx->length); } void _DecodeSOS(Context* ctx, char* ZZ){ int i, MCUx, MCUy, sbx, sby; int rstcount = ctx->rstInterval, nextrst = 0; Component* c; _DecodeLength(ctx); if(ctx->result) return; if((ctx->length < (4 + 2 * ctx->compNum)) || (ctx->pos[0] != ctx->compNum)) ERROR_RETURN(SyntaxError); _Skip(ctx, 1); for(i=0, c=ctx->comp; i<ctx->compNum; ++i, ++c){ if(ctx->pos[0] != c->cid) ERROR_RETURN(SyntaxError); if(ctx->pos[1] & 0xEC) ERROR_RETURN(SyntaxError); if(ctx->pos[1] & 0x02) ERROR_RETURN(Unsupported); c->dctabsel = ctx->pos[1] >> 4; c->actabsel = (ctx->pos[1] & 1) | 2; _Skip(ctx, 2); } if(ctx->pos[0] || (ctx->pos[1] != 0x3F)) ERROR_RETURN(SyntaxError); if(ctx->pos[2]) ERROR_RETURN(Unsupported); _Skip(ctx, ctx->length); for(MCUy=0; MCUy<ctx->MCUheight; ++MCUy) for(MCUx=0; MCUx<ctx->MCUwidth; ++MCUx){ for(i=0, c=ctx->comp; i<ctx->compNum; ++i,++c) for(sby=0; sby<c->ssy; ++sby) for(sbx=0; sbx<c->ssx; ++sbx){ _DecodeBlock(ctx, ZZ, c, &c->pixels[((MCUy * c->ssy + sby) * c->stride + MCUx * c->ssx + sbx) << 3]); if(ctx->result) return; } if(ctx->rstInterval && !(--rstcount)){ _ByteAlign(ctx); i = _GetBits(ctx, 16); if(((i & 0xFFF8) != 0xFFFD0) || ((i & 7) != nextrst)) ERROR_RETURN(SyntaxError); nextrst = (nextrst + 1) & 7; rstcount = ctx->rstInterval; for(i=0; i<3; ++i) ctx->comp[i].dcpred = 0; } } ctx->result = InternalFinished; } void _DecodeBlock(Context* ctx, char * ZZ, Component* c, uchar* out){ uchar code; int value, coef=0; memset(ctx->block, 0, sizeof(ctx->block)); c->dcpred += _GetVLC(ctx, &ctx->vlctable[c->dctabsel][0], 0); ctx->block[0] = (c->dcpred) * ctx->qtable[c->qtselect][0]; do{ value = _GetVLC(ctx, &ctx->vlctable[c->actabsel][0], &code); if(!code) break; // EOB if(!(code & 0x0F) && (code != 0xF0)) ERROR_RETURN(SyntaxError); coef += (code >> 4) + 1; if(coef>63) ERROR_RETURN(SyntaxError); ctx->block[(int)ZZ[coef]] = value * ctx->qtable[c->qtselect][coef]; }while(coef < 63); for(coef=0; coef<64; coef+=8) _RowIDCT(&ctx->block[coef]); for(coef=0; coef<8; ++coef) _ColIDCT(&ctx->block[coef], &out[coef], c->stride); } int _GetVLC(Context* ctx, VlcCode* vlc, uchar* code){ int value = _ShowBits(ctx, 16); int bits = vlc[value].bits; if(!bits){ ctx->result = SyntaxError; return 0; } _SkipBits(ctx, bits); value = vlc[value].code; if(code) *code = (uchar)value; bits = value & 15; if(!bits) return 0; value = _GetBits(ctx, bits); if(value < (1 << (bits - 1))) value += ((-1) << bits) + 1; return value; } int _ShowBits(Context* ctx, int bits){ uchar nextbyte; if(!bits) return 0; while(ctx->bufferBits < bits){ if(ctx->size <= 0){ ctx->buffer = (ctx->buffer << 8) | 0xFF; ctx->bufferBits += 8; continue; } nextbyte = *ctx->pos++; --ctx->size; ctx->bufferBits += 8; ctx->buffer = (ctx->buffer << 8) | nextbyte; if(nextbyte == 0xFF){ if(ctx->size){ uchar marker = *ctx->pos++; --ctx->size; switch(marker){ case 0: break; case 0xD9: ctx->size = 0; break; default: if((marker & 0xF8) != 0xD0) ctx->result = SyntaxError; else { ctx->buffer = (ctx->buffer << 8) | marker; ctx->bufferBits += 8; } } } else ctx->result = SyntaxError; } } return (ctx->buffer >> (ctx->bufferBits - bits)) & ((1 << bits) - 1); } void _SkipBits(Context* ctx, int bits){ if(ctx->bufferBits < bits) _ShowBits(ctx, bits); ctx->bufferBits -= bits; } int _GetBits(Context* ctx, int bits){ int res = _ShowBits(ctx, bits); _SkipBits(ctx, bits); return res; } enum { W1 = 2841, W2 = 2676, W3 = 2408, W5 = 1609, W6 = 1108, W7 = 565, }; void _RowIDCT(int* blk){ int x0, x1, x2, x3, x4, x5, x6, x7, x8; if(!((x1 = blk[4] << 11) | (x2 = blk[6]) | (x3 = blk[2]) | (x4 = blk[1]) | (x5 = blk[7]) | (x6 = blk[5]) | (x7 = blk[3]))) { blk[0] = blk[1] = blk[2] = blk[3] = blk[4] = blk[5] = blk[6] = blk[7] = blk[0] << 3; return; } x0 = (blk[0] << 11) + 128; x8 = W7 * (x4 + x5); x4 = x8 + (W1 - W7) * x4; x5 = x8 - (W1 + W7) * x5; x8 = W3 * (x6 + x7); x6 = x8 - (W3 - W5) * x6; x7 = x8 - (W3 + W5) * x7; x8 = x0 + x1; x0 -= x1; x1 = W6 * (x3 + x2); x2 = x1 - (W2 + W6) * x2; x3 = x1 + (W2 - W6) * x3; x1 = x4 + x6; x4 -= x6; x6 = x5 + x7; x5 -= x7; x7 = x8 + x3; x8 -= x3; x3 = x0 + x2; x0 -= x2; x2 = (181 * (x4 + x5) + 128) >> 8; x4 = (181 * (x4 - x5) + 128) >> 8; blk[0] = (x7 + x1) >> 8; blk[1] = (x3 + x2) >> 8; blk[2] = (x0 + x4) >> 8; blk[3] = (x8 + x6) >> 8; blk[4] = (x8 - x6) >> 8; blk[5] = (x0 - x4) >> 8; blk[6] = (x3 - x2) >> 8; blk[7] = (x7 - x1) >> 8; } void _ColIDCT(const int* blk, uchar* out, int stride){ int x0, x1, x2, x3, x4, x5, x6, x7, x8; if(!((x1 = blk[8 * 4] << 8) | (x2 = blk[8 * 6]) | (x3 = blk[8 * 2]) | (x4 = blk[8 * 1]) | (x5 = blk[8 * 7]) | (x6 = blk[8 * 5]) | (x7 = blk[8 * 3]))) { x1 = _Clip(((blk[0] + 32) >> 6) + 128); for (x0 = 8; x0; --x0) { *out = (unsigned char)x1; out += stride; } return; } x0 = (blk[0] << 8) + 8192; x8 = W7 * (x4 + x5) + 4; x4 = (x8 + (W1 - W7) * x4) >> 3; x5 = (x8 - (W1 + W7) * x5) >> 3; x8 = W3 * (x6 + x7) + 4; x6 = (x8 - (W3 - W5) * x6) >> 3; x7 = (x8 - (W3 + W5) * x7) >> 3; x8 = x0 + x1; x0 -= x1; x1 = W6 * (x3 + x2) + 4; x2 = (x1 - (W2 + W6) * x2) >> 3; x3 = (x1 + (W2 - W6) * x3) >> 3; x1 = x4 + x6; x4 -= x6; x6 = x5 + x7; x5 -= x7; x7 = x8 + x3; x8 -= x3; x3 = x0 + x2; x0 -= x2; x2 = (181 * (x4 + x5) + 128) >> 8; x4 = (181 * (x4 - x5) + 128) >> 8; *out = _Clip(((x7 + x1) >> 14) + 128); out += stride; *out = _Clip(((x3 + x2) >> 14) + 128); out += stride; *out = _Clip(((x0 + x4) >> 14) + 128); out += stride; *out = _Clip(((x8 + x6) >> 14) + 128); out += stride; *out = _Clip(((x8 - x6) >> 14) + 128); out += stride; *out = _Clip(((x0 - x4) >> 14) + 128); out += stride; *out = _Clip(((x3 - x2) >> 14) + 128); out += stride; *out = _Clip(((x7 - x1) >> 14) + 128); } void _ByteAlign(Context* ctx){ ctx->bufferBits &= 0xF8; } void _SkipMarker(Context* ctx){ _DecodeLength(ctx); _Skip(ctx, ctx->length); } void _Convert(Context* ctx){ int i; Component* c; for(i=0, c=ctx->comp; i<ctx->compNum; ++i, ++c){ while((c->width < ctx->width) || (c->height < ctx->height)){ if(c->width < ctx->width) _UpsampleH(ctx, c); if(ctx->result) return; if(c->height < ctx->height) _UpsampleV(ctx, c); if(ctx->result) return; } if((c->width < ctx->width) || (c->height < ctx->height)) ERROR_RETURN(InternalError); } } enum { CF4A = (-9), CF4B = (111), CF4C = (29), CF4D = (-3), CF3A = (28), CF3B = (109), CF3C = (-9), CF3X = (104), CF3Y = (27), CF3Z = (-3), CF2A = (139), CF2B = (-11), }; void _UpsampleH(Context* ctx, Component* c){ const int xmax = c->width - 3; uchar *out, *lin, *lout; int x, y; out = (uchar*)malloc((c->width * c->height) << 1); if(!out) ERROR_RETURN(OutOfMemory); lin = c->pixels; lout = out; y =c->height; while(y--){ lout[0] = CF(CF2A * lin[0] + CF2B * lin[1]); lout[1] = CF(CF3X * lin[0] + CF3Y * lin[1] + CF3Z * lin[2]); lout[2] = CF(CF3A * lin[0] + CF3B * lin[1] + CF3C * lin[2]); for (x = 0; x < xmax; ++x) { lout[(x << 1) + 3] = CF(CF4A * lin[x] + CF4B * lin[x + 1] + CF4C * lin[x + 2] + CF4D * lin[x + 3]); lout[(x << 1) + 4] = CF(CF4D * lin[x] + CF4C * lin[x + 1] + CF4B * lin[x + 2] + CF4A * lin[x + 3]); } lin += c->stride; lout += c->width << 1; lout[-3] = CF(CF3A * lin[-1] + CF3B * lin[-2] + CF3C * lin[-3]); lout[-2] = CF(CF3X * lin[-1] + CF3Y * lin[-2] + CF3Z * lin[-3]); lout[-1] = CF(CF2A * lin[-1] + CF2B * lin[-2]); } c->width <<= 1; c->stride = c->width; free(c->pixels); c->pixels = out; } void _UpsampleV(Context* ctx, Component* c){ const int w = c->width, s1 = c->stride, s2 = s1 + s1; uchar *out, *cin, *cout; int x, y; out = (uchar*)malloc((c->width * c->height) << 1); if(!out) ERROR_RETURN(OutOfMemory); for(x = 0; x<w; ++x){ cin = &c->pixels[x]; cout = &out[x]; *cout = CF(CF2A * cin[0] + CF2B * cin[s1]); cout += w; *cout = CF(CF3X * cin[0] + CF3Y * cin[s1] + CF3Z * cin[s2]); cout += w; *cout = CF(CF3A * cin[0] + CF3B * cin[s1] + CF3C * cin[s2]); cout += w; cin += s1; for(y=c->height-3; y; --y) { *cout = CF(CF4A * cin[-s1] + CF4B * cin[0] + CF4C * cin[s1] + CF4D * cin[s2]); cout += w; *cout = CF(CF4D * cin[-s1] + CF4C * cin[0] + CF4B * cin[s1] + CF4A * cin[s2]); cout += w; cin += s1; } cin += s1; *cout = CF(CF3A * cin[0] + CF3B * cin[-s1] + CF3C * cin[-s2]); cout += w; *cout = CF(CF3X * cin[0] + CF3Y * cin[-s1] + CF3Z * cin[-s2]); cout += w; *cout = CF(CF2A * cin[0] + CF2B * cin[-s1]); } c->height <<= 1; c->stride = c->width; free(c->pixels); c->pixels = out; } uchar CF(const int x){ return _Clip((x + 64) >> 7); }
32.169661
130
0.479556
81b5ad814e5fc103cfd0f4acb27a36bd13e8391a
148
h
C
crc32.h
shipwadkaw/XOR-CRC32-BIT
42da5ad51f93c438c04a3081f3dccf7188240b62
[ "BSD-2-Clause" ]
null
null
null
crc32.h
shipwadkaw/XOR-CRC32-BIT
42da5ad51f93c438c04a3081f3dccf7188240b62
[ "BSD-2-Clause" ]
null
null
null
crc32.h
shipwadkaw/XOR-CRC32-BIT
42da5ad51f93c438c04a3081f3dccf7188240b62
[ "BSD-2-Clause" ]
null
null
null
#ifndef __ALSKDJFLASLKDFJLA_crc32_h #define __ALSKDJFLASLKDFJLA_crc32_h int fLengthL(const char * fname); int crc32L(const char * fname); #endif
21.142857
35
0.804054
54b347366b5d15e5591827612ee685175c128edf
18,382
c
C
datasets/linux-4.11-rc3/drivers/gpu/drm/amd/powerplay/smumgr/fiji_smumgr.c
yijunyu/demo-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
2
2020-09-26T13:18:36.000Z
2021-06-16T20:38:20.000Z
datasets/linux-4.11-rc3/drivers/gpu/drm/amd/powerplay/smumgr/fiji_smumgr.c
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
null
null
null
datasets/linux-4.11-rc3/drivers/gpu/drm/amd/powerplay/smumgr/fiji_smumgr.c
yijunyu/demo-vscode-fast
11c0c84081a3181494b9c469bda42a313c457ad2
[ "BSD-2-Clause" ]
1
2020-05-08T04:02:02.000Z
2020-05-08T04:02:02.000Z
/* * Copyright 2015 Advanced Micro Devices, Inc. * * 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * */ #include "pp_debug.h" #include "smumgr.h" #include "smu73.h" #include "smu_ucode_xfer_vi.h" #include "fiji_smumgr.h" #include "fiji_ppsmc.h" #include "smu73_discrete.h" #include "ppatomctrl.h" #include "smu/smu_7_1_3_d.h" #include "smu/smu_7_1_3_sh_mask.h" #include "gmc/gmc_8_1_d.h" #include "gmc/gmc_8_1_sh_mask.h" #include "oss/oss_3_0_d.h" #include "gca/gfx_8_0_d.h" #include "bif/bif_5_0_d.h" #include "bif/bif_5_0_sh_mask.h" #include "fiji_pwrvirus.h" #include "fiji_smc.h" #define AVFS_EN_MSB 1568 #define AVFS_EN_LSB 1568 #define FIJI_SMC_SIZE 0x20000 static const struct SMU73_Discrete_GraphicsLevel avfs_graphics_level[8] = { /* Min Sclk pcie DeepSleep Activity CgSpll CgSpll spllSpread SpllSpread CcPwr CcPwr Sclk Display Enabled Enabled Voltage Power */ /* Voltage, Frequency, DpmLevel, DivId, Level, FuncCntl3, FuncCntl4, Spectrum, Spectrum2, DynRm, DynRm1 Did, Watermark, ForActivity, ForThrottle, UpHyst, DownHyst, DownHyst, Throttle */ { 0x3c0fd047, 0x30750000, 0x00, 0x03, 0x1e00, 0x00200410, 0x87020000, 0x21680000, 0x0c000000, 0, 0, 0x16, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 }, { 0xa00fd047, 0x409c0000, 0x01, 0x04, 0x1e00, 0x00800510, 0x87020000, 0x21680000, 0x11000000, 0, 0, 0x16, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 }, { 0x0410d047, 0x50c30000, 0x01, 0x00, 0x1e00, 0x00600410, 0x87020000, 0x21680000, 0x0d000000, 0, 0, 0x0e, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 }, { 0x6810d047, 0x60ea0000, 0x01, 0x00, 0x1e00, 0x00800410, 0x87020000, 0x21680000, 0x0e000000, 0, 0, 0x0c, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 }, { 0xcc10d047, 0xe8fd0000, 0x01, 0x00, 0x1e00, 0x00e00410, 0x87020000, 0x21680000, 0x0f000000, 0, 0, 0x0c, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 }, { 0x3011d047, 0x70110100, 0x01, 0x00, 0x1e00, 0x00400510, 0x87020000, 0x21680000, 0x10000000, 0, 0, 0x0c, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 }, { 0x9411d047, 0xf8240100, 0x01, 0x00, 0x1e00, 0x00a00510, 0x87020000, 0x21680000, 0x11000000, 0, 0, 0x0c, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 }, { 0xf811d047, 0x80380100, 0x01, 0x00, 0x1e00, 0x00000610, 0x87020000, 0x21680000, 0x12000000, 0, 0, 0x0c, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 } }; static int fiji_start_smu_in_protection_mode(struct pp_smumgr *smumgr) { int result = 0; /* Wait for smc boot up */ /* SMUM_WAIT_INDIRECT_FIELD_UNEQUAL(smumgr, SMC_IND, RCU_UC_EVENTS, boot_seq_done, 0); */ SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC, SMC_SYSCON_RESET_CNTL, rst_reg, 1); result = smu7_upload_smu_firmware_image(smumgr); if (result) return result; /* Clear status */ cgs_write_ind_register(smumgr->device, CGS_IND_REG__SMC, ixSMU_STATUS, 0); SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC, SMC_SYSCON_CLOCK_CNTL_0, ck_disable, 0); /* De-assert reset */ SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC, SMC_SYSCON_RESET_CNTL, rst_reg, 0); /* Wait for ROM firmware to initialize interrupt hendler */ /*SMUM_WAIT_VFPF_INDIRECT_REGISTER(smumgr, SMC_IND, SMC_INTR_CNTL_MASK_0, 0x10040, 0xFFFFFFFF); */ /* Set SMU Auto Start */ SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC, SMU_INPUT_DATA, AUTO_START, 1); /* Clear firmware interrupt enable flag */ cgs_write_ind_register(smumgr->device, CGS_IND_REG__SMC, ixFIRMWARE_FLAGS, 0); SMUM_WAIT_VFPF_INDIRECT_FIELD(smumgr, SMC_IND, RCU_UC_EVENTS, INTERRUPTS_ENABLED, 1); cgs_write_register(smumgr->device, mmSMC_MSG_ARG_0, 0x20000); cgs_write_register(smumgr->device, mmSMC_MESSAGE_0, PPSMC_MSG_Test); SMUM_WAIT_FIELD_UNEQUAL(smumgr, SMC_RESP_0, SMC_RESP, 0); /* Wait for done bit to be set */ SMUM_WAIT_VFPF_INDIRECT_FIELD_UNEQUAL(smumgr, SMC_IND, SMU_STATUS, SMU_DONE, 0); /* Check pass/failed indicator */ if (SMUM_READ_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC, SMU_STATUS, SMU_PASS) != 1) { PP_ASSERT_WITH_CODE(false, "SMU Firmware start failed!", return -1); } /* Wait for firmware to initialize */ SMUM_WAIT_VFPF_INDIRECT_FIELD(smumgr, SMC_IND, FIRMWARE_FLAGS, INTERRUPTS_ENABLED, 1); return result; } static int fiji_start_smu_in_non_protection_mode(struct pp_smumgr *smumgr) { int result = 0; /* wait for smc boot up */ SMUM_WAIT_VFPF_INDIRECT_FIELD_UNEQUAL(smumgr, SMC_IND, RCU_UC_EVENTS, boot_seq_done, 0); /* Clear firmware interrupt enable flag */ cgs_write_ind_register(smumgr->device, CGS_IND_REG__SMC, ixFIRMWARE_FLAGS, 0); /* Assert reset */ SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC, SMC_SYSCON_RESET_CNTL, rst_reg, 1); result = smu7_upload_smu_firmware_image(smumgr); if (result) return result; /* Set smc instruct start point at 0x0 */ smu7_program_jump_on_start(smumgr); /* Enable clock */ SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC, SMC_SYSCON_CLOCK_CNTL_0, ck_disable, 0); /* De-assert reset */ SMUM_WRITE_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC, SMC_SYSCON_RESET_CNTL, rst_reg, 0); /* Wait for firmware to initialize */ SMUM_WAIT_VFPF_INDIRECT_FIELD(smumgr, SMC_IND, FIRMWARE_FLAGS, INTERRUPTS_ENABLED, 1); return result; } static int fiji_setup_pwr_virus(struct pp_smumgr *smumgr) { int i, result = -1; uint32_t reg, data; const PWR_Command_Table *virus = PwrVirusTable; struct fiji_smumgr *priv = (struct fiji_smumgr *)(smumgr->backend); priv->avfs.AvfsBtcStatus = AVFS_LOAD_VIRUS; for (i = 0; (i < PWR_VIRUS_TABLE_SIZE); i++) { switch (virus->command) { case PwrCmdWrite: reg = virus->reg; data = virus->data; cgs_write_register(smumgr->device, reg, data); break; case PwrCmdEnd: priv->avfs.AvfsBtcStatus = AVFS_BTC_VIRUS_LOADED; result = 0; break; default: pr_err("Table Exit with Invalid Command!"); priv->avfs.AvfsBtcStatus = AVFS_BTC_VIRUS_FAIL; result = -1; break; } virus++; } return result; } static int fiji_start_avfs_btc(struct pp_smumgr *smumgr) { int result = 0; struct fiji_smumgr *priv = (struct fiji_smumgr *)(smumgr->backend); priv->avfs.AvfsBtcStatus = AVFS_BTC_STARTED; if (priv->avfs.AvfsBtcParam) { if (!smum_send_msg_to_smc_with_parameter(smumgr, PPSMC_MSG_PerformBtc, priv->avfs.AvfsBtcParam)) { if (!smum_send_msg_to_smc(smumgr, PPSMC_MSG_EnableAvfs)) { priv->avfs.AvfsBtcStatus = AVFS_BTC_COMPLETED_UNSAVED; result = 0; } else { pr_err("[AVFS][fiji_start_avfs_btc] Attempt" " to Enable AVFS Failed!"); smum_send_msg_to_smc(smumgr, PPSMC_MSG_DisableAvfs); result = -1; } } else { pr_err("[AVFS][fiji_start_avfs_btc] " "PerformBTC SMU msg failed"); result = -1; } } /* Soft-Reset to reset the engine before loading uCode */ /* halt */ cgs_write_register(smumgr->device, mmCP_MEC_CNTL, 0x50000000); /* reset everything */ cgs_write_register(smumgr->device, mmGRBM_SOFT_RESET, 0xffffffff); /* clear reset */ cgs_write_register(smumgr->device, mmGRBM_SOFT_RESET, 0); return result; } static int fiji_setup_pm_fuse_for_avfs(struct pp_smumgr *smumgr) { int result = 0; uint32_t table_start; uint32_t charz_freq_addr, inversion_voltage_addr, charz_freq; uint16_t inversion_voltage; charz_freq = 0x30750000; /* In 10KHz units 0x00007530 Actual value */ inversion_voltage = 0x1A04; /* mV Q14.2 0x41A Actual value */ PP_ASSERT_WITH_CODE(0 == smu7_read_smc_sram_dword(smumgr, SMU7_FIRMWARE_HEADER_LOCATION + offsetof(SMU73_Firmware_Header, PmFuseTable), &table_start, 0x40000), "[AVFS][Fiji_SetupGfxLvlStruct] SMU could not communicate " "starting address of PmFuse structure", return -1;); charz_freq_addr = table_start + offsetof(struct SMU73_Discrete_PmFuses, PsmCharzFreq); inversion_voltage_addr = table_start + offsetof(struct SMU73_Discrete_PmFuses, InversionVoltage); result = smu7_copy_bytes_to_smc(smumgr, charz_freq_addr, (uint8_t *)(&charz_freq), sizeof(charz_freq), 0x40000); PP_ASSERT_WITH_CODE(0 == result, "[AVFS][fiji_setup_pm_fuse_for_avfs] charz_freq could not " "be populated.", return -1;); result = smu7_copy_bytes_to_smc(smumgr, inversion_voltage_addr, (uint8_t *)(&inversion_voltage), sizeof(inversion_voltage), 0x40000); PP_ASSERT_WITH_CODE(0 == result, "[AVFS][fiji_setup_pm_fuse_for_avfs] " "charz_freq could not be populated.", return -1;); return result; } static int fiji_setup_graphics_level_structure(struct pp_smumgr *smumgr) { int32_t vr_config; uint32_t table_start; uint32_t level_addr, vr_config_addr; uint32_t level_size = sizeof(avfs_graphics_level); PP_ASSERT_WITH_CODE(0 == smu7_read_smc_sram_dword(smumgr, SMU7_FIRMWARE_HEADER_LOCATION + offsetof(SMU73_Firmware_Header, DpmTable), &table_start, 0x40000), "[AVFS][Fiji_SetupGfxLvlStruct] SMU could not " "communicate starting address of DPM table", return -1;); /* Default value for vr_config = * VR_MERGED_WITH_VDDC + VR_STATIC_VOLTAGE(VDDCI) */ vr_config = 0x01000500; /* Real value:0x50001 */ vr_config_addr = table_start + offsetof(SMU73_Discrete_DpmTable, VRConfig); PP_ASSERT_WITH_CODE(0 == smu7_copy_bytes_to_smc(smumgr, vr_config_addr, (uint8_t *)&vr_config, sizeof(int32_t), 0x40000), "[AVFS][Fiji_SetupGfxLvlStruct] Problems copying " "vr_config value over to SMC", return -1;); level_addr = table_start + offsetof(SMU73_Discrete_DpmTable, GraphicsLevel); PP_ASSERT_WITH_CODE(0 == smu7_copy_bytes_to_smc(smumgr, level_addr, (uint8_t *)(&avfs_graphics_level), level_size, 0x40000), "[AVFS][Fiji_SetupGfxLvlStruct] Copying of DPM table failed!", return -1;); return 0; } /* Work in Progress */ static int fiji_restore_vft_table(struct pp_smumgr *smumgr) { struct fiji_smumgr *priv = (struct fiji_smumgr *)(smumgr->backend); if (AVFS_BTC_COMPLETED_SAVED == priv->avfs.AvfsBtcStatus) { priv->avfs.AvfsBtcStatus = AVFS_BTC_COMPLETED_RESTORED; return 0; } else return -EINVAL; } /* Work in Progress */ static int fiji_save_vft_table(struct pp_smumgr *smumgr) { struct fiji_smumgr *priv = (struct fiji_smumgr *)(smumgr->backend); if (AVFS_BTC_COMPLETED_SAVED == priv->avfs.AvfsBtcStatus) { priv->avfs.AvfsBtcStatus = AVFS_BTC_COMPLETED_RESTORED; return 0; } else return -EINVAL; } static int fiji_avfs_event_mgr(struct pp_smumgr *smumgr, bool smu_started) { struct fiji_smumgr *priv = (struct fiji_smumgr *)(smumgr->backend); switch (priv->avfs.AvfsBtcStatus) { case AVFS_BTC_COMPLETED_SAVED: /*S3 State - Pre SMU Start */ priv->avfs.AvfsBtcStatus = AVFS_BTC_RESTOREVFT_FAILED; PP_ASSERT_WITH_CODE(0 == fiji_restore_vft_table(smumgr), "[AVFS][fiji_avfs_event_mgr] Could not Copy Graphics " "Level table over to SMU", return -1;); priv->avfs.AvfsBtcStatus = AVFS_BTC_COMPLETED_RESTORED; break; case AVFS_BTC_COMPLETED_RESTORED: /*S3 State - Post SMU Start*/ priv->avfs.AvfsBtcStatus = AVFS_BTC_SMUMSG_ERROR; PP_ASSERT_WITH_CODE(0 == smum_send_msg_to_smc(smumgr, 0x666), "[AVFS][fiji_avfs_event_mgr] SMU did not respond " "correctly to VftTableIsValid Msg", return -1;); priv->avfs.AvfsBtcStatus = AVFS_BTC_SMUMSG_ERROR; PP_ASSERT_WITH_CODE(0 == smum_send_msg_to_smc(smumgr, PPSMC_MSG_EnableAvfs), "[AVFS][fiji_avfs_event_mgr] SMU did not respond " "correctly to EnableAvfs Message Msg", return -1;); priv->avfs.AvfsBtcStatus = AVFS_BTC_COMPLETED_SAVED; break; case AVFS_BTC_BOOT: /*Cold Boot State - Post SMU Start*/ if (!smu_started) break; priv->avfs.AvfsBtcStatus = AVFS_BTC_FAILED; PP_ASSERT_WITH_CODE(0 == fiji_setup_pm_fuse_for_avfs(smumgr), "[AVFS][fiji_avfs_event_mgr] Failure at " "fiji_setup_pm_fuse_for_avfs", return -1;); priv->avfs.AvfsBtcStatus = AVFS_BTC_DPMTABLESETUP_FAILED; PP_ASSERT_WITH_CODE(0 == fiji_setup_graphics_level_structure(smumgr), "[AVFS][fiji_avfs_event_mgr] Could not Copy Graphics Level" " table over to SMU", return -1;); priv->avfs.AvfsBtcStatus = AVFS_BTC_VIRUS_FAIL; PP_ASSERT_WITH_CODE(0 == fiji_setup_pwr_virus(smumgr), "[AVFS][fiji_avfs_event_mgr] Could not setup " "Pwr Virus for AVFS ", return -1;); priv->avfs.AvfsBtcStatus = AVFS_BTC_FAILED; PP_ASSERT_WITH_CODE(0 == fiji_start_avfs_btc(smumgr), "[AVFS][fiji_avfs_event_mgr] Failure at " "fiji_start_avfs_btc. AVFS Disabled", return -1;); priv->avfs.AvfsBtcStatus = AVFS_BTC_SAVEVFT_FAILED; PP_ASSERT_WITH_CODE(0 == fiji_save_vft_table(smumgr), "[AVFS][fiji_avfs_event_mgr] Could not save VFT Table", return -1;); priv->avfs.AvfsBtcStatus = AVFS_BTC_COMPLETED_SAVED; break; case AVFS_BTC_DISABLED: /* Do nothing */ break; case AVFS_BTC_NOTSUPPORTED: /* Do nothing */ break; default: pr_err("[AVFS] Something is broken. See log!"); break; } return 0; } static int fiji_start_smu(struct pp_smumgr *smumgr) { int result = 0; struct fiji_smumgr *priv = (struct fiji_smumgr *)(smumgr->backend); /* Only start SMC if SMC RAM is not running */ if (!(smu7_is_smc_ram_running(smumgr) || cgs_is_virtualization_enabled(smumgr->device))) { fiji_avfs_event_mgr(smumgr, false); /* Check if SMU is running in protected mode */ if (0 == SMUM_READ_VFPF_INDIRECT_FIELD(smumgr->device, CGS_IND_REG__SMC, SMU_FIRMWARE, SMU_MODE)) { result = fiji_start_smu_in_non_protection_mode(smumgr); if (result) return result; } else { result = fiji_start_smu_in_protection_mode(smumgr); if (result) return result; } fiji_avfs_event_mgr(smumgr, true); } /* To initialize all clock gating before RLC loaded and running.*/ cgs_set_clockgating_state(smumgr->device, AMD_IP_BLOCK_TYPE_GFX, AMD_CG_STATE_GATE); cgs_set_clockgating_state(smumgr->device, AMD_IP_BLOCK_TYPE_GMC, AMD_CG_STATE_GATE); cgs_set_clockgating_state(smumgr->device, AMD_IP_BLOCK_TYPE_SDMA, AMD_CG_STATE_GATE); cgs_set_clockgating_state(smumgr->device, AMD_IP_BLOCK_TYPE_COMMON, AMD_CG_STATE_GATE); /* Setup SoftRegsStart here for register lookup in case * DummyBackEnd is used and ProcessFirmwareHeader is not executed */ smu7_read_smc_sram_dword(smumgr, SMU7_FIRMWARE_HEADER_LOCATION + offsetof(SMU73_Firmware_Header, SoftRegisters), &(priv->smu7_data.soft_regs_start), 0x40000); result = smu7_request_smu_load_fw(smumgr); return result; } static bool fiji_is_hw_avfs_present(struct pp_smumgr *smumgr) { uint32_t efuse = 0; uint32_t mask = (1 << ((AVFS_EN_MSB - AVFS_EN_LSB) + 1)) - 1; if (cgs_is_virtualization_enabled(smumgr->device)) return 0; if (!atomctrl_read_efuse(smumgr->device, AVFS_EN_LSB, AVFS_EN_MSB, mask, &efuse)) { if (efuse) return true; } return false; } /** * Write a 32bit value to the SMC SRAM space. * ALL PARAMETERS ARE IN HOST BYTE ORDER. * @param smumgr the address of the powerplay hardware manager. * @param smc_addr the address in the SMC RAM to access. * @param value to write to the SMC SRAM. */ static int fiji_smu_init(struct pp_smumgr *smumgr) { int i; struct fiji_smumgr *fiji_priv = NULL; fiji_priv = kzalloc(sizeof(struct fiji_smumgr), GFP_KERNEL); if (fiji_priv == NULL) return -ENOMEM; smumgr->backend = fiji_priv; if (smu7_init(smumgr)) return -EINVAL; fiji_priv->avfs.AvfsBtcStatus = AVFS_BTC_BOOT; if (fiji_is_hw_avfs_present(smumgr)) /* AVFS Parameter * 0 - BTC DC disabled, BTC AC disabled * 1 - BTC DC enabled, BTC AC disabled * 2 - BTC DC disabled, BTC AC enabled * 3 - BTC DC enabled, BTC AC enabled * Default is 0 - BTC DC disabled, BTC AC disabled */ fiji_priv->avfs.AvfsBtcParam = 0; else fiji_priv->avfs.AvfsBtcStatus = AVFS_BTC_NOTSUPPORTED; for (i = 0; i < SMU73_MAX_LEVELS_GRAPHICS; i++) fiji_priv->activity_target[i] = 30; return 0; } const struct pp_smumgr_func fiji_smu_funcs = { .smu_init = &fiji_smu_init, .smu_fini = &smu7_smu_fini, .start_smu = &fiji_start_smu, .check_fw_load_finish = &smu7_check_fw_load_finish, .request_smu_load_fw = &smu7_reload_firmware, .request_smu_load_specific_fw = NULL, .send_msg_to_smc = &smu7_send_msg_to_smc, .send_msg_to_smc_with_parameter = &smu7_send_msg_to_smc_with_parameter, .download_pptable_settings = NULL, .upload_pptable_settings = NULL, .update_smc_table = fiji_update_smc_table, .get_offsetof = fiji_get_offsetof, .process_firmware_header = fiji_process_firmware_header, .init_smc_table = fiji_init_smc_table, .update_sclk_threshold = fiji_update_sclk_threshold, .thermal_setup_fan_table = fiji_thermal_setup_fan_table, .populate_all_graphic_levels = fiji_populate_all_graphic_levels, .populate_all_memory_levels = fiji_populate_all_memory_levels, .get_mac_definition = fiji_get_mac_definition, .initialize_mc_reg_table = fiji_initialize_mc_reg_table, .is_dpm_running = fiji_is_dpm_running, };
35.147228
200
0.728974
0731d9aef1977087c35f95071c80d9786107af8f
7,594
h
C
qemu/include/hw/ptimer.h
WUSTL-CSPL/RT-TEE
aafb3e9ff6c6e744c6bce1e42bcb198e1063efcc
[ "MIT" ]
55
2019-12-20T03:25:14.000Z
2022-01-16T07:19:47.000Z
qemu/include/hw/ptimer.h
WUSTL-CSPL/RT-TEE
aafb3e9ff6c6e744c6bce1e42bcb198e1063efcc
[ "MIT" ]
3
2021-07-27T19:36:05.000Z
2021-12-31T02:20:53.000Z
qemu/include/hw/ptimer.h
WUSTL-CSPL/RT-TEE
aafb3e9ff6c6e744c6bce1e42bcb198e1063efcc
[ "MIT" ]
11
2020-08-06T03:59:45.000Z
2022-02-25T02:31:59.000Z
/* * General purpose implementation of a simple periodic countdown timer. * * Copyright (c) 2007 CodeSourcery. * * This code is licensed under the GNU LGPL. */ #ifndef PTIMER_H #define PTIMER_H #include "qemu-common.h" #include "qemu/timer.h" #include "migration/vmstate.h" /* The ptimer API implements a simple periodic countdown timer. * The countdown timer has a value (which can be read and written via * ptimer_get_count() and ptimer_set_count()). When it is enabled * using ptimer_run(), the value will count downwards at the frequency * which has been configured using ptimer_set_period() or ptimer_set_freq(). * When it reaches zero it will trigger a QEMU bottom half handler, and * can be set to either reload itself from a specified limit value * and keep counting down, or to stop (as a one-shot timer). * * Forgetting to set the period/frequency (or setting it to zero) is a * bug in the QEMU device and will cause warning messages to be printed * to stderr when the guest attempts to enable the timer. */ /* The default ptimer policy retains backward compatibility with the legacy * timers. Custom policies are adjusting the default one. Consider providing * a correct policy for your timer. * * The rough edges of the default policy: * - Starting to run with a period = 0 emits error message and stops the * timer without a trigger. * * - Setting period to 0 of the running timer emits error message and * stops the timer without a trigger. * * - Starting to run with counter = 0 or setting it to "0" while timer * is running causes a trigger and reloads counter with a limit value. * If limit = 0, ptimer emits error message and stops the timer. * * - Counter value of the running timer is one less than the actual value. * * - Changing period/frequency of the running timer loses time elapsed * since the last period, effectively restarting the timer with a * counter = counter value at the moment of change (.i.e. one less). */ #define PTIMER_POLICY_DEFAULT 0 /* Periodic timer counter stays with "0" for a one period before wrapping * around. */ #define PTIMER_POLICY_WRAP_AFTER_ONE_PERIOD (1 << 0) /* Running periodic timer that has counter = limit = 0 would continuously * re-trigger every period. */ #define PTIMER_POLICY_CONTINUOUS_TRIGGER (1 << 1) /* Starting to run with/setting counter to "0" won't trigger immediately, * but after a one period for both oneshot and periodic modes. */ #define PTIMER_POLICY_NO_IMMEDIATE_TRIGGER (1 << 2) /* Starting to run with/setting counter to "0" won't re-load counter * immediately, but after a one period. */ #define PTIMER_POLICY_NO_IMMEDIATE_RELOAD (1 << 3) /* Make counter value of the running timer represent the actual value and * not the one less. */ #define PTIMER_POLICY_NO_COUNTER_ROUND_DOWN (1 << 4) /* * Starting to run with a zero counter, or setting the counter to "0" via * ptimer_set_count() or ptimer_set_limit() will not trigger the timer * (though it will cause a reload). Only a counter decrement to "0" * will cause a trigger. Not compatible with NO_IMMEDIATE_TRIGGER; * ptimer_init() will assert() that you don't set both. */ #define PTIMER_POLICY_TRIGGER_ONLY_ON_DECREMENT (1 << 5) /* ptimer.c */ typedef struct ptimer_state ptimer_state; typedef void (*ptimer_cb)(void *opaque); /** * ptimer_init - Allocate and return a new ptimer * @bh: QEMU bottom half which is run on timer expiry * @policy: PTIMER_POLICY_* bits specifying behaviour * * The ptimer returned must be freed using ptimer_free(). * The ptimer takes ownership of @bh and will delete it * when the ptimer is eventually freed. */ ptimer_state *ptimer_init(QEMUBH *bh, uint8_t policy_mask); /** * ptimer_free - Free a ptimer * @s: timer to free * * Free a ptimer created using ptimer_init() (including * deleting the bottom half which it is using). */ void ptimer_free(ptimer_state *s); /** * ptimer_set_period - Set counter increment interval in nanoseconds * @s: ptimer to configure * @period: period of the counter in nanoseconds * * Note that if your counter behaviour is specified as having a * particular frequency rather than a period then ptimer_set_freq() * may be more appropriate. */ void ptimer_set_period(ptimer_state *s, int64_t period); /** * ptimer_set_freq - Set counter frequency in Hz * @s: ptimer to configure * @freq: counter frequency in Hz * * This does the same thing as ptimer_set_period(), so you only * need to call one of them. If the counter behaviour is specified * as setting the frequency then this function is more appropriate, * because it allows specifying an effective period which is * precise to fractions of a nanosecond, avoiding rounding errors. */ void ptimer_set_freq(ptimer_state *s, uint32_t freq); /** * ptimer_get_limit - Get the configured limit of the ptimer * @s: ptimer to query * * This function returns the current limit (reload) value * of the down-counter; that is, the value which it will be * reset to when it hits zero. * * Generally timer devices using ptimers should be able to keep * their reload register state inside the ptimer using the get * and set limit functions rather than needing to also track it * in their own state structure. */ uint64_t ptimer_get_limit(ptimer_state *s); /** * ptimer_set_limit - Set the limit of the ptimer * @s: ptimer * @limit: initial countdown value * @reload: if nonzero, then reset the counter to the new limit * * Set the limit value of the down-counter. The @reload flag can * be used to emulate the behaviour of timers which immediately * reload the counter when their reload register is written to. */ void ptimer_set_limit(ptimer_state *s, uint64_t limit, int reload); /** * ptimer_get_count - Get the current value of the ptimer * @s: ptimer * * Return the current value of the down-counter. This will * return the correct value whether the counter is enabled or * disabled. */ uint64_t ptimer_get_count(ptimer_state *s); /** * ptimer_set_count - Set the current value of the ptimer * @s: ptimer * @count: count value to set * * Set the value of the down-counter. If the counter is currently * enabled this will arrange for a timer callback at the appropriate * point in the future. */ void ptimer_set_count(ptimer_state *s, uint64_t count); /** * ptimer_run - Start a ptimer counting * @s: ptimer * @oneshot: non-zero if this timer should only count down once * * Start a ptimer counting down; when it reaches zero the bottom half * passed to ptimer_init() will be invoked. If the @oneshot argument is zero, * the counter value will then be reloaded from the limit and it will * start counting down again. If @oneshot is non-zero, then the counter * will disable itself when it reaches zero. */ void ptimer_run(ptimer_state *s, int oneshot); /** * ptimer_stop - Stop a ptimer counting * @s: ptimer * * Pause a timer (the count stays at its current value until ptimer_run() * is called to start it counting again). * * Note that this can cause it to "lose" time, even if it is immediately * restarted. */ void ptimer_stop(ptimer_state *s); extern const VMStateDescription vmstate_ptimer; #define VMSTATE_PTIMER(_field, _state) \ VMSTATE_STRUCT_POINTER_V(_field, _state, 1, vmstate_ptimer, ptimer_state) #define VMSTATE_PTIMER_ARRAY(_f, _s, _n) \ VMSTATE_ARRAY_OF_POINTER_TO_STRUCT(_f, _s, _n, 0, \ vmstate_ptimer, ptimer_state) #endif
35.820755
77
0.728733
60cdf96c2b20f2c2d733073aaeb9df4ca75bd9b5
1,628
h
C
src/baye/paccount.h
GDxU/ibayesanfight
30c67bad75e6cc7e28578d98419244fc324ed315
[ "MIT" ]
4
2020-12-22T08:14:47.000Z
2022-01-11T02:06:55.000Z
src/baye/paccount.h
lyxverycool/sanguobaye_c
f6484b1b67219633dd7e6603d7c53d1a801e9992
[ "MIT" ]
null
null
null
src/baye/paccount.h
lyxverycool/sanguobaye_c
f6484b1b67219633dd7e6603d7c53d1a801e9992
[ "MIT" ]
2
2021-01-18T04:46:36.000Z
2022-03-26T05:05:52.000Z
#ifndef PACCOUNT_H #define PACCOUNT_H /*------------------------------- 特效资源结构定义 魔法特效序号200以后为幻身魔法特效 序号,到239共40个。 魔法特效序号239以后为玩家角色合体 普通攻击效果所用 过场特效序号239以后为异常状态特效 动画所用,249以后为主菜单动画所用 ---------------------------------*/ typedef struct {/*特效数据结构(5 byte)*/ U8 x; /*该图片在屏幕上输出的坐标*/ U8 y; /*该图片在屏幕上输出的坐标*/ U8 cdelay; /*本张图片显示延时*/ U8 ndelay; /*下一张图片在本张图片显示多长时间后显示*/ U8 picIdx; /*本桢所用图片序号*/ }SPEUNIT; typedef struct { /*特效图片组结构(4 byte)*/ U8 type; /*特效类型*/ U8 idx; /*特效序号(1~239为任意分配的序号)*/ U8 count; /*桢数*/ U8 picmax; /*最大图片序号*/ U8 startfrm; /*播放起始帧*/ U8 endfrm; /*播放终止帧*/ /*SPEUNIT spe[252];*/ /*桢数据项*/ /*U8 *dat[252];*/ /*图片数据区*/ }SPERES; typedef struct PosItem { U8 x0; U8 y0; U8 x1; U8 y1; U8 sx; U8 sy; U8 ex; U8 ey; }PosItemType; typedef struct MenuStruct { U8 sx; U8 sy; U8 ex; U8 ey; U8 top; U8 set; U8 count; U8 *menustr[20]; }MenuType; typedef struct CitySet { U8 x; U8 y; U8 setx; U8 sety; }CitySetType; #define CITYMAP_W g_engineConfig.cityMapWidth /*地图宽*/ #define CITYMAP_H g_engineConfig.cityMapHeight /*地图高*/ #define CITYMAP_TIL_W 16 /*地图块大小*/ #define CITYMAP_TIL_H 16 /*地图块大小*/ #define CITY_ICON_W 8 /*城市图标大小*/ #define CITY_ICON_H 8 /*城市图标大小*/ #define SHOWMAP_WS ((WK_EX-WK_SX+1+1)/CITYMAP_TIL_W-2) /*屏幕显示地图块数*/ #define SHOWMAP_HS ((WK_EY-WK_SY+1)/CITYMAP_TIL_H) /*屏幕显示地图块数*/ #define SHOWMAP_WS_MAX 30 /*屏幕最大支持显示地图块数*/ #define SHOWMAP_HS_MAX 30 /*屏幕最大支持显示地图块数*/ FAR void InitItem(U8 x0,U8 y0,U8 x1,U8 y1,PosItemType *positem); FAR U8 AddItem(U8 wid,U8 hig,PosItemType *positem,U8 *x,U8 *y); FAR U8 NextLineItem(PosItemType *positem); #endif
19.380952
67
0.656634
c262d2e931d0f8698dc9a422e7d3324cbcf57555
3,980
c
C
src/addfname.c
wernsey/zoo
6264a99f9aea7afb4deb3089bd6d4d036e94f9ab
[ "Unlicense" ]
5
2020-12-20T21:07:41.000Z
2022-01-25T16:43:42.000Z
src/addfname.c
wernsey/zoo
6264a99f9aea7afb4deb3089bd6d4d036e94f9ab
[ "Unlicense" ]
1
2020-12-20T20:27:19.000Z
2020-12-21T12:34:12.000Z
src/addfname.c
wernsey/zoo
6264a99f9aea7afb4deb3089bd6d4d036e94f9ab
[ "Unlicense" ]
2
2020-09-24T15:25:26.000Z
2020-12-20T21:08:01.000Z
/* Adds a filename to global list. * * This global list will eventually be searched by the inlist() function. * The second and subsequent parameters suppplied are stored with the * name of the file and returned by inlist. * * The contents of this file are hereby released to the public domain. * * -- Rahul Dhesi 2004/06/19 */ #include "options.h" #include "zooio.h" #include "various.h" #include "zoo.h" #include "zoofns.h" #include "zoomem.h" /* to get LIST_SIZE */ #define FENTRY_BSIZE 80 /* allocation granularity for fentry below */ #ifdef IGNORECASE #define COMPARE str_icmp #else #define COMPARE strcmp #endif #define FN(IDX) (justname ? nameptr(fentry[IDX]->fname) : fentry[IDX]->fname) static struct item **fentry; /* array of ptrs to file information structs */ static unsigned sz_fentry; /* its current size */ static int lastname = 0; /* index of last name */ struct item { /* global filename list entry */ char *fname; long position; unsigned int date; unsigned int time; unsigned vflag; unsigned version_no; }; void addfname(fname, position, date, time, vflag, version_no) char *fname; long position; unsigned int date, time; unsigned vflag; unsigned version_no; { if (lastname == 0) { sz_fentry = FENTRY_BSIZE; fentry = (struct item **)ealloc(sizeof(struct item *) * sz_fentry); fentry[0] = (struct item *)ealloc(sizeof(struct item)); } /* allocated more memory if needed */ if ((unsigned)lastname >= sz_fentry - 3) { sz_fentry += FENTRY_BSIZE; fentry = (struct item **) erealloc(fentry, sizeof(struct item *) * sz_fentry); } fentry[lastname]->fname = str_dup(fname); fentry[lastname]->position = position; fentry[lastname]->date = date; fentry[lastname]->time = time; fentry[lastname]->vflag = vflag; fentry[lastname]->version_no = version_no; lastname++; /* allocate memory for empty entry at end */ fentry[lastname] = (struct item *)ealloc(sizeof(struct item)); fentry[lastname]->fname = NULL; } void fname_free(void) { while (lastname >= 0) { efree(fentry[lastname]->fname); free(fentry[lastname--]); } if (fentry) free(fentry); } /** * inlist() Examines global list built by addfname() to see if supplied * filename is in the list. * * If found, returns the file's position within the archive as the function * value and the date, time, version flag, and version number as parameters. * If not found, returns -1. Also returns the highest version no. seen * for this filename and the vflag associated with that version. * * A simple sequential search is done. * * If justname is nonzero, then the search is for the filename only * without the directory prefix; else it is for the full * pathname. */ long inlist(fname, date, time, this_version_no, high_vflag, high_version_no, high_pos, justname) char *fname; unsigned int *date, *time; unsigned *high_vflag; unsigned *this_version_no; unsigned *high_version_no; long *high_pos; int justname; { int i = 0; int j; *high_version_no = 0; if (justname) fname = nameptr(fname); /* if directory wanted */ if (fentry[lastname]->fname) efree(fentry[lastname]->fname); fentry[lastname]->fname = str_dup(fname); /* sentinel */ fentry[lastname]->version_no = 0; while (COMPARE(fname, FN(i)) != 0) i++; if (i == lastname) return -1L; *date = fentry[i]->date; *time = fentry[i]->time; *high_pos = fentry[i]->position; *high_vflag = fentry[i]->vflag; /* find highest version no. for file */ for (j = i; j < lastname; j++) { if (COMPARE(fname, FN(j)) == 0) { if (*high_version_no < fentry[j]->version_no) { *high_version_no = fentry[j]->version_no; *high_vflag = fentry[j]->vflag; *high_pos = fentry[j]->position; *date = fentry[j]->date; *time = fentry[j]->time; } } } *this_version_no = fentry[i]->version_no; return fentry[i]->position; }
26.891892
96
0.666834
fc29ed6acc4b622e609f67d105d82dff0ad263e4
15,001
h
C
ace/tao/tao/Stub.h
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/tao/tao/Stub.h
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/tao/tao/Stub.h
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
// This may look like C, but it's really -*- C++ -*- //============================================================================= /** * @file Stub.h * * Stub.h,v 1.84 2001/08/03 03:46:52 othman Exp * * * Data structures used by static and dynamic stubs, and to a * lesser degree by skeletons * * Header file for Win32 C/C++/COM interface to one kind of CORBA * remote invocation framework. This is for use by * compiler-generated code, not by portable applications! * * These constitute the stub API to this "ORB Core." Such * interfaces are not specified by OMG, and may differ between * different ORBs. This one has the particular advantage that * stubs can be quite small. * * * @author Copyright 1994-1995 by Sun Microsystems, Inc. */ //============================================================================= #ifndef TAO_STUB_H #define TAO_STUB_H #include "ace/pre.h" #include "tao/Pluggable.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #include "tao/MProfile.h" #include "tao/ORB.h" #include "tao/ORB_Core.h" // Forward declarations. class TAO_RelativeRoundtripTimeoutPolicy; class TAO_Client_Priority_Policy; class TAO_Sync_Scope_Policy; class TAO_Buffering_Constraint_Policy; class TAO_Sync_Strategy; class TAO_GIOP_Invocation; class TAO_Policy_Set; // Descriptions of parameters. class TAO_Profile; // Function pointer returning a pointer to CORBA::Exception. This is used to // describe the allocator for user-defined exceptions that are used internally // by the interpreter. typedef CORBA::Exception* (*TAO_Exception_Alloc) (void); struct TAO_Exception_Data { // = TITLE // TAO_Exception_Data // // = DESCRIPTION // Description of a single exception. // // The interpreter needs a way to allocate memory to hold the exception // that was raised by the stub. This data structure provides the typecode // for the exception as well as a static function pointer that // does the job of memory allocation. const char *id; // Repository id of the exception. TAO_Exception_Alloc alloc; // The allocator for this exception. }; /** * @class TAO_Stub * * @brief TAO_Stub * * Per-objref data includes the (protocol-specific) Profile, which * is handled by placing it into a subclass of this type along * with data that may be used in protocol-specific caching * schemes. * The type ID (the data specified by CORBA 2.0 that gets exposed * "on the wire", and in stringified objrefs) is held by this * module. * The stub APIs are member functions of this * type. */ class TAO_Export TAO_Stub { public: #if (TAO_HAS_CORBA_MESSAGING == 1) /** * Returns the effective policy if <type> is a known client-exposed * policy type. Returns the effective override for all other policy * types. */ virtual CORBA::Policy_ptr get_policy (CORBA::PolicyType type, CORBA::Environment &ACE_TRY_ENV = TAO_default_environment () ); virtual CORBA::Policy_ptr get_client_policy (CORBA::PolicyType type, CORBA::Environment &ACE_TRY_ENV = TAO_default_environment () ); virtual TAO_Stub* set_policy_overrides (const CORBA::PolicyList & policies, CORBA::SetOverrideType set_add, CORBA::Environment &ACE_TRY_ENV = TAO_default_environment ()); virtual CORBA::PolicyList * get_policy_overrides (const CORBA::PolicyTypeSeq & types, CORBA::Environment &ACE_TRY_ENV = TAO_default_environment ()); CORBA::Boolean validate_connection (CORBA::PolicyList_out inconsistent_policies, CORBA::Environment &ACE_TRY_ENV = TAO_default_environment ()); #endif /* TAO_HAS_CORBA_MESSAGING == 1 */ // = Methods for obtaining effective overrides. // // Same functionality as <get_client_policy>, but more efficient. // Each of the methods below returns effective override for the // corresponding policy. The effective override is obtained by // first checking for an override of the given policy type at the // Object scope, then at the Current scope, then at the ORB scope, // and, finally, ORB default values are checked. CORBA::Policy *relative_roundtrip_timeout (void); CORBA::Policy *sync_scope (void); #if (TAO_HAS_BUFFERING_CONSTRAINT_POLICY == 1) CORBA::Policy *buffering_constraint (void); #endif /* TAO_HAS_BUFFERING_CONSTRAINT_POLICY == 1 */ /// Return the sync strategy to be used in by the transport. /// Selection will be based on the SyncScope policies. TAO_Sync_Strategy &sync_strategy (void); /// All objref representations carry around a type ID. CORBA::String_var type_id; /** * All objref representations know how to hash themselves and * compare themselves for equivalence to others. It's easily * possible to have two objrefs that are distinct copies of data * that refers/points to the same remote object (i.e. are * equivalent). */ CORBA::ULong hash (CORBA::ULong maximum, CORBA_Environment &ACE_TRY_ENV = TAO_default_environment ()); /// Implement the is_equivalent() method for the CORBA::Object CORBA::Boolean is_equivalent (CORBA::Object_ptr other_obj); // Our Constructors ... /// Construct from a repository ID and a list of profiles. TAO_Stub (const char *repository_id, const TAO_MProfile &profiles, TAO_ORB_Core *orb_core); // = Memory management. CORBA::ULong _incr_refcnt (void); CORBA::ULong _decr_refcnt (void); // Manage the base (non-forwarded) profiles. /// returns a pointer to the profile_in_use object. This object /// retains ownership of this profile. TAO_Profile *profile_in_use (void) ; /** * Copy of the profile list, user must free memory when done. * although the user can call make_profiles() then reorder * the list and give it back to TAO_Stub. */ TAO_MProfile *make_profiles (void); /// Obtain a reference to the basic profile set. const TAO_MProfile& base_profiles (void) const; /// Obtain a reference to the basic profile set. TAO_MProfile& base_profiles (void); /// Obtain a pointer to the forwarded profile set const TAO_MProfile *forward_profiles (void) const; // Manage forward and base profiles. /** * THREAD SAFE. If forward_profiles is null then this will * get the next profile in the base_profiles list. If forward is not null * then this will get the next profile for the list of forwarding * profiles. If all profiles have been tried then 0 is returned and * profile_in_use_ is set to the first profile in the base_profiles * list. */ TAO_Profile *next_profile (void); /// NON-THREAD SAFE version of next_profile (void) TAO_Profile *next_profile_i (void); /** * THREAD SAFE * this method will reset the base profile list to reference the first * profile and if there are anmy existing forward profiles they are * reset. */ void reset_profiles (void); /// NON-THREAD SAFE version of reset_profiles (void); void reset_profiles_i (void); /// Returns 1 if a forward profile has successfully been used. /// profile_success_ && forward_profiles_ CORBA::Boolean valid_forward_profile (void); /// NON-THREAD-SAFE. Will set profile_success_ to 0. void set_valid_profile (void); /// Returns TRUE if a connection was successful with at least /// one profile. CORBA::Boolean valid_profile (void); /// Initialize the base_profiles_ and set profile_in_use_ to /// reference the first profile. TAO_Profile *base_profiles (const TAO_MProfile& mprofiles); /** * THREAD SAFE. * Set the forward_profiles. This object will assume ownership of * this TAO_MProfile object!! */ void add_forward_profiles (const TAO_MProfile &mprofiles); /** * THREAD SAFE * Used to get the next profile after the one being used has * failed during the initial connect or send of the message! */ CORBA::Boolean next_profile_retry (void); /// Accessor. TAO_ORB_Core* orb_core (void) const; /// This returns a duplicated ORB pointer. CORBA::ORB_ptr servant_orb_ptr (void); /// This returns the ORB var itself (generally for temporary use). CORBA::ORB_var &servant_orb_var (void); /** * Accesor and mutator for the servant ORB. Notice that the muatator * assumes the ownership of the passed in ORB and the accesor does not * return a copy of the orb since the accessing of the ORB is considered * temporary. */ void servant_orb (CORBA::ORB_ptr orb); /// Set the addressing mode. void addressing_mode (CORBA::Short addr_mode); /// Return the Addressing mode. CORBA::Short addressing_mode (void); /// Make a call on to services to see whether they have some /// preferences on selecting the right profiles. CORBA::Boolean service_profile_selection (void); /** * Create the IOP::IOR info. We will create the info at most once. * Get the index of the profile we are using to make the invocation. */ int create_ior_info (IOP::IOR *&ior_info, CORBA::ULong &index, CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException)); protected: /// Destructor is to be called only through _decr_refcnt(). virtual ~TAO_Stub (void); private: /// Makes a copy of the profile and frees the existing profile_in_use. /// NOT THREAD SAFE TAO_Profile *set_profile_in_use_i (TAO_Profile *pfile); /// NON-THREAD-SAFE. Utility method which resets or initializes /// the base_profile list and forward flags. void reset_base (); /// NON-THREAD-SAFE. Utility method which unrolls (removes or pops) /// the top most forwarding profile list. void forward_back_one (void); /// NOT THREAD-SAFE. Utility method which pops all forward profile /// lists and resets the forward_profiles_ pointer. void reset_forward (); /// NON-THREAD-SAFE. utility method for next_profile. TAO_Profile *next_forward_profile (void); /// THREAD-SAFE Create the IOR info int get_profile_ior_info (TAO_MProfile &profile, IOP::IOR *&ior_info, CORBA::Environment &ACE_TRY_ENV) ACE_THROW_SPEC ((CORBA::SystemException)); protected: /// Automatically manage the ORB_Core reference count /** * The ORB_Core cannot go away until the object references it * creates are destroyed. There are multiple reasons for this, but * in particular, the allocators used for some of the TAO_Profile * objects contained on each TAO_Stub are owned by the TAO_ORB_Core. * * This <B>must</B> be the first field of the class, otherwise the * TAO_ORB_Core is destroyed too early! * */ TAO_ORB_Core_Auto_Ptr orb_core_; /// ORB required for reference counting. This will help us keep the /// ORB around until the CORBA::Object we represent dies. /** * @todo Why do we need both a reference to the ORB_Core and its * ORB? It think the memory management rules for the ORB_Core * changed, in the good old days it was the CORBA::ORB class * who owned the ORB_Core, now it is the other way around.... */ CORBA::ORB_var orb_; /** * If this stub refers to a collocated object then we need to hold on to * the servant's ORB (which may be different from the client ORB) so that, * 1. we know that the ORB will stay alive long enough, and, * 2. we can search for the servant/POA's status starting from * the ORB's RootPOA. */ CORBA::ORB_var servant_orb_; /// Ordered list of profiles for this object. TAO_MProfile base_profiles_; /// The list of forwarding profiles. This is actually implemented as a /// linked list of TAO_MProfile objects. TAO_MProfile *forward_profiles_; /// This is the profile that we are currently sending/receiving with. TAO_Profile *profile_in_use_; /// Mutex to protect access to the forwarding profile. ACE_Lock* profile_lock_ptr_; /// Have we successfully talked to the forward profile yet? size_t profile_success_; /// Mutex to protect reference count. TAO_SYNCH_MUTEX refcount_lock_; /// Number of outstanding references to this object. CORBA::ULong refcount_; /// The policy overrides in this object, if nil then use the default /// policies. TAO_Policy_Set *policies_; /// The addressing mode. CORBA::Short addressing_mode_; /** * The ior info. This is needed for GIOP 1.2, as the clients could * receive an exception from the server asking for this info. The * exception that the client receives is LOC_NEEDS_ADDRESSING_MODE. * The data is set up here to be passed on to Invocation classes * when they receive an exception. This info is for the base * profiles that this class stores */ IOP::IOR *ior_info_; /// Forwarded IOR info IOP::IOR *forwarded_ior_info_; // = Disallow copy constructor and assignment operator. ACE_UNIMPLEMENTED_FUNC (TAO_Stub (const TAO_Stub &)) ACE_UNIMPLEMENTED_FUNC (TAO_Stub &operator = (const TAO_Stub &)) #if defined (__GNUG__) // G++ (even 2.6.3) stupidly thinks instances can't be created. // This de-warns. friend class everyone_needs_a_friend; #endif /* __GNUG__ */ }; // Define a TAO_Stub auto_ptr class. /** * @class TAO_Stub_Auto_Ptr * * @brief Implements the draft C++ standard auto_ptr abstraction. * This class allows one to work Stub Objects *Only*! */ class TAO_Export TAO_Stub_Auto_Ptr { public: // = Initialization and termination methods. /* explicit */ TAO_Stub_Auto_Ptr (TAO_Stub *p = 0); TAO_Stub_Auto_Ptr (TAO_Stub_Auto_Ptr &ap); TAO_Stub_Auto_Ptr &operator= (TAO_Stub_Auto_Ptr &rhs); ~TAO_Stub_Auto_Ptr (void); // = Accessor methods. TAO_Stub &operator *() const; TAO_Stub *get (void) const; TAO_Stub *release (void); void reset (TAO_Stub *p = 0); TAO_Stub *operator-> () const; protected: TAO_Stub *p_; }; #if defined (__ACE_INLINE__) # include "tao/Stub.i" #endif /* __ACE_INLINE__ */ #include "ace/post.h" #endif /* TAO_STUB_H */
33.634529
88
0.658023
0a134c8bc3eb8751923696a4860a0694bd325ff2
910
h
C
cpptest/include/operator_lookup.h
mattxlee/clvm_rs
57ac7502d0b63e3be674b3e619894af9c8039f8f
[ "Apache-2.0" ]
null
null
null
cpptest/include/operator_lookup.h
mattxlee/clvm_rs
57ac7502d0b63e3be674b3e619894af9c8039f8f
[ "Apache-2.0" ]
null
null
null
cpptest/include/operator_lookup.h
mattxlee/clvm_rs
57ac7502d0b63e3be674b3e619894af9c8039f8f
[ "Apache-2.0" ]
null
null
null
#ifndef CHIA_OPERATOR_LOOKUP_H #define CHIA_OPERATOR_LOOKUP_H #include <functional> #include <map> #include <string> #include <string_view> #include <tuple> #include "program.h" namespace chia { using OpFunc = std::function<std::tuple<int, CLVMObjectPtr>(CLVMObjectPtr args)>; class Ops { public: static Ops& GetInstance(); void Assign(std::string_view op_name, OpFunc f); OpFunc Query(std::string_view op_name); private: Ops(); private: std::map<std::string, OpFunc> ops_; }; class OperatorLookup { public: Bytes QUOTE_ATOM; Bytes APPLY_ATOM; OperatorLookup(); std::tuple<int, CLVMObjectPtr> operator()(Bytes const& op, CLVMObjectPtr args) const; private: void InitKeywords(); private: std::map<uint8_t, std::string> atom_to_keyword_; std::map<std::string, uint8_t> keyword_to_atom_; }; } // namespace chia #endif
17.169811
70
0.683516
f748c4712510e24e9dc045652a26344c037d2d74
2,115
c
C
uefi-sct/SctPkg/TestCase/UEFI/IHV/Protocol/DriverBinding/BlackBoxTest/Guid.c
sunnywang-arm/edk2-test
475be9f7a70d012705eca64dd24a9eeaed643183
[ "BSD-2-Clause" ]
47
2018-10-15T02:34:39.000Z
2022-02-07T11:02:45.000Z
uefi-sct/SctPkg/TestCase/UEFI/IHV/Protocol/DriverBinding/BlackBoxTest/Guid.c
sunnywang-arm/edk2-test
475be9f7a70d012705eca64dd24a9eeaed643183
[ "BSD-2-Clause" ]
null
null
null
uefi-sct/SctPkg/TestCase/UEFI/IHV/Protocol/DriverBinding/BlackBoxTest/Guid.c
sunnywang-arm/edk2-test
475be9f7a70d012705eca64dd24a9eeaed643183
[ "BSD-2-Clause" ]
78
2018-10-08T01:17:19.000Z
2022-03-16T14:33:15.000Z
/** @file Copyright 2006 - 2015 Unified EFI, Inc.<BR> Copyright (c) 2010 - 2015, 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. **/ /*++ Module Name: Guid.c Abstract: GUIDs auto-generated for EFI test assertion. --*/ #include "Efi.h" #include "Guid.h" EFI_GUID gDriverBindingBBTestFunctionAssertionGuid001 = EFI_TEST_DRIVERBINDINGBBTESTFUNCTION_ASSERTION_001_GUID; EFI_GUID gDriverBindingBBTestFunctionAssertionGuid002 = EFI_TEST_DRIVERBINDINGBBTESTFUNCTION_ASSERTION_002_GUID; EFI_GUID gDriverBindingBBTestFunctionAssertionGuid003 = EFI_TEST_DRIVERBINDINGBBTESTFUNCTION_ASSERTION_003_GUID; EFI_GUID gDriverBindingBBTestFunctionAssertionGuid004 = EFI_TEST_DRIVERBINDINGBBTESTFUNCTION_ASSERTION_004_GUID; EFI_GUID gDriverBindingBBTestFunctionAssertionGuid005 = EFI_TEST_DRIVERBINDINGBBTESTFUNCTION_ASSERTION_005_GUID; EFI_GUID gDriverBindingBBTestFunctionAssertionGuid006 = EFI_TEST_DRIVERBINDINGBBTESTFUNCTION_ASSERTION_006_GUID; EFI_GUID gDriverBindingBBTestFunctionAssertionGuid007 = EFI_TEST_DRIVERBINDINGBBTESTFUNCTION_ASSERTION_007_GUID; EFI_GUID gDriverBindingBBTestFunctionAssertionGuid008 = EFI_TEST_DRIVERBINDINGBBTESTFUNCTION_ASSERTION_008_GUID; EFI_GUID gDriverBindingBBTestFunctionAssertionGuid009 = EFI_TEST_DRIVERBINDINGBBTESTFUNCTION_ASSERTION_009_GUID; EFI_GUID gDriverBindingBBTestFunctionAssertionGuid010 = EFI_TEST_DRIVERBINDINGBBTESTFUNCTION_ASSERTION_010_GUID; EFI_GUID gDriverBindingBBTestFunctionAssertionGuid011 = EFI_TEST_DRIVERBINDINGBBTESTFUNCTION_ASSERTION_011_GUID; EFI_GUID gDriverBindingBBTestFunctionAssertionGuid012 = EFI_TEST_DRIVERBINDINGBBTESTFUNCTION_ASSERTION_012_GUID;
39.166667
113
0.844444
f78dc74211f5ccc60146c0651a162feea186d6b4
3,253
c
C
tests/poolalloc.c
Gustavo6046/annkh
86e1cce56137fd8b64dc891745a1bf6e21fbc401
[ "MIT" ]
null
null
null
tests/poolalloc.c
Gustavo6046/annkh
86e1cce56137fd8b64dc891745a1bf6e21fbc401
[ "MIT" ]
null
null
null
tests/poolalloc.c
Gustavo6046/annkh
86e1cce56137fd8b64dc891745a1bf6e21fbc401
[ "MIT" ]
null
null
null
#include "munit/munit.h" #include "poollist.h" struct p_root all_numbers = POOL_ROOT(int, 4); void list_length_and_middle_free(void) { int idx; struct pl_pool_list mylist = pl_make(&all_numbers, 2); int someints[] = { 2, 3, 4 }; // add three numbers idx = pl_insert(&mylist, &someints[0]); munit_assert_int(idx, ==, 0); idx = pl_insert(&mylist, &someints[1]); munit_assert_int(idx, ==, 1); idx = pl_insert(&mylist, &someints[2]); munit_assert_int(idx, ==, 2); munit_assert_int(mylist.length, ==, 3); munit_assert_int(mylist.head, ==, 3); munit_assert_int(mylist.middle_freed, ==, 0); munit_assert_true(pl_has(&mylist, 0)); munit_assert_true(pl_has(&mylist, 1)); munit_assert_true(pl_has(&mylist, 2)); // pop two and ensure they are 4 and 3 int num; munit_assert_true(pl_pop(&mylist, &num)); munit_assert_false(pl_has(&mylist, 2)); munit_assert_true(pl_has(&mylist, 1)); munit_assert_int(num, ==, 4); munit_assert_true(pl_pop(&mylist, &num)); munit_assert_false(pl_has(&mylist, 1)); munit_assert_int(num, ==, 3); munit_assert_int(mylist.length, ==, 1); munit_assert_int(mylist.head, ==, 1); munit_assert_int(mylist.middle_freed, ==, 0); munit_assert_false(pl_has(&mylist, 1)); munit_assert_false(pl_has(&mylist, 2)); // make it 3 long again pl_insert(&mylist, &someints[1]); munit_assert_false(pl_has(&mylist, 2)); munit_assert_true(pl_has(&mylist, 1)); pl_insert(&mylist, &someints[2]); munit_assert_true(pl_has(&mylist, 1)); munit_assert_true(pl_has(&mylist, 2)); munit_assert_int(mylist.length, ==, 3); munit_assert_int(mylist.head, ==, 3); munit_assert_int(mylist.middle_freed, ==, 0); // remove the middle and make sure it sets middle_freed // and head properly munit_assert_true(pl_remove(&mylist, 1, &num)); munit_assert_int(num, ==, 3); munit_assert_int(mylist.length, ==, 2); munit_assert_int(mylist.head, ==, 3); munit_assert_int(mylist.middle_freed, ==, 1); // pop the head and ensure head is decremented // all the way back to 1 and middle_freed is // reset munit_assert_true(pl_pop(&mylist, &num)); munit_assert_int(num, ==, 4); munit_assert_int(mylist.length, ==, 1); munit_assert_int(mylist.head, ==, 1); munit_assert_int(mylist.middle_freed, ==, 0); // make it 3 long again... pl_insert(&mylist, &someints[1]); pl_insert(&mylist, &someints[2]); munit_assert_int(mylist.length, ==, 3); munit_assert_int(mylist.head, ==, 3); munit_assert_int(mylist.middle_freed, ==, 0); // ...remove the middle again... munit_assert_true(pl_remove(&mylist, 1, &num)); munit_assert_int(num, ==, 3); munit_assert_int(mylist.length, ==, 2); munit_assert_int(mylist.head, ==, 3); munit_assert_int(mylist.middle_freed, ==, 1); // ...and ensure the next insert fills it back in! pl_insert(&mylist, &someints[1]); munit_assert_int(mylist.length, ==, 3); munit_assert_int(mylist.head, ==, 3); munit_assert_int(mylist.middle_freed, ==, 0); munit_assert_true(pl_has(&mylist, 1)); } int main(void) { list_length_and_middle_free(); }
27.108333
59
0.653551
59cd0437d7bea3b20a965ea3c557c1cd4af35b2f
315
h
C
CubeEngine/EngineSrc/BackEnd/gl/DeviceShaderGL.h
tangziwen/Cube-Engine
c79b878dcc7e2e382f4463ca63519627d6220afd
[ "MIT" ]
360
2015-01-26T08:15:01.000Z
2021-07-11T16:30:58.000Z
CubeEngine/EngineSrc/BackEnd/gl/DeviceShaderGL.h
tangziwen/Cube-Engine
c79b878dcc7e2e382f4463ca63519627d6220afd
[ "MIT" ]
6
2015-03-09T09:15:07.000Z
2020-07-06T01:34:00.000Z
CubeEngine/EngineSrc/BackEnd/gl/DeviceShaderGL.h
tangziwen/CubeMiniGame
90bffa66d4beba5fddc39fc642a8fb36703cf32d
[ "MIT" ]
41
2015-03-10T03:17:46.000Z
2021-07-13T06:26:26.000Z
#pragma once #include "../DeviceShaderCollection.h" namespace tzw { class DeviceShaderGL : public DeviceShaderCollection { public: void addShader(const unsigned char * buff, size_t size, DeviceShaderType type, const unsigned char * fileInfoStr) override; bool create() override; bool finish() override; }; };
19.6875
124
0.765079
59d545998a3db614cf20e3725a061b079fa4dad5
1,139
h
C
build/stx/support/tools/splint-3.1.2/src/Headers/programNodeList.h
GunterMueller/ST_STX_Fork
d891b139f3c016b81feeb5bf749e60585575bff7
[ "MIT" ]
1
2020-01-23T20:46:08.000Z
2020-01-23T20:46:08.000Z
build/stx/support/tools/splint-3.1.2/src/Headers/programNodeList.h
GunterMueller/ST_STX_Fork
d891b139f3c016b81feeb5bf749e60585575bff7
[ "MIT" ]
null
null
null
build/stx/support/tools/splint-3.1.2/src/Headers/programNodeList.h
GunterMueller/ST_STX_Fork
d891b139f3c016b81feeb5bf749e60585575bff7
[ "MIT" ]
null
null
null
/* ** Copyright (C) University of Virginia, Massachusetts Institue of Technology 1994-2003. ** See ../LICENSE for license information. ** */ # ifndef PROGRAMNODELIST_H # define PROGRAMNODELIST_H typedef /*@only@*/ programNode o_programNode; struct s_programNodeList { int nelements; int nspace; /*@reldef@*/ /*@relnull@*/ o_programNode *elements; } ; /*@iter programNodeList_elements (sef programNodeList x, yield exposed programNode el); @*/ # define programNodeList_elements(x, m_el) \ { int m_ind; programNode *m_elements = &((x)->elements[0]); \ for (m_ind = 0 ; m_ind < (x)->nelements; m_ind++) \ { programNode m_el = *(m_elements++); # define end_programNodeList_elements }} extern /*@only@*/ programNodeList programNodeList_new(void); extern void programNodeList_addh (programNodeList p_s, /*@keep@*/ programNode p_el) ; extern /*@only@*/ cstring programNodeList_unparse (programNodeList p_s) ; extern void programNodeList_free (/*@only@*/ programNodeList p_s) ; /*@constant int programNodeListBASESIZE;@*/ # define programNodeListBASESIZE SMALLBASESIZE # else # error "Multiple include" # endif
26.488372
91
0.72432
74a83ef10a79908fd5bea00f101200b6026604f6
1,198
h
C
LiteCppDB/LiteCppDB/JsonSerializer.h
pnadan/LiteCppDB
cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2
[ "MIT" ]
2
2019-07-18T06:30:33.000Z
2020-01-23T17:40:36.000Z
LiteCppDB/LiteCppDB/JsonSerializer.h
pnadan/LiteCppDB
cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2
[ "MIT" ]
null
null
null
LiteCppDB/LiteCppDB/JsonSerializer.h
pnadan/LiteCppDB
cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2
[ "MIT" ]
null
null
null
#pragma once #include "BsonValue.h" #include "StringScanner.h" #include <string> #include <sstream> #ifdef LITECPPDB_EXPORTS #define LITECPPDB_API __declspec(dllexport) #else #define LITECPPDB_API __declspec(dllimport) #endif namespace LiteCppDB { // Static class for serialize/deserialize BsonDocuments into json extended format class JsonSerializer { public: #pragma region Serialize // Json serialize a BsonValue into a String LITECPPDB_API static std::string Serialize(BsonValue value, bool pretty = false, bool writeBinary = true); // Json serialize a BsonValue into a TextWriter LITECPPDB_API static void Serialize(BsonValue value, std::ostringstream& writer, bool pretty = false, bool writeBinary = true); #pragma endregion Serialize #pragma region Deserialize /// Deserialize a Json string into a BsonValue LITECPPDB_API static BsonValue Deserialize(std::string json); // Deserialize a Json TextReader into a BsonValue LITECPPDB_API static BsonValue Deserialize(std::istringstream& reader); // Deserialize a json using a StringScanner and returns BsonValue LITECPPDB_API static BsonValue Deserialize(StringScanner& s); #pragma endregion Deserialize }; }
27.227273
129
0.787145
dd6d52ec6caf58c261695c33d5ecde0bc1710abc
1,029
h
C
Applications/AppStore/ContextActionsPresentationController.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
Applications/AppStore/ContextActionsPresentationController.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
Applications/AppStore/ContextActionsPresentationController.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 Steve Nygard. // #import <UIKit/UIPresentationController.h> @class UIVisualEffectView; @interface ContextActionsPresentationController : UIPresentationController { UIVisualEffectView *_backgroundView; // 8 = 0x8 CDUnknownBlockType _dismissalAnimations; // 16 = 0x10 } - (void).cxx_destruct; // IMP=0x0000000100013004 @property(copy, nonatomic) CDUnknownBlockType dismissalAnimations; // @synthesize dismissalAnimations=_dismissalAnimations; @property(retain, nonatomic) UIVisualEffectView *backgroundView; // @synthesize backgroundView=_backgroundView; - (void)dismissalTransitionWillBegin; // IMP=0x0000000100012cbc - (void)presentationTransitionWillBegin; // IMP=0x00000001000127f4 - (_Bool)shouldRemovePresentersView; // IMP=0x00000001000127ec - (id)initWithPresentedViewController:(id)arg1 presentingViewController:(id)arg2; // IMP=0x00000001000126ec @end
38.111111
123
0.793975
f7cc06972a39e318ef96c6f4ded38e7cfc5c22b9
934
h
C
include/timers.h
CodeOhms/egb220_line_robot
33c60296d58d8edcdf55579fa50ee50c9058f60c
[ "MIT" ]
null
null
null
include/timers.h
CodeOhms/egb220_line_robot
33c60296d58d8edcdf55579fa50ee50c9058f60c
[ "MIT" ]
null
null
null
include/timers.h
CodeOhms/egb220_line_robot
33c60296d58d8edcdf55579fa50ee50c9058f60c
[ "MIT" ]
null
null
null
#ifndef TIMERS_H #define TIMERS_H #include <avr/io.h> enum timer_prescalers { no_clock_source, no_prescaler, timer_prescaler8, timer_prescaler64, timer_prescaler256, timer_prescaler1024, extern_clock_falling, extern_clock_rising }; enum waveform_generation_mode { normal, pwm_phase_correct_0xFF, CTC, fast_pwm_0xFF, pwm_phase_correct_OCRx, fast_pwm_OCRx }; enum compare_output_mode { com_normal, com_toggle, com_clear, com_set }; enum compare_output { comp_A, comp_B, comp_C }; void timer0_set_prescaler(enum timer_prescalers prescaler); enum timer_prescalers timer0_get_prescaler(); uint16_t timer_prescaler_enum_to_int(enum timer_prescalers prescaler); void timer0_waveform_generation_mode(enum waveform_generation_mode wgm); void timer0_compare_output_mode(enum compare_output_mode cop, enum compare_output comp_out); #endif //TIMERS_H
17.622642
92
0.767666
101182ab8c182ae6585ef99292aa106b54df2b6d
832
c
C
rouziclib/text/history.c
forksnd/rouziclib
347a5482cd34092c408502a3bdc4eda2c82672a7
[ "Apache-2.0" ]
36
2015-11-26T00:08:02.000Z
2022-01-18T20:54:05.000Z
rouziclib/text/history.c
forksnd/rouziclib
347a5482cd34092c408502a3bdc4eda2c82672a7
[ "Apache-2.0" ]
2
2018-04-01T04:11:52.000Z
2020-04-25T16:13:51.000Z
rouziclib/text/history.c
forksnd/rouziclib
347a5482cd34092c408502a3bdc4eda2c82672a7
[ "Apache-2.0" ]
7
2017-05-24T02:04:55.000Z
2022-01-31T05:26:42.000Z
void text_history_add(text_history_t *th, const char *string) { uint64_t hash; int create_entry = 1; if (th==NULL) return ; hash = get_string_hash(string); if (th->entry==NULL) alloc_enough(&th->entry, 8, &th->entry_as, sizeof(text_history_entry_t), 1.); if (th->entry_count > 0) if (th->entry[th->entry_count-1].hash == hash) create_entry = 0; if (create_entry) { alloc_enough(&th->entry, th->entry_count+=1, &th->entry_as, sizeof(text_history_entry_t), 2.); th->entry[th->entry_count-1].hash = hash; th->entry[th->entry_count-1].string = make_string_copy(string); } } char *text_history_get_entry(text_history_t *th, int index) { if (th==NULL) return NULL; if (th->entry==NULL || th->entry_count <= 0) return NULL; index = MINN(th->entry_count-1, index); return th->entry[index].string; }
21.894737
96
0.68149
103466f294b24bfca04265b3a22e78f00d64097e
907
c
C
OpenCorePkg/Library/OcGuardLib/Canary.c
CEOALT1/RefindPlusUDK
116b957ad735f96fbb6d80a0ba582046960ba164
[ "BSD-2-Clause" ]
133
2019-12-19T12:46:09.000Z
2022-02-26T13:36:48.000Z
OpenCorePkg/Library/OcGuardLib/Canary.c
CEOALT1/RefindPlusUDK
116b957ad735f96fbb6d80a0ba582046960ba164
[ "BSD-2-Clause" ]
35
2019-12-26T11:17:33.000Z
2021-12-25T18:52:12.000Z
OpenCorePkg/Library/OcGuardLib/Canary.c
CEOALT1/RefindPlusUDK
116b957ad735f96fbb6d80a0ba582046960ba164
[ "BSD-2-Clause" ]
35
2019-12-18T13:42:41.000Z
2022-02-08T10:38:00.000Z
/** @file OcGuardLib Copyright (c) 2018, vit9696 All rights reserved. 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. **/ // // TODO: For the cookie to work for security needs, the value is to be runtime // generated, e.g. with rdrand. For now this code is only written to help debugging // stack corruptions. // UINT64 __security_cookie = 0x9C7D6B4580C0BC9ULL; VOID __security_check_cookie ( IN UINTN Value ) { volatile UINTN Index; if (Value != (UINTN) __security_cookie) { Index = 0; while (Index == 0) { } } }
22.675
83
0.734289
dc2fefe0cc6ac817d52c8f94bba2ac34437b11b4
4,067
c
C
transports/ip.c
sshoecraft/solardirector
9b971097f7ad9afa88e0785f51801fda22b8abf6
[ "BSD-3-Clause" ]
5
2021-05-10T21:07:17.000Z
2021-09-29T20:31:00.000Z
transports/ip.c
sshoecraft/solardirector
9b971097f7ad9afa88e0785f51801fda22b8abf6
[ "BSD-3-Clause" ]
2
2021-03-01T04:04:19.000Z
2022-02-21T16:13:04.000Z
transports/ip.c
sshoecraft/solardirector
9b971097f7ad9afa88e0785f51801fda22b8abf6
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2021, Stephen P. Shoecraft All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ #include <sys/types.h> #ifdef __WIN32 #include <winsock2.h> #include <windows.h> #include <ws2tcpip.h> #else #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #endif #include <fcntl.h> #include <ctype.h> #include "transports.h" #define DEFAULT_PORT 23 #ifdef __WIN32 typedef SOCKET socket_t; #define SOCKET_CLOSE(s) closesocket(s); #else typedef int socket_t; #define SOCKET_CLOSE(s) close(s) #define INVALID_SOCKET -1 #endif struct ip_session { socket_t sock; char target[SOLARD_TARGET_LEN]; int port; }; typedef struct ip_session ip_session_t; static void *ip_new(void *conf, void *target, void *topts) { ip_session_t *s; char *p; s = calloc(1,sizeof(*s)); if (!s) { perror("ip_new: malloc"); return 0; } s->sock = INVALID_SOCKET; p = strchr((char *)target,':'); if (p) *p = 0; strncat(s->target,(char *)target,SOLARD_TARGET_LEN-1); if (p) { p++; s->port = atoi(p); } if (!s->port) s->port = DEFAULT_PORT; dprintf(5,"target: %s, port: %d\n", s->target, s->port); return s; } static int ip_open(void *handle) { ip_session_t *s = handle; struct sockaddr_in addr; socklen_t sin_size; struct hostent *he; char temp[SOLARD_TARGET_LEN]; uint8_t *ptr; if (s->sock != INVALID_SOCKET) return 0; s->sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s->sock == INVALID_SOCKET) { log_write(LOG_SYSERR,"socket"); return 1; } /* Try to resolve the target */ he = (struct hostent *) 0; if (!is_ip(s->target)) { he = gethostbyname(s->target); dprintf(6,"he: %p\n", he); if (he) { ptr = (unsigned char *) he->h_addr; sprintf(temp,"%d.%d.%d.%d",ptr[0],ptr[1],ptr[2],ptr[3]); } } if (!he) strcpy(temp,s->target); dprintf(3,"temp: %s\n",temp); memset(&addr,0,sizeof(addr)); sin_size = sizeof(addr); addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(temp); addr.sin_port = htons(s->port); dprintf(3,"connecting...\n"); if (connect(s->sock,(struct sockaddr *)&addr,sin_size) < 0) { lprintf(LOG_SYSERR,"connect to %s", s->target); return 1; } return 0; } static int ip_read(void *handle, void *buf, int buflen) { ip_session_t *s = handle; int bytes, bidx, num; struct timeval tv; fd_set rdset; dprintf(5,"buf: %p, buflen: %d\n", buf, buflen); tv.tv_usec = 0; tv.tv_sec = 1; FD_ZERO(&rdset); if (s->sock == INVALID_SOCKET) return -1; dprintf(5,"reading...\n"); bidx=0; while(1) { FD_SET(s->sock,&rdset); num = select(s->sock+1,&rdset,0,0,&tv); dprintf(5,"num: %d\n", num); if (!num) break; dprintf(5,"buf: %p, bufen: %d\n", buf, buflen); bytes = recv(s->sock, buf, buflen, 0); dprintf(5,"bytes: %d\n", bytes); if (bytes < 0) { if (errno == EAGAIN) continue; bidx = -1; break; } else if (bytes == 0) { break; } else if (bytes > 0) { buf += bytes; bidx += bytes; buflen -= bytes; if (buflen < 1) break; } } #ifdef DEBUG if (debug >= 5) bindump("ip_read",buf,bidx); #endif dprintf(5,"returning: %d\n", bidx); return bidx; } static int ip_write(void *handle, void *buf, int buflen) { ip_session_t *s = handle; int bytes; dprintf(1,"s->sock: %p\n", s->sock); if (s->sock == INVALID_SOCKET) return -1; #ifdef DEBUG if (debug >= 5) bindump("ip_write",buf,buflen); #endif bytes = send(s->sock, buf, buflen, 0); dprintf(1,"bytes: %d\n", bytes); return bytes; } static int ip_close(void *handle) { ip_session_t *s = handle; if (s->sock != INVALID_SOCKET) { dprintf(5,"closing...\n"); SOCKET_CLOSE(s->sock); s->sock = INVALID_SOCKET; } return 0; } static int ip_config(void *h, int func, ...) { va_list ap; int r; r = 1; va_start(ap,func); switch(func) { default: dprintf(1,"error: unhandled func: %d\n", func); break; } return r; } solard_driver_t ip_driver = { SOLARD_DRIVER_TRANSPORT, "ip", ip_new, ip_open, ip_close, ip_read, ip_write, ip_config };
20.133663
69
0.644455
dc87aea6a54cb0243ec4b6a66581ec768f226fbb
3,391
c
C
mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/int8/layer_norm_int8.c
PowerOlive/mindspore
bda20724a94113cedd12c3ed9083141012da1f15
[ "Apache-2.0" ]
3,200
2020-02-17T12:45:41.000Z
2022-03-31T20:21:16.000Z
mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/int8/layer_norm_int8.c
zimo-geek/mindspore
665ec683d4af85c71b2a1f0d6829356f2bc0e1ff
[ "Apache-2.0" ]
176
2020-02-12T02:52:11.000Z
2022-03-28T22:15:55.000Z
mindspore/ccsrc/backend/kernel_compiler/cpu/nnacl/int8/layer_norm_int8.c
zimo-geek/mindspore
665ec683d4af85c71b2a1f0d6829356f2bc0e1ff
[ "Apache-2.0" ]
621
2020-03-09T01:31:41.000Z
2022-03-30T03:43:19.000Z
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "nnacl/int8/layer_norm_int8.h" void LayerNormGammaAndBetaInt8(int8_t *dst, const int8_t *src, const float *gamma_data, const float *beta_data, const LayerNormQuantArg *quant, int num, const float mean, const float deno) { for (int i = 0; i < num; i++) { float fp32_src = (src[i] - quant->in_zp_) * quant->in_scale_; float fp32_dst = (fp32_src - mean) * deno; fp32_dst = fp32_dst * gamma_data[i] + beta_data[i]; int32_t int32_dst = (int32_t)round(fp32_dst * 1.0 / quant->out_scale_ + quant->out_zp_); dst[i] = (int8_t)MSMAX(MSMIN(int32_dst, 127), -128); } } /* * origin : (x-mean) / sqrt(variance + epsilon) * gamma + beta * quant : (x-mean) / sqrt(sum(x * x) - mean * mean) * gamma + beta * * */ int LayerNormInt8(const int8_t *src_data, const float *gamma_data, const float *beta_data, int8_t *dst_data, const LayerNormParameter *param, const LayerNormQuantArg *quant, int task_id) { if (src_data == NULL || dst_data == NULL || gamma_data == NULL || beta_data == NULL) { return NNACL_NULL_PTR; } NNACL_CHECK_ZERO_RETURN_ERR(param->params_inner_size_); NNACL_CHECK_ZERO_RETURN_ERR(param->params_outer_size_); int step = UP_DIV(param->norm_outer_size_, param->op_parameter_.thread_num_); int thread_end = MSMIN((task_id + 1) * step, param->norm_outer_size_); for (int i = task_id * step; i < thread_end; i++) { const int8_t *src_norm = src_data + i * param->norm_inner_size_; int8_t *dst_norm = dst_data + i * param->norm_inner_size_; float mean = 0.0f; float square_mean = 0.0f; for (int j = 0; j < param->norm_inner_size_; j++) { float float_src = (src_norm[j] - quant->in_zp_) * quant->in_scale_; mean += float_src; square_mean += float_src * float_src; } mean /= (float)param->norm_inner_size_; square_mean /= (float)param->norm_inner_size_; const float deno = 1 / sqrtf(square_mean - mean * mean + param->epsilon_); if (param->norm_outer_size_ <= param->params_outer_size_) { for (int x = 0; x < param->norm_inner_size_ / param->params_inner_size_; x++) { const int8_t *src_param = src_norm + x * param->params_inner_size_; int8_t *dst_param = dst_norm + x * param->params_inner_size_; LayerNormGammaAndBetaInt8(dst_param, src_param, gamma_data, beta_data, quant, param->norm_inner_size_, mean, deno); } } else { int x = i / param->params_outer_size_; const float *gamma = gamma_data + x * param->norm_inner_size_; const float *beta = beta_data + x * param->norm_inner_size_; LayerNormGammaAndBetaInt8(dst_norm, src_norm, gamma, beta, quant, param->norm_inner_size_, mean, deno); } } return NNACL_OK; }
45.213333
116
0.673253
673a0e7693f830196640ddad7720f824b4139741
1,145
c
C
plugins/copy_totals/lib/lclipboard.c
drmargarido/dr-tracker
9bd7568719c72741156b8898b92050e29c3ecc4b
[ "MIT" ]
17
2019-11-17T01:04:48.000Z
2021-11-06T09:40:52.000Z
plugins/copy_totals/lib/lclipboard.c
drmargarido/dr-tracker
9bd7568719c72741156b8898b92050e29c3ecc4b
[ "MIT" ]
3
2020-02-07T12:43:42.000Z
2020-08-06T18:24:32.000Z
plugins/copy_totals/lib/lclipboard.c
drmargarido/d-tracker
99e6ed113f655cc8e90aefacad7b82b0cc55a6de
[ "MIT" ]
null
null
null
#include <stdlib.h> #include "lua.h" #include "lauxlib.h" #include "lualib.h" #include "libclipboard.h" static clipboard_c *cb; char * text = NULL; // Lua bindings to Interact with the clipboard static int f_init(lua_State *L){ cb = clipboard_new(NULL); int result = 1; if (cb == NULL) { printf("Clipboard initialization failed!\n"); result = 0; } lua_pushnumber(L, result); return 1; } static int f_close(lua_State *L){ if(text){ free(text); } clipboard_free(cb); return 0; } static int f_get_text(lua_State *L) { if(text){ free(text); } text = clipboard_text(cb); lua_pushstring(L, text); return 1; } static int f_set_text(lua_State *L) { int result = 0; if(cb != NULL){ const char * text = luaL_checkstring(L, 1); result = clipboard_set_text(cb, text); } lua_pushnumber(L, result); return 1; } static const luaL_Reg lib[] = { { "init", f_init }, { "close", f_close }, { "get_text", f_get_text }, { "set_text", f_set_text }, { NULL, NULL } }; LUALIB_API int luaopen_lclipboard(lua_State *L) { luaL_openlib(L, "clipboard", lib, 0); return 1; }
18.174603
49
0.633188
7cdc989c4741d6d78b8028cc30ed99c1fdf810ac
281
h
C
EP Mobile/EP Mobile/EPSDrugCalculatorNotes.h
mannd/epmobile-ios
7974764c7c5233668f02876598af985e0f79692d
[ "Apache-2.0" ]
2
2015-02-13T17:16:50.000Z
2015-08-19T01:51:56.000Z
EP Mobile/EP Mobile/EPSDrugCalculatorNotes.h
mannd/epmobile-ios
7974764c7c5233668f02876598af985e0f79692d
[ "Apache-2.0" ]
6
2015-10-26T06:16:56.000Z
2020-12-08T17:21:50.000Z
EP Mobile/EP Mobile/EPSDrugCalculatorNotes.h
mannd/epmobile-ios
7974764c7c5233668f02876598af985e0f79692d
[ "Apache-2.0" ]
1
2022-03-13T21:59:39.000Z
2022-03-13T21:59:39.000Z
// // EPSDrugCalculatorNotes.h // EP Mobile // // Created by David Mann on 2/24/15. // Copyright (c) 2015 EP Studios. All rights reserved. // #import <Foundation/Foundation.h> #import "EPSNotesProtocol.h" @interface EPSDrugCalculatorNotes : NSObject <EPSNotesProtocol> @end
18.733333
63
0.725979
73307d566a57d6a1b1fbcea83e2583eb56fa2510
4,179
h
C
code_reading/oceanbase-master/src/sql/dtl/ob_dtl_channel_mem_manager.h
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/sql/dtl/ob_dtl_channel_mem_manager.h
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
null
null
null
code_reading/oceanbase-master/src/sql/dtl/ob_dtl_channel_mem_manager.h
wangcy6/weekly_read
3a8837ee9cd957787ee1785e4066dd623e02e13a
[ "Apache-2.0" ]
1
2020-10-18T12:59:31.000Z
2020-10-18T12:59:31.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #ifndef OB_DTL_CHANNEL_MEM_MANEGER_H #define OB_DTL_CHANNEL_MEM_MANEGER_H #include "lib/queue/ob_lighty_queue.h" #include "lib/utility/ob_print_utils.h" #include "lib/allocator/ob_fifo_allocator.h" #include "sql/dtl/ob_dtl_linked_buffer.h" #include "lib/atomic/ob_atomic.h" #include "lib/allocator/ob_mod_define.h" #include "lib/alloc/alloc_func.h" #include "share/config/ob_server_config.h" namespace oceanbase { namespace sql { namespace dtl { // class ObDtlLinkedBuffer; class ObDtlChannelMemManager { public: ObDtlChannelMemManager(uint64_t tenant_id); virtual ~ObDtlChannelMemManager() { destroy(); } int init(); void destroy(); public: ObDtlLinkedBuffer* alloc(int64_t chid, int64_t size); int free(ObDtlLinkedBuffer* buf, bool auto_free = true); void set_seqno(int64_t seqno) { seqno_ = seqno; } int64_t get_seqno() { return seqno_; } TO_STRING_KV(K_(size_per_buffer)); OB_INLINE int64_t get_alloc_cnt() { return alloc_cnt_; } OB_INLINE int64_t get_free_cnt() { return free_cnt_; } OB_INLINE int64_t get_free_queue_length() { return queue_len_; } OB_INLINE int64_t get_real_alloc_cnt() { return real_alloc_cnt_; } OB_INLINE int64_t get_real_free_cnt() { return real_free_cnt_; } OB_INLINE void increase_alloc_cnt() { ATOMIC_INC(&alloc_cnt_); } OB_INLINE void increase_free_cnt() { ATOMIC_INC(&free_cnt_); } OB_INLINE void increase_free_queue_cnt() { ATOMIC_INC(&queue_len_); } OB_INLINE void decrease_free_queue_cnt() { ATOMIC_DEC(&queue_len_); } int64_t get_total_memory_size() { return size_per_buffer_ * queue_len_; } int get_max_mem_percent(); void update_max_memory_percent(); int64_t get_buffer_size() { return size_per_buffer_; } int auto_free_on_time(int64_t cur_max_reserve_count); OB_INLINE int64_t queue_cnt() { return free_queue_.size(); } private: bool out_of_memory(); int64_t get_used_memory_size(); int64_t get_max_dtl_memory_size(); int64_t get_max_tenant_memory_limit_size(); void real_free(ObDtlLinkedBuffer* buf); private: uint64_t tenant_id_; int64_t size_per_buffer_; int64_t seqno_; static const int64_t MAX_CAPACITY = 1024; common::LightyQueue free_queue_; common::ObFIFOAllocator allocator_; int64_t pre_alloc_cnt_; double max_mem_percent_; // some statistics int64_t alloc_cnt_; int64_t free_cnt_; int64_t queue_len_; int64_t real_alloc_cnt_; int64_t real_free_cnt_; }; OB_INLINE int64_t ObDtlChannelMemManager::get_used_memory_size() { // common::ObModItem item; // lib::get_tenant_mod_memory(tenant_id_, common::ObModIds::OB_SQL_DTL, item); // return item.hold_; return 0; } OB_INLINE int64_t ObDtlChannelMemManager::get_max_dtl_memory_size() { if (0 == max_mem_percent_) { get_max_mem_percent(); } return get_max_tenant_memory_limit_size() * max_mem_percent_ / 100; } OB_INLINE int64_t ObDtlChannelMemManager::get_max_tenant_memory_limit_size() { int64_t percent_execpt_memstore = 100 - GCONF.memstore_limit_percentage; return lib::get_tenant_memory_limit(tenant_id_) * percent_execpt_memstore / 100; } OB_INLINE bool ObDtlChannelMemManager::out_of_memory() { bool oom = false; int64_t used = get_used_memory_size(); int64_t max_dtl_memory_size = get_max_dtl_memory_size(); if (used > max_dtl_memory_size) { oom = true; } return oom; } OB_INLINE void ObDtlChannelMemManager::update_max_memory_percent() { get_max_mem_percent(); } } // namespace dtl } // namespace sql } // namespace oceanbase #endif /* OB_DTL_CHANNEL_MEM_MANEGER_H */
22.711957
88
0.74324
7364d0de1039d7dec398a680750665c589b649ed
575
h
C
imgui_markup/include/imgui_markup/objects/attribute_types/object_float2.h
FluxxCode/imgui_layer
0b0b73b132160d483259d88c9b024fdb2e1d3e63
[ "MIT" ]
null
null
null
imgui_markup/include/imgui_markup/objects/attribute_types/object_float2.h
FluxxCode/imgui_layer
0b0b73b132160d483259d88c9b024fdb2e1d3e63
[ "MIT" ]
null
null
null
imgui_markup/include/imgui_markup/objects/attribute_types/object_float2.h
FluxxCode/imgui_layer
0b0b73b132160d483259d88c9b024fdb2e1d3e63
[ "MIT" ]
null
null
null
#ifndef IMGUI_MARKUP_INCLUDE_IMGUI_MARKUP_OBJECTS_ATTRIBUTE_TYPES_OBJECT_FLOAT2_H_ #define IMGUI_MARKUP_INCLUDE_IMGUI_MARKUP_OBJECTS_ATTRIBUTE_TYPES_OBJECT_FLOAT2_H_ #include "imgui_markup/objects/common/object.h" #include "imgui_markup/attribute_types/float2.h" namespace imgui_markup { struct ObjectFloat2 : public Object { ObjectFloat2(std::string id, Object* parent); ObjectFloat2& operator=(const ObjectFloat2& other); Float2 value; }; } // namespace imgui_markup #endif // IMGUI_MARKUP_INCLUDE_IMGUI_MARKUP_OBJECTS_ATTRIBUTE_TYPES_OBJECT_FLOAT2_H_
26.136364
85
0.833043
738b6d7425ec16fa2dea3de466ee1188001b7c19
661
c
C
qemu/scsi/pr-manager-stub.c
hyunjoy/scripts
01114d3627730d695b5ebe61093c719744432ffa
[ "Apache-2.0" ]
55
2019-12-20T03:25:14.000Z
2022-01-16T07:19:47.000Z
qemu/scsi/pr-manager-stub.c
hyunjoy/scripts
01114d3627730d695b5ebe61093c719744432ffa
[ "Apache-2.0" ]
3
2021-07-27T19:36:05.000Z
2021-12-31T02:20:53.000Z
qemu/scsi/pr-manager-stub.c
hyunjoy/scripts
01114d3627730d695b5ebe61093c719744432ffa
[ "Apache-2.0" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
/* * Persistent reservation manager - stub for non-Linux platforms * * Copyright (c) 2018 Red Hat, Inc. * * Author: Paolo Bonzini <pbonzini@redhat.com> * * This code is licensed under the LGPL. * */ #include "qemu/osdep.h" #include "qapi/error.h" #include "scsi/pr-manager.h" #include "trace.h" #include "qapi/qapi-types-block.h" #include "qapi/qapi-commands-block.h" PRManager *pr_manager_lookup(const char *id, Error **errp) { /* The classes do not exist at all! */ error_setg(errp, "No persistent reservation manager with id '%s'", id); return NULL; } PRManagerInfoList *qmp_query_pr_managers(Error **errp) { return NULL; }
21.322581
75
0.686838
485ffe8aaf936e88ce9d0411aedeb64b897dcd58
793
h
C
Twitter-Dumped/7.51.5/t1/T1NewsCameraCaptureCameraScribeValue.h
ichitaso/TwitterListEnabler
d4d9ba973e59ff7f0d97ae74fc473bdd0aea54df
[ "MIT" ]
1
2019-10-15T09:26:49.000Z
2019-10-15T09:26:49.000Z
Twitter-Dumped/7.60.6/T1NewsCameraCaptureCameraScribeValue.h
ichitaso/TwitterListEnabler
d4d9ba973e59ff7f0d97ae74fc473bdd0aea54df
[ "MIT" ]
null
null
null
Twitter-Dumped/7.60.6/T1NewsCameraCaptureCameraScribeValue.h
ichitaso/TwitterListEnabler
d4d9ba973e59ff7f0d97ae74fc473bdd0aea54df
[ "MIT" ]
1
2019-11-17T06:06:49.000Z
2019-11-17T06:06:49.000Z
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <objc/NSObject.h> @interface T1NewsCameraCaptureCameraScribeValue : NSObject { long long _position; long long _flashMode; long long _orientation; } @property(readonly, nonatomic) long long orientation; // @synthesize orientation=_orientation; @property(readonly, nonatomic) long long flashMode; // @synthesize flashMode=_flashMode; @property(readonly, nonatomic) long long position; // @synthesize position=_position; - (_Bool)isEqual:(id)arg1; - (unsigned long long)hash; - (id)initWithPosition:(long long)arg1 flashMode:(long long)arg2 orientation:(long long)arg3; - (id)init; @end
30.5
94
0.736444
092391b8196446478d10b96b2c3270cde1589c5a
16,547
c
C
handc/runtime/smemory.c
dkolbly/rscheme
cb112d601ac9b99fadbbce3263d6677d91e78313
[ "TCL" ]
15
2015-02-05T14:59:12.000Z
2021-02-04T07:13:00.000Z
handc/runtime/smemory.c
dkolbly/rscheme
cb112d601ac9b99fadbbce3263d6677d91e78313
[ "TCL" ]
null
null
null
handc/runtime/smemory.c
dkolbly/rscheme
cb112d601ac9b99fadbbce3263d6677d91e78313
[ "TCL" ]
2
2016-02-17T07:26:02.000Z
2018-08-19T06:26:53.000Z
/*-----------------------------------------------------------------*-C-*--- * File: %p% * * Copyright (C)1997 Donovan Kolbly <d.kolbly@rscheme.org> * as part of the RScheme project, licensed for free use. * See <http://www.rscheme.org/> for the latest information. * * File version: %I% * File mod date: %E% %U% * System build: %b% * * Purpose: RScheme<-->Memory interface (scheme side) *------------------------------------------------------------------------*/ #include <string.h> #include <rscheme/gcadapt.h> #include <rscheme/scheme.h> #include <rscheme/smemory.h> #include <rscheme/gcserver.h> #include <rscheme/runtime.h> #ifdef ATRACE #include <rscheme/atrace.h> #endif #include <rscheme/profile.h> #ifdef COUNT_ALLOCS unsigned total_alloc_bytes = 0; unsigned total_alloc_objects = 0; #endif #ifndef INLINES #define SMLINK_TYPE /* nothing */ #include "smemory.ci" #include "readwrit.ci" #endif struct HeapTypeDecl *(rs_heap_type_info[MAX_HEAP_TYPES]); static void gvec_scanner( obj item, gc_scan_found_fn *found, void *info ) { obj *p, *limit; p = (obj *)PTR_TO_DATAPTR(item); limit = (obj *)((char *)p + SIZEOF_PTR(item)); while (p < limit) { found( info, *p++ ); } } static struct HeapTypeDecl gvec_heap_type_info = { "gvec", gvec_scanner }; static void null_scanner( obj item, gc_scan_found_fn *found, void *info ) { return; } static struct HeapTypeDecl bvec_heap_type_info = { "bvec", null_scanner }; static struct HeapTypeDecl fsw_heap_type_info = { "first-slot-weak", gvec_scanner /* scans the same as a gvec */ }; static void aa_scanner( obj item, gc_scan_found_fn *found, void *info ) { obj *p = (obj *)PTR_TO_DATAPTR(item); found( info, p[0] ); found( info, p[1] ); } static struct HeapTypeDecl aa_heap_type_info = { "alloc-area", aa_scanner }; static struct HeapTypeDecl immob_heap_type_info = { "immob", null_scanner }; static struct HeapTypeDecl abstract_heap_type_info = { "abstract", null_scanner }; void init_smemory( void ) { unsigned i; for (i=0; i<MAX_HEAP_TYPES; i++) { rs_heap_type_info[i] = NULL; } rs_heap_type_info[0] = &gvec_heap_type_info; rs_heap_type_info[1] = &bvec_heap_type_info; rs_heap_type_info[2] = &immob_heap_type_info; rs_heap_type_info[3] = &abstract_heap_type_info; rs_heap_type_info[4] = &fsw_heap_type_info; rs_heap_type_info[5] = &aa_heap_type_info; } void rs_add_heap_type( int type, struct HeapTypeDecl *info ) { if ((type < 0) || (type >= MAX_HEAP_TYPES)) { scheme_error( "add-heap-type: ~d is out of range", 1, int2fx( type ) ); } if (rs_heap_type_info[ type ]) { scheme_error( "add-heap-type: heap type ~d is already in use by ~s", 2, int2fx( type ), make_string( rs_heap_type_info[type]->name ) ); } rs_heap_type_info[ type ] = info; } void gc_work( UINT_32 amt ) { INT_32 t = amt; while (amt > 0) { /* * guarantee progress each time through the loop */ if (gc_alloc_time <= 1) { amt -= 1; } else if (gc_alloc_time > amt) { amt = 0; } else { amt -= gc_alloc_time; } gc_alloc_time = -1; gc_safe_point( 5000 ); } } #ifdef NDEBUG #define BVEC_ACCESS(bvec,byte_offset,opn,type) \ ((type *)((char *)PTR_TO_DATAPTR(bvec) + byte_offset)) #else #define BVEC_ACCESS(bvec,byte_offset,opn,type) \ ((type *)bvec_access_check( bvec, byte_offset, opn, sizeof(type) )) static void *bvec_access_check( obj bvec, UINT_32 byte_offset, char *opn, size_t type_size ) { if (!BVEC_P(bvec)) { scheme_error( "bvec-~a: invalid argument (~s not a bvec)", 2, make_string(opn), bvec ); } else if (byte_offset + type_size > SIZEOF_PTR(bvec)) { scheme_error( "bvec-~a: invalid offset\n" "(~#*@40s at +~d for ~d is out of range (~d max))", 5, make_string(opn), bvec, int2fx(byte_offset), int2fx(type_size), int2fx(SIZEOF_PTR(bvec)) ); } return (char *)PTR_TO_DATAPTR(bvec) + byte_offset; } #endif INT_8 bvec_read_int8( obj bvec, UINT_32 byte_offset ) { return *BVEC_ACCESS( bvec, byte_offset, "read-signed-8", INT_8 ); } UINT_16 bvec_read_uint16( obj bvec, UINT_32 byte_offset ) { return *BVEC_ACCESS( bvec, byte_offset, "read-unsigned-16", UINT_16 ); } INT_16 bvec_read_int16( obj bvec, UINT_32 byte_offset ) { return *BVEC_ACCESS( bvec, byte_offset, "read-signed-16", INT_16 ); } INT_32 bvec_read_int32( obj bvec, UINT_32 byte_offset ) { return *BVEC_ACCESS( bvec, byte_offset, "read-signed-32", INT_32 ); } INT_64 bvec_read_int64( obj bvec, UINT_32 byte_offset ) { return *BVEC_ACCESS( bvec, byte_offset, "read-signed-64", INT_64 ); } IEEE_32 bvec_read_ieee32( obj bvec, UINT_32 byte_offset ) { return *BVEC_ACCESS( bvec, byte_offset, "read-ieee-32", IEEE_32 ); } IEEE_64 bvec_read_ieee64( obj bvec, UINT_32 byte_offset ) { return *BVEC_ACCESS( bvec, byte_offset, "read-signed-16", IEEE_64 ); } void bvec_write_uint8( obj bvec, UINT_32 byte_offset, UINT_8 v ) { *BVEC_ACCESS( bvec, byte_offset, "write-unsigned-8", UINT_8 ) = v; } void bvec_write_int8( obj bvec, UINT_32 byte_offset, INT_8 v ) { *BVEC_ACCESS( bvec, byte_offset, "write-signed-8", INT_8 ) = v; } void bvec_write_uint16( obj bvec, UINT_32 byte_offset, UINT_16 v ) { *BVEC_ACCESS( bvec, byte_offset, "write-unsigned-16", UINT_16 ) = v; } void bvec_write_int16( obj bvec, UINT_32 byte_offset, INT_16 v ) { *BVEC_ACCESS( bvec, byte_offset, "write-signed-16", INT_16 ) = v; } void bvec_write_int32( obj bvec, UINT_32 byte_offset, INT_32 v ) { *BVEC_ACCESS( bvec, byte_offset, "write-signed-32", INT_32 ) = v; } void bvec_write_int64( obj bvec, UINT_32 byte_offset, INT_64 v ) { *BVEC_ACCESS( bvec, byte_offset, "write-signed-64", INT_64 ) = v; } void bvec_write_ieee32( obj bvec, UINT_32 byte_offset, IEEE_32 v ) { *BVEC_ACCESS( bvec, byte_offset, "write-ieee-32", IEEE_32 ) = v; } void bvec_write_ieee64( obj bvec, UINT_32 byte_offset, IEEE_64 v ) { *BVEC_ACCESS( bvec, byte_offset, "write-ieee-64", IEEE_64 ) = v; } /************************************************************************/ /* Object relocation support * * given a hash table mapping source->dest objects, * (1) do all mappings in the root set * (2) arrange to trip the read barrier for all source objects * * (returns the number of root pointers replaced) */ #if INCLUDE_READ_BARRIER static void setup_read_barrier_1( void *info, obj h, obj k, obj v ) { /* can't replace non-pointers, and don't allow replacement with non-ptrs */ if (PTR_P(k) && PTR_P(v)) { POBHeader *p = PTR_TO_HDRPTR(k); if (CLASS_P(k)) { if (CLASS_P(v)) { int *q = (int *)info; *q = 1; } else { scheme_error( "relocate-objects: can't replace class ~s with ~s\n", 2, k, v ); } } p->pob_class = ZERO; p->pob_size = VAL(v); } } static int do_class_rplc( void *info, void *ptr ) { POBHeader *p = (POBHeader *)ptr; obj h, k, v, tbl = *(obj *)info; k = p->pob_class; h = obj_hash(k); v = objecttable_lookup( tbl, h, k ); if (truish(v)) { p->pob_class = v; } return 0; } struct root_rplc_info { obj tbl; int count; }; static int do_root_rplc( obj *proot, void *info ) { if (PTR_P(*proot)) { struct root_rplc_info *i = (struct root_rplc_info *)info; obj h, k, v; k = *proot; h = obj_hash(k); v = objecttable_lookup( i->tbl, h, k ); if (truish(v)) { printf( "relocating root: %#x => %#x\n", VAL(k), VAL(v) ); *proot = v; i->count++; } } return 0; } #endif int rs_relocate_objects( obj tbl ) { #if INCLUDE_READ_BARRIER int need_heap_scan_q = 0; struct root_rplc_info i; hashtable_foreach( tbl, (void *)&need_heap_scan_q, setup_read_barrier_1 ); i.tbl = tbl; i.count = 0; process_all_roots( do_root_rplc, &i ); if (need_heap_scan_q) { gc_for_each( do_class_rplc, &tbl ); } return i.count; #else scheme_error( "relocate-objects: not implemented w/o read barrier", 0 ); return 0; #endif } /************************************************************************/ #define BUCKET_SIZE (200) struct item_ent { obj item; UINT_32 offset; }; struct all_bucket { struct all_bucket *next; struct item_ent elements[BUCKET_SIZE]; }; struct all_list { struct all_bucket *head; unsigned head_count; unsigned total_count; obj seek; }; static void add_to_list( void *info, obj item, UINT_32 offset ) { struct all_list *list = (struct all_list *)info; struct all_bucket *buck; if (list->head_count >= BUCKET_SIZE) { /* add a new bucket */ buck = (struct all_bucket *)malloc( sizeof(struct all_bucket) ); buck->next = list->head; list->head = buck; list->head_count = 0; } else { buck = list->head; } buck->elements[list->head_count].item = item; buck->elements[list->head_count].offset = offset; list->head_count++; list->total_count++; } static int check_1_obj( void *info, void *ptr ) { POBHeader *p = (POBHeader *)ptr; struct all_list *list = (struct all_list *)info; if (EQ(p->pob_class,list->seek)) { add_to_list( info, GCPTR_TO_PTR(ptr), 0 ); } return 0; } static int check_1_ptrs( void *info, void *ptr ) { POBHeader *p = (POBHeader *)ptr; struct all_list *list = (struct all_list *)info; if (CLASS_GVEC_P(p->pob_class)) { obj *s = (obj *)(p+1); UINT_32 i; for (i=0; i<p->pob_size; i+=SLOT(1)) { if (EQ(*s,list->seek)) { add_to_list( info, GCPTR_TO_PTR(ptr), i ); } s++; } } return 0; } obj all_instances( obj of_class ) { struct all_list list; struct all_bucket *b, temp; obj v; unsigned i, j, n; temp.next = NULL; list.head_count = list.total_count = 0; list.head = &temp; list.seek = of_class; gc_for_each( check_1_obj, &list ); v = alloc( SLOT(list.total_count), vector_class ); j = 0; for (b=list.head, n=list.head_count; b; b=b->next, n=BUCKET_SIZE) { for (i=0; i<n; i++) { gvec_write_init( v, j, b->elements[i].item ); j += SLOT(1); } } while (1) { b = list.head; if (b == &temp) break; list.head = b->next; free( b ); } return v; } /* A variant of all_pointers_to() that is useful during gdb() sessions */ void rs_find_pointers( obj instance ) { struct all_list list; struct all_bucket *b, temp; unsigned i, j, n; temp.next = NULL; list.head_count = list.total_count = 0; list.head = &temp; list.seek = instance; gc_for_each( check_1_ptrs, &list ); fprintf( stderr, "Found %u pointers to {%08lx}\n", list.total_count, VAL(instance) ); j = 0; for (b=list.head, n=list.head_count; b; b=b->next, n=BUCKET_SIZE) { struct item_ent *e; e = b->elements; for (i=0; i<n; i++, e++) { fprintf( stderr, " [%u] from {%08lx} SLOT(%lu) ; a %s\n", j, VAL(e->item), e->offset / SLOT(1), symbol_text( class_name( CLASSOF_PTR( e->item ) ) ) ); j++; } } while (1) { b = list.head; if (b == &temp) break; list.head = b->next; free( b ); } } obj all_pointers_to( obj instance ) { struct all_list list; struct all_bucket *b, temp; obj v; unsigned i, j, n; temp.next = NULL; list.head_count = list.total_count = 0; list.head = &temp; list.seek = instance; gc_for_each( check_1_ptrs, &list ); v = alloc( SLOT(list.total_count), vector_class ); j = 0; for (b=list.head, n=list.head_count; b; b=b->next, n=BUCKET_SIZE) { struct item_ent *e; e = b->elements; for (i=0; i<n; i++, e++) { gvec_write_init( v, j, cons( e->item, RIBYTES_TO_FXWORDS(e->offset) ) ); j += SLOT(1); } } while (1) { b = list.head; if (b == &temp) break; list.head = b->next; free( b ); } return v; } obj clone( obj from ) { return clone2( from, object_class(from) ); } obj clone2( obj from, obj new_class ) { obj htype, the_class, newobj = FALSE_OBJ; UINT_32 length, i; if (!OBJ_ISA_PTR(from)) scheme_error( "clone2: ~s not a heap object", 1, from ); the_class = CLASSOF_PTR(from); htype = gvec_read( the_class, SLOT(1) ); if (!EQ(htype,gvec_read(new_class,SLOT(1)))) { scheme_error( "clone2: new class ~s is incompatible with ~s", 2, new_class, the_class ); } length = SIZEOF_PTR(from); switch (fx2int(htype)) { case 0: /* gvec */ newobj = alloc( length, new_class ); for (i=0; i<length; i+=SLOT(1)) gvec_write_init( newobj, i, gvec_read( from, i ) ); break; case 1: /* bvec */ newobj = bvec_alloc( length, new_class ); memcpy( PTR_TO_DATAPTR(newobj), PTR_TO_DATAPTR(from), length ); break; default: scheme_error( "clone2: internal error: heap type ~s invalid", 2, htype ); } return newobj; } /********************** allocation areas ***********************/ /* * default allocation implementation */ obj default_alloc_obj( AllocArea *area, obj obj_class, UINT_32 bytes ) { return alloc( bytes, obj_class ); } obj make_gvec( obj the_class, UINT_32 size, obj fill ) { obj item = alloc( size, the_class ); if (OBJ_ISA_PTR(fill)) while (size > 0) { size -= SLOT(1); gvec_write_init_ptr( item, size, fill ); } else while (size > 0) { size -= SLOT(1); gvec_write_init_non_ptr( item, size, fill ); } return item; } obj subvector( obj vec, obj start, obj end ) { UINT_32 k; obj result, len; assert( VECTOR_P(vec) ); assert( OBJ_ISA_FIXNUM(start) ); assert( OBJ_ISA_FIXNUM(end) ); /* range checking */ if (FX_LT(start,ZERO) || FX_LT(end,start) || FX_GT(end,RIBYTES_TO_FXWORDS(SIZEOF_PTR(vec)))) { scheme_error( "subvector: invalid interval ~d - ~d for ~s", 3, start, end, vec ); } len = FX_SUB(end,start); result = alloc( FXWORDS_TO_RIBYTES(len), vector_class ); for (k=0; k<FXWORDS_TO_RIBYTES(len); k+=SLOT(1)) { gvec_write_init( result, k, gvec_ref( vec, FXWORDS_TO_RIBYTES(start) ) ); start = ADD1(start); } return result; } obj alloc_in_area( AllocArea *area, obj the_class, UINT_32 size ) { return area->allocfn( area, the_class, size ); } obj make_gvec_in_area( obj area, obj the_class, UINT_32 size, obj fill ) { obj item; assert( ALLOCAREA_P(area) ); item = alloc_in_area( AS_ALLOCAREA(area), the_class, size ); if (OBJ_ISA_PTR(fill)) { while (size > 0) { size -= SLOT(1); /* note that in the current, slightly askew scheme of things, gvec_write_fresh doesn't apply to allocations from other areas. Since we may have allocated from another area, we better use the regular write barrier. */ gvec_write_init_non_ptr( item, size, ZERO ); gvec_write( item, size, fill ); } } else { while (size > 0) { size -= SLOT(1); gvec_write_init_non_ptr( item, size, fill ); } } return item; } obj make_bvec_in_area( obj in_area, obj the_class, UINT_32 size, UINT_8 fill ) { obj item; assert( ALLOCAREA_P(in_area) ); item = alloc_in_area( AS_ALLOCAREA(in_area), the_class, size ); memset( PTR_TO_DATAPTR(item), fill, size ); return item; } #ifdef RS_PROFILE /* * `rs_profile_alloc' writes the profiling record for an allocation * called from smemory.ci:alloc() */ void rs_profile_alloc( obj the_class, UINT_32 bytes ) { rs_profile1( loading_image ? "<*from-system-image*>" : symbol_text(class_name(obj_class)), bytes ); } #endif #ifdef SIGUSR_HOOKS static int mark_thing( void *info, void *ptr ) { IRCH(ptr)->flagBits |= 0x80000000; return 0; } static int find_unmarked_things( void *info, void *ptr ) { if (!(IRCH(ptr)->flagBits & 0x80000000)) { fdebug_slots( (FILE*)info, GCPTR_TO_PTR(ptr) ); } return 0; } void run_sigusr_hook( int sigusr_num ) /* 1 or 2 */ { FILE *f; switch (sigusr_num) { case 1: gc_for_each( mark_thing, (void *)0 ); break; case 2: gc_now(); f = fopen( "/tmp/newobjs.dat", "w" ); gc_for_each( find_unmarked_things, (void *)f ); fclose(f); break; } } #endif /* SIGUSR_HOOKS */
22.121658
79
0.610624
6e0967e96dfd37f3b5335be466dced35957539be
415
h
C
WooNetwork/WooNetwork/Client/ClientNetwork.h
jstzwd/WooNetwork
d74a556de4a00129bbeed47549696dc5f39292b2
[ "Apache-2.0" ]
null
null
null
WooNetwork/WooNetwork/Client/ClientNetwork.h
jstzwd/WooNetwork
d74a556de4a00129bbeed47549696dc5f39292b2
[ "Apache-2.0" ]
null
null
null
WooNetwork/WooNetwork/Client/ClientNetwork.h
jstzwd/WooNetwork
d74a556de4a00129bbeed47549696dc5f39292b2
[ "Apache-2.0" ]
null
null
null
#pragma once #include <WinSock2.h> #include <WS2tcpip.h> #include "..\Base\NetworkCommunication.h" #include <iostream> namespace Woo { namespace Client { #define DEFAULT_PORT "1000" #define MAX_PACKAGE_SIZE 1000000 class ClientNetwork { public: SOCKET m_clientSocket; u_long m_blockingMode; ClientNetwork(u_long blockingMode); ~ClientNetwork(); int ReceiveData(char* receBuffer); }; } }
16.6
41
0.73012
abb85e37fcb4b27a3b55c6b213bd0736e18ce2f7
5,752
h
C
WWDirectComputeTest/WWDirectComputeUser.h
yamamoto2002/bitspersampleconv2
331a9fc531269e5dfdc78548e583f793a7687dc0
[ "MIT" ]
null
null
null
WWDirectComputeTest/WWDirectComputeUser.h
yamamoto2002/bitspersampleconv2
331a9fc531269e5dfdc78548e583f793a7687dc0
[ "MIT" ]
null
null
null
WWDirectComputeTest/WWDirectComputeUser.h
yamamoto2002/bitspersampleconv2
331a9fc531269e5dfdc78548e583f793a7687dc0
[ "MIT" ]
1
2020-11-12T06:55:18.000Z
2020-11-12T06:55:18.000Z
// 日本語。 #pragma once #include <d3d11.h> #include <map> #include <list> #include <stdint.h> /// 読み出し専用GPUメモリ管理情報 struct WWReadOnlyGpuBufferInfo { ID3D11Resource *pBuf; ID3D11ShaderResourceView *pSrv; }; /// 読み書き可能GPUメモリ管理情報 struct WWReadWriteGpuBufferInfo { ID3D11Resource *pBuf; ID3D11UnorderedAccessView *pUav; }; /// Either pSrv or pUav is needed. nullptr == unneeded struct WWTexture1DParams { int Width; int MipLevels; int ArraySize; DXGI_FORMAT Format; D3D11_USAGE Usage; int BindFlags; int CPUAccessFlags; int MiscFlags; const float * data; int dataCount; const char *name; ID3D11ShaderResourceView **pSrv; ID3D11UnorderedAccessView **pUav; }; class WWDirectComputeUser { public: WWDirectComputeUser(void); ~WWDirectComputeUser(void); HRESULT Init(void); void Term(void); // ComputeShaderをコンパイルしてGPUに送る HRESULT CreateComputeShader( LPCWSTR path, LPCSTR entryPoint, const D3D_SHADER_MACRO *defines, ID3D11ComputeShader **ppCS); void DestroyComputeShader(ID3D11ComputeShader *pCS); // 入力データ(読み出し専用)をGPUメモリに送る HRESULT SendReadOnlyDataAndCreateShaderResourceView( unsigned int uElementSize, unsigned int uCount, void * pSendData, const char *name, ID3D11ShaderResourceView **ppSrv); void DestroyDataAndShaderResourceView( ID3D11ShaderResourceView * pSrv); /// 入出力可能データをGPUメモリに作成。 /// @param pSendData nullptrでも可。 HRESULT CreateBufferAndUnorderedAccessView( unsigned int uElementSize, unsigned int uCount, void *pSendData, const char *name, ID3D11UnorderedAccessView **ppUav); void DestroyDataAndUnorderedAccessView( ID3D11UnorderedAccessView * pUav); // 実行。中でブロックする。 HRESULT Run( ID3D11ComputeShader * pComputeShader, UINT nNumSRV, ID3D11ShaderResourceView * ppSRV[], UINT nNumUAV, ID3D11UnorderedAccessView * ppUAV[], void * pCSData, DWORD dwNumDataBytes, UINT X, UINT Y, UINT Z); // 計算結果をGPUから取り出す。 HRESULT RecvResultToCpuMemory( ID3D11UnorderedAccessView * pUav, void *dest, int bytes); ID3D11Device *GetDevice(void) { return m_pDevice; } HRESULT CreateConstantBuffer( unsigned int uElementSize, unsigned int uCount, const char *name, ID3D11Buffer **ppBufOut); void DestroyConstantBuffer(ID3D11Buffer * pBuf); void DestroyTexture1D(ID3D11Texture1D *pTex); HRESULT CreateSeveralTexture1D(int n, WWTexture1DParams *params); private: ID3D11Device* m_pDevice; ID3D11DeviceContext* m_pContext; ID3D11Buffer *m_pConstBuffer; HRESULT CreateComputeDevice(void); HRESULT CreateBufferShaderResourceView( ID3D11Buffer * pBuffer, const char *name, ID3D11ShaderResourceView ** ppSrvOut); HRESULT CreateBufferUnorderedAccessView( ID3D11Buffer * pBuffer, const char *name, ID3D11UnorderedAccessView ** ppUavOut); std::map<ID3D11ShaderResourceView *, WWReadOnlyGpuBufferInfo> m_readGpuBufInfo; std::map<ID3D11UnorderedAccessView *, WWReadWriteGpuBufferInfo> m_rwGpuBufInfo; std::list<ID3D11ComputeShader*> m_computeShaderList; HRESULT CreateStructuredBuffer( unsigned int uElementSize, unsigned int uCount, void * pInitData, const char *name, ID3D11Buffer ** ppBufOut); HRESULT CreateTexture1D( int Width, int MipLevels, int ArraySize, DXGI_FORMAT Format, D3D11_USAGE Usage, int BindFlags, int CPUAccessFlags, int MiscFlags, const void *pInitialData, uint32_t initialDataBytes, ID3D11Texture1D **ppTexOut ); HRESULT CreateTexture1DAndShaderResourceView( int Width, int MipLevels, int ArraySize, DXGI_FORMAT Format, D3D11_USAGE Usage, int BindFlags, int CPUAccessFlags, int MiscFlags, const float * data, int dataCount, const char *name, ID3D11ShaderResourceView **ppSrv); HRESULT CreateTexture1DAndUnorderedAccessView( int Width, int MipLevels, int ArraySize, DXGI_FORMAT Format, D3D11_USAGE Usage, int BindFlags, int CPUAccessFlags, int MiscFlags, const float * data, int dataCount, const char *name, ID3D11UnorderedAccessView **ppUav); HRESULT CreateTexture1DShaderResourceView( ID3D11Texture1D * pTex, DXGI_FORMAT format, const char *name, ID3D11ShaderResourceView ** ppSrvOut); HRESULT CreateTexture1DUnorderedAccessView( ID3D11Texture1D * pTex, DXGI_FORMAT format, const char *name, ID3D11UnorderedAccessView ** ppUavOut); // Runの代わりに、SetupDispatch() Dispatch() UnsetupDispatch()しても良い。 HRESULT SetupDispatch( ID3D11ComputeShader * pComputeShader, UINT nNumSRV, ID3D11ShaderResourceView * ppSRV[], UINT nNumUAV, ID3D11UnorderedAccessView * ppUAV[], void *pCSData, //< constant buffer data on CPU memory DWORD dwNumDataBytes); /// Constant buffer無しバージョン。 void Dispatch( UINT X, UINT Y, UINT Z); void UnsetupDispatch(void); };
27.132075
84
0.627608
822241c8b428a00910e4aa552eaf754f0bc30180
8,085
c
C
bootstrap/instantiate.c
nanocritical/n
52324a7c9fab49a37c842a43d6c25d7cef4750b3
[ "Apache-2.0" ]
null
null
null
bootstrap/instantiate.c
nanocritical/n
52324a7c9fab49a37c842a43d6c25d7cef4750b3
[ "Apache-2.0" ]
null
null
null
bootstrap/instantiate.c
nanocritical/n
52324a7c9fab49a37c842a43d6c25d7cef4750b3
[ "Apache-2.0" ]
null
null
null
#include "instantiate.h" #include "types.h" #include "topdeps.h" #include "unify.h" #include "passzero.h" // Does not itself check that 'args' are valid types for instantiation. // This is done in passfwd.c:validate_genarg_types(). static ERROR do_instantiate(struct typ **result, struct module *mod, const struct node *for_error, ssize_t for_error_offset, struct typ *t, struct typ **args, size_t arity) { BEGTIMEIT(TIMEIT_INSTANTIATE_TOTAL); BEGTIMEIT(TIMEIT_INSTANTIATE); BEGTIMEIT(TIMEIT_INSTANTIATE_INTF); BEGTIMEIT(TIMEIT_INSTANTIATE_REF); assert(arity == 0 || (typ_is_generic_functor(t) && arity == typ_generic_arity(t))); struct node *gendef = typ_definition_ignore_any_overlay(t); if (node_toplevel(gendef)->generic->pristine == NULL) { if (for_error == NULL) { assert(false && "Not supposed to fail when for_error is NULL"); } else { error e = mk_except_type(mod, for_error, "not a generic functor"); EXCEPT(e); } } struct node *pristine = node_toplevel(gendef)->generic->pristine; struct node *instance = create_instance_deepcopy_from_pristine(mod, gendef, pristine); node_toplevel(instance)->generic->for_error = for_error; // Do not use set_typ()! With second-order generics, we actually do not // want to update this value when linking to another type during // unification. If the functor for instance->typ gets linked to something // else, then instance->typ itself must be linked to something else. // Making instance unreachable (through a typ). // See also types.c:link_generic_arg_update(). node_toplevel(instance)->generic->our_generic_functor_typ = t; struct node *genargs = subs_at(instance, IDX_GENARGS); struct node *ga = subs_first(genargs); for (size_t n = 0; n < arity; ++n) { node_set_which(ga, SETGENARG); if (args[n] == NULL) { ga = next(ga); continue; } struct node *ga_arg = subs_last(ga); node_set_which(ga_arg, DIRECTDEF); set_typ(&ga_arg->as.DIRECTDEF.typ, args[n]); ga_arg->as.DIRECTDEF.flags = NODE_IS_TYPE; if (for_error != NULL) { ga->as.SETGENARG.for_error = for_error_offset >= 0 && for_error_offset+n < subs_count(for_error) ? subs_at_const(for_error, for_error_offset+n) : for_error; } ga = next(ga); } error e = catchup_instantiation(mod, node_module_owner(gendef), instance, false); if (e) { if (for_error != NULL) { char *n = pptyp(mod, t); e = mk_except_type(mod, for_error, "while instantiating generic here '%s'", n); free(n); } THROW(e); } *result = instance->typ; ENDTIMEIT(typ_is_reference(instance->typ), TIMEIT_INSTANTIATE_REF); ENDTIMEIT(instance->which == DEFINTF, TIMEIT_INSTANTIATE_INTF); ENDTIMEIT(true, TIMEIT_INSTANTIATE); ENDTIMEIT(true, TIMEIT_INSTANTIATE_TOTAL); return 0; } static ERROR do_instantiate_tentative(struct typ **result, struct module *mod, const struct node *for_error, ssize_t for_error_offset, struct typ *t, struct typ **args, size_t arity) { BEGTIMEIT(TIMEIT_INSTANTIATE_TENTATIVE); BEGTIMEIT(TIMEIT_INSTANTIATE_TENTATIVE_INTF); BEGTIMEIT(TIMEIT_INSTANTIATE_TENTATIVE_REF); *result = typ_create_tentative(mod, t, args, arity); ENDTIMEIT(typ_is_reference(*result), TIMEIT_INSTANTIATE_TENTATIVE_REF); ENDTIMEIT(typ_definition_which(*result) == DEFINTF, TIMEIT_INSTANTIATE_TENTATIVE_INTF); ENDTIMEIT(true, TIMEIT_INSTANTIATE_TENTATIVE); return 0; } static bool instantiation_is_ungenarg_or_tentative(const struct module *mod, struct typ *t, struct typ **args, size_t arity) { if (mod->state->tentatively || mod->state->top_state != NULL) { if (arity == 0) { return true; } if (typ_is_ungenarg(t) || typ_is_tentative(t)) { return true; } for (size_t n = 0; n < arity; ++n) { if (args[n] == NULL) { return true; } if (typ_is_ungenarg(args[n]) || typ_is_tentative(args[n])) { return true; } } // Optimisation: immediately turn into a final instantiation. return false; } else { return false; } } error instantiate(struct typ **result, struct module *mod, const struct node *for_error, ssize_t for_error_offset, struct typ *t, struct typ **args, size_t arity, bool reject_identical) { assert(arity == typ_generic_arity(t)); if (!reject_identical) { struct typ *r = instances_find_existing_identical(mod, t, args, arity); if (r != NULL) { if (result != NULL) { *result = r; } return 0; } } const bool tentative = instantiation_is_ungenarg_or_tentative(mod, t, args, arity); bool is_ungenarg = typ_is_ungenarg(t); for (size_t n = 0; n < arity; ++n) { is_ungenarg |= args[n] == NULL ? false : typ_is_ungenarg(args[n]); } if (!tentative && !is_ungenarg) { struct typ *r = instances_find_existing_final_with(t, args, arity); if (r != NULL) { if (result != NULL) { *result = r; } return 0; } } if (tentative) { error e = do_instantiate_tentative(result, mod, for_error, for_error_offset, t, args, arity); EXCEPT(e); } else { error e = do_instantiate(result, mod, for_error, for_error_offset, t, args, arity); EXCEPT(e); } return 0; } struct typ *tentative_generic_arg(struct module *mod, const struct node *for_error, struct typ *t, size_t n) { struct typ *ga = typ_generic_arg(t, n); const size_t arity = typ_generic_arity(ga); if (arity == 0) { assert(!typ_is_tentative(ga)); return instantiate_fully_implicit(mod, for_error, ga); } else if (typ_is_generic_functor(ga)) { return typ_create_tentative_functor(mod, ga); } // Otherwise, the generic argument is declared as c:(`container t), where // t is another generic argument. The typ will be created by the ungenarg // mapping in typ_create_tentative. return NULL; } struct typ *instantiate_fully_implicit(struct module *mod, const struct node *for_error, struct typ *t) { if (typ_generic_arity(t) == 0) { assert(typ_definition_which(t) == DEFINTF || typ_is_isalist_literal(t)); return typ_create_tentative(mod, t, NULL, 0); } assert(typ_is_generic_functor(t) || typ_generic_arity(t) == 0); const size_t gen_arity = typ_generic_arity(t); struct typ **args = calloc(gen_arity, sizeof(struct typ *)); for (size_t n = 0; n < gen_arity; ++n) { assert(!typ_is_tentative(typ_generic_arg(t, n))); args[n] = tentative_generic_arg(mod, for_error, t, n); assert(args[n] == NULL || typ_is_tentative(args[n])); } struct typ *i = NULL; error e = instantiate(&i, mod, for_error, -1, t, args, gen_arity, true); // FIXME: Temporary workaround: it's actually legal for this code to // return an error, because of an error in the N code under consideration. // Some refactoring needs to be done so that we can raise the error // properly. In the meantime, we print it here when needed. if (e && g_env.running_example) { examples_destroy("<FIXME: unknown>"); } assert(!e); if (gen_arity == 0) { assert(typ_is_tentative(i)); } else { assert(typ_is_tentative(typ_generic_functor(i)) == typ_is_tentative(t)); } for (size_t n = 0; n < gen_arity; ++n) { assert(typ_is_tentative(typ_generic_arg(i, n)) && "FIXME: some generics cannot be instiated fully implicitly, e.g. Nonnull_cast"); } free(args); return i; }
33.135246
94
0.625727
79f946d664a6a926298ee724fd87ae57a54f3d80
11,697
c
C
IOT_Device/src/client.c
Victoooooor/IOT_FactoryData
3a56dfeed3574331612a4717075ea061385ef17e
[ "MIT" ]
null
null
null
IOT_Device/src/client.c
Victoooooor/IOT_FactoryData
3a56dfeed3574331612a4717075ea061385ef17e
[ "MIT" ]
null
null
null
IOT_Device/src/client.c
Victoooooor/IOT_FactoryData
3a56dfeed3574331612a4717075ea061385ef17e
[ "MIT" ]
null
null
null
#include "client.h" //初始化数据接收空间 static char tempbuf[512] = {0}; static cJSON *parsed_json,*json_dsp,*json_cmd; //显示二级缓存 static char data_str[20] = {0}; int server_connect(char* ip, int port) { int re; int fd = 0; struct sockaddr_in addr; struct timeval timeout; memset(&addr, 0,sizeof(addr)); //配置连接设置 addr.sin_port = htons((short)port); if(addr.sin_port==0){ fprintf(stderr,"PORT FORMAT ERROR\n"); goto err; } addr.sin_addr.s_addr = inet_addr(ip); if(addr.sin_addr.s_addr==IPADDR_NONE){ fprintf(stderr,"IP FORMAT ERROR\n"); goto err; } addr.sin_family = AF_INET; //生成socket fd = lwip_socket(AF_INET,SOCK_STREAM,0); if (fd < 0){ fprintf(stderr,"fail to creat socket errno = %d \r\n", errno); goto err; } fprintf(stderr, "Target Server fd=%d, ip=%s, port=%d\n", fd, ip, addr.sin_port); timeout.tv_sec = 10; timeout.tv_usec = 0; //设置socket re = lwip_setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO,(char *)&timeout, sizeof(timeout)); if (re < 0){ fprintf(stderr,"Set Socket options failed, Err: %d \r\n", errno); goto err; } //尝试连接 re = lwip_connect(fd, (const struct sockaddr*) &addr, sizeof(addr)); if (re != 0){ fprintf(stderr,"TCP Connection failed, Err: %d \r\n", errno); goto err; } event_publish(EVENT_TCP_CONNECTED,NULL);//发起连接成功事件 return fd; err: close(fd); aos_msleep(500); event_publish(EVENT_NETMGR_DHCP_SUCCESS,NULL);//发起连接失败事件 return -1; } static void data_send(void* argc, void* argv){ //检查环形缓存 if(ringbuf_is_empty(send_ringbuf)) return; //读取socket描述符 int* fd = (int*) argv; printf("FROM %d\r\n", *fd); //从环形缓存中读取数据转存入发送缓存 unsigned short num_packets = (512-send_ringbuf->freesize) / sizeof(packet); unsigned short *pack_len = buf+4; *pack_len = num_packets * sizeof(packet); unsigned short data_len; for (int i =0; i < num_packets; i++){ ringbuf_pop(send_ringbuf,buf+OVERHEAD+(i*sizeof(packet)),&data_len); if(data_len!=sizeof(packet)) fprintf(stderr,"size unmatched......\n"); } //生成校验 unsigned short total_Len = *pack_len+OVERHEAD+get_sum(buf+2,*pack_len+OVERHEAD-2); //传输数据 unsigned short ret = lwip_write(*fd, buf, total_Len); fprintf(stderr,"in data_send: %d\t%d\n", ret, data_len); fprintf(stderr,"checksum: %d\n",check_sum(buf,ret)); if(ret != total_Len){ // send failed send_state = false; } } static void data_recv(void* argc, void* argv){ int* fd = (int*) argv; int ret = lwip_recv(*fd, tempbuf,512,MSG_DONTWAIT); //不阻塞 printf("net read length:%d FROM %d\r\n", ret, *fd); if(ret > 0){ tempbuf[ret] = '\0'; fprintf(stderr,"msg: %s\r\n",tempbuf); //json解包 parsed_json = cJSON_Parse(tempbuf); if(parsed_json!=NULL){ //执行显示内容 json_dsp = cJSON_GetObjectItem(parsed_json,"dsp"); if(json_dsp != NULL){ if(json_dsp->type & (cJSON_String|cJSON_Raw)) _disp(2,json_dsp->valuestring,1); else if(json_dsp->type & cJSON_Number){ char temp_number[50] = {0}; snprintf(temp_number,50,"%.2E",json_dsp->valuedouble); _disp(2,temp_number,1); } } //支持执行服务端发送指令 json_cmd = cJSON_GetObjectItem(parsed_json,"cmd"); if(json_cmd != NULL){ ; } } else{ fprintf(stderr,"parsed NULL\r\n"); } } } static void data_disp(void* argc, void* argv){ int *data = (int*) argv; snprintf(data_str, 20, "%d\0",*data); _disp(1,data_str,1); } void data_collect(const int fd){ //重置变量 packet data; bool edge=0; send_state = true; s1=false; state=-1;//人工调用toggle_handler +=1,用于同步OLED toggle_handler(NULL); int uart_fd = -1; int port_id = 2; char dev_name[16] = {0}; char rfid_data_buf[50] = {0}; snprintf(dev_name, sizeof(dev_name), "/dev/ttyUART%d", port_id); fprintf(stderr, "opening device:%s\r\n", dev_name); uart_fd = open(dev_name, 0); if (uart_fd < 0) { fprintf(stderr, "open uart error\r\n"); _disp(0,"OPEN_UART F",1); aos_msleep(10000); aos_reboot(); } //初始化环形缓存 byte buf_ring[512]={0}; k_ringbuf_t ring; ringbuf_init(&ring,buf_ring,512,RINGBUF_TYPE_FIX,sizeof(packet)); if(!ringbuf_is_empty(&ring)) ringbuf_reset(&ring); send_ringbuf = &ring; //初始化1Hz数据发送 aos_timer_t send_timer; if(aos_timer_create(&send_timer,data_send,&fd,1000,AOS_TIMER_REPEAT)){ fprintf(stderr, "send_failed\n"); _disp(0, "send_failed",1); aos_msleep(1000); aos_reboot(); } //初始化0.5Hz数据接收 aos_timer_t recv_timer; if(aos_timer_create(&recv_timer,data_recv,&fd,2000,AOS_TIMER_REPEAT)){ fprintf(stderr, "recv_failed\n"); _disp(0, "recv_failed",1); aos_msleep(1000); aos_reboot(); } //初始化屏幕数据显示 int realtime = 0; aos_timer_t disp_timer; if(aos_timer_create(&disp_timer,data_disp,&realtime,250,AOS_TIMER_REPEAT|AOS_TIMER_AUTORUN)){ fprintf(stderr, "disp_failed\n"); _disp(0, "disp_failed",1); aos_msleep(1000); aos_reboot(); } //偏移数据指针 unsigned short *header= buf, *Device_ID = buf+2, *pack_len = buf+4, *checksum = buf+(OVERHEAD+sizeof(packet)); *header = PACKET_HEAD; *Device_ID = DEVICE_CODE; *pack_len = sizeof(packet); //初始化开关量PIN gpio_dev_t tg = { .config = INPUT_PULL_DOWN, .port = TOGGLE, }; gpio_dev_t tg2 = { .config = INPUT_PULL_DOWN, .port = SWITCH, }; hal_gpio_init(&tg); hal_gpio_init(&tg2); int ret = sizeof(buf); int ret_ADC[NUM_PIN] = {0}; //初始电压数据采集 adc_dev_t v1; adc_dev_t v2; adc_dev_t v3; v1.port = TEST_ADC_PORT_ADC0; v1.config.sampling_cycle = 1000; v2.port = TEST_ADC_PORT_ADC1; v2.config.sampling_cycle = 1000; v3.port = TEST_ADC_PORT_ADC2; v3.config.sampling_cycle = 1000; ret_ADC[0] = hal_adc_init(&v1); ret_ADC[1] = hal_adc_init(&v2); ret_ADC[2] = hal_adc_init(&v3); if (ret_ADC[0] || ret_ADC[1] || ret_ADC[2]){ _disp(0, "ADC Failed",1); aos_msleep(10000); aos_reboot(); } //初始USB-TTL pipeline [nonblocking] ret = ioctl(uart_fd, IOC_UART_SET_CFLAG, B19200 | CS8); if (ret != 0) { close(uart_fd); fprintf(stderr, "ioctl uart error\r\n"); _disp(0, "UART Failed",1); aos_msleep(10000); aos_reboot(); } //绑定开关量触发handler hal_gpio_enable_irq(&tg,IRQ_TRIGGER_RISING_EDGE,toggle_handler,NULL); hal_gpio_enable_irq(&tg2,IRQ_TRIGGER_RISING_EDGE,toggle_handler2,NULL); aos_timer_start(&send_timer);//开始数据传输 aos_timer_start(&recv_timer);//开始数据接收 while(send_state)//send_state为 { /* sampling speed * 数据采样频率 */ if(s1){ aos_msleep(50); if(!edge){ edge = 1; switch(state){ case 0: _disp(0,"NK-7001",0); break; case 1: _disp(0,"HD-1202E",0); break; case 2: _disp(0,"Model-520-2",0); break; default: break; }; } } else{ aos_msleep(1000); if(edge){ switch(state){ case 0: _disp(0,"NK-7001",1); break; case 1: _disp(0,"HD-1202E",1); break; case 2: _disp(0,"Model-520-2",1); break; default: break; }; edge = 0; } } data.state = (s1<<2) | state; hal_adc_value_get(&v1, &(data.ADC[0]),1000); hal_adc_value_get(&v2, &(data.ADC[1]),1000); hal_adc_value_get(&v3, &(data.ADC[2]),1000); //转换数据 data.ADC[0] = Electro_Meter(data.ADC[0]); ringbuf_push(&ring, &data, sizeof(packet)); realtime = data.ADC[0]; //micro USB 数据读写示例 ret = read(uart_fd, rfid_data_buf, sizeof(rfid_data_buf)); if (ret > 0) { printf("read length:%d\r\n", ret); for (int i = 0; i < ret; i++) { printf("%02x ", rfid_data_buf[i]); } printf("\r\n"); write(uart_fd,rfid_data_buf,ret); } else{ printf("reading\r\n"); } } //停止数据发送 aos_timer_stop(&send_timer); aos_timer_free(&send_timer); //停止数据接收 aos_timer_stop(&recv_timer); aos_timer_free(&recv_timer); //停止更新屏幕数据 aos_timer_stop(&disp_timer); aos_timer_free(&disp_timer); //释放内存 fprintf(stderr, "TCP_SEND failed\n"); _disp(0,"Send Failed",1); lwip_close(fd); close(fd); hal_gpio_clear_irq(&tg); hal_gpio_clear_irq(&tg2); hal_gpio_finalize(&tg); hal_gpio_finalize(&tg2); hal_adc_finalize(&v1); hal_adc_finalize(&v2); hal_adc_finalize(&v3); _disp(0, "finalized",1); // aos_free(ret_ADC); //this line is toxic, causes memory problem & system reboots event_publish(EVENT_NETMGR_DHCP_SUCCESS,NULL); return; } void toggle_handler(void* arg){ fprintf(stderr,"TOGGGGLE: %d\n",state); if (s1) return; state++; state%=3; switch(state){ case 0: _disp(0,"NK-7001",1); ctrl_set(1); break; case 1: _disp(0,"HD-1202E",1); ctrl_set(0); break; case 2: _disp(0,"Model-520-2",1); ctrl_set(1); break; default: break; }; } void toggle_handler2(void* arg){ fprintf(stderr,"SWIIIITCH: %d\n",s1); if(s1) s1=false; else{ s1 = true; } } unsigned short get_sum(byte* check, const int len){ int temp = 0; for(int i = 0; i < len/4; i++){ *(check+len+i) = 0; temp = 0; for(int j = 0; j < 4; j++){ temp += *(check+j*len/4+i); } *(check+len+i) = temp % 0xFF; *(check+len+i) = ~*(check+len+i); } return len/4; } int check_sum(byte* sent, unsigned short recvd){ unsigned short* start = (unsigned short*)sent; while (recvd && *start != 0xFFFF) { recvd--; } if (recvd <= 16) { return -1; } byte* check = (byte*)(start + 1); unsigned short* data_len = start + 2; unsigned short check_len = (*data_len + 4) / 4; for (int i = 0; i < check_len; i++) { int sum = 0; for (int j = 0; j < 5; j++) { sum += *(check + j * check_len + i); } sum %= 0xFF; if (sum) { return 1; } } return 0; } int Electro_Meter(int measured) { if (slope == .0) { slope = (V_high - V_low) / ((double)(M_high - M_low)); offset = (double)(V_high) - slope * M_high; slope2 = (V_high2 - V_low2) / ((double)(M_high2 - M_low2)); offset2 = (double)(V_high2) - slope2 * M_high2; } if(state == 0 | state == 2) return (int)(measured * slope + offset); else if(state == 1) return (int)(measured * slope2 + offset2); return 0; }
26.344595
97
0.540138
615bed4504c1e177bc18a49f7dfa70feae8581c2
1,011
h
C
Project 5/inc/Bank.h
ethanstockbridge/Advanced-Computer-Hardware-Design
dfc9ecc6e282d82bf8aa2b5e5dcb17234ef38d6c
[ "MIT" ]
null
null
null
Project 5/inc/Bank.h
ethanstockbridge/Advanced-Computer-Hardware-Design
dfc9ecc6e282d82bf8aa2b5e5dcb17234ef38d6c
[ "MIT" ]
null
null
null
Project 5/inc/Bank.h
ethanstockbridge/Advanced-Computer-Hardware-Design
dfc9ecc6e282d82bf8aa2b5e5dcb17234ef38d6c
[ "MIT" ]
null
null
null
/** * @file Bank.h * @author Ethan Stockbridge (ethanstockbridge@gmail.com) * @author Devan Kidd (jjkidd1245@gmail.com) * @brief Bank class * @date 2022-04-05 * */ #ifndef BANK_H #define BANK_H #include "Database.h" #include "Logger.h" #include "Request.h" /** * @brief Bank class to manage user's transactions and record to the database, and logger * */ class Bank { private: /** * @brief Database and logger for this bank's transactions * */ Database* myDB; Logger* myLog; public: /** * @brief Construct a new Bank object * * @param importDB Database to get/write the user information to * @param importLog Log to write the transactions to */ Bank(Database* importDB, Logger* importLog); /** * @brief Perform the request, req * * @param req Request to be performed * @return true Success * @return false Failure (possibly that user1 had no money) */ bool transfer(Request* req); }; #endif
19.442308
89
0.634026
b232492f9e3564142ca7d6027078bed86e304a26
8,260
h
C
istool/source/PageLanguages.h
YURSHAT/istool
544cfb9c180cc746e90a9e5cc2e56b60f709ff82
[ "BSD-3-Clause" ]
3
2020-04-24T23:21:48.000Z
2020-04-30T10:52:33.000Z
istool/source/PageLanguages.h
YURSHAT/istool
544cfb9c180cc746e90a9e5cc2e56b60f709ff82
[ "BSD-3-Clause" ]
null
null
null
istool/source/PageLanguages.h
YURSHAT/istool
544cfb9c180cc746e90a9e5cc2e56b60f709ff82
[ "BSD-3-Clause" ]
1
2021-09-02T03:29:47.000Z
2021-09-02T03:29:47.000Z
#pragma once #include "MyDoc.h" #include "FilesHelper.h" #include "StringToken.h" #include "DlgSelectLanguageFiles.h" ///////////////////////////////////////////////////////////////////////////// // CPageLanguages dialog class CPageLanguages : public CPropertyPageImpl<CPageLanguages>, public CMyPropertyPageBase<CPageLanguages>, public CWinDataExchange<CPageLanguages>, public Henden::CToolTipDialog<CPageLanguages> { public: enum { IDD = IDD_LANGUAGES }; BEGIN_MSG_MAP(CPageLanguages) CHAIN_MSG_MAP(Henden::CToolTipDialog<CPageLanguages>) CHAIN_MSG_MAP(CMyPropertyPageBase<CPageLanguages>) CHAIN_MSG_MAP(CPropertyPageImpl<CPageLanguages>) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_HANDLER(IDC_LANGUAGES_NAME, EN_CHANGE, OnModified) COMMAND_HANDLER(IDC_LANGUAGES_MESSAGESFILE, EN_CHANGE, OnModified) COMMAND_HANDLER(IDC_LANGUAGES_LICENSEFILE, EN_CHANGE, OnModified) COMMAND_HANDLER(IDC_LANGUAGES_INFOBEFOREFILE, EN_CHANGE, OnModified) COMMAND_HANDLER(IDC_LANGUAGES_INFOAFTERFILE, EN_CHANGE, OnModified) COMMAND_HANDLER(IDC_LANGUAGES_MESSAGESFILE2, BN_CLICKED, OnSelectLanguageFiles) REFLECT_NOTIFICATIONS() END_MSG_MAP() BEGIN_DDX_MAP(CPageLanguages) DDX_CONTROL(IDC_LANGUAGES_LICENSEFILE2, m_btnLicenseFile) DDX_CONTROL(IDC_LANGUAGES_INFOBEFOREFILE2, m_btnInfoBeforeFile) DDX_CONTROL(IDC_LANGUAGES_INFOAFTERFILE2, m_btnInfoAfterFile) DDX_TEXT(IDC_LANGUAGES_NAME, m_strName) DDX_TEXT(IDC_LANGUAGES_MESSAGESFILE, m_strMessagesFile) DDX_TEXT(IDC_LANGUAGES_LICENSEFILE, m_strLicenseFile) DDX_TEXT(IDC_LANGUAGES_INFOBEFOREFILE, m_strInfoBeforeFile) DDX_TEXT(IDC_LANGUAGES_INFOAFTERFILE, m_strInfoAfterFile) END_DDX_MAP() CString m_strName, m_strMessagesFile, m_strLicenseFile, m_strInfoBeforeFile, m_strInfoAfterFile; Henden::CButtonFile m_btnLicenseFile, m_btnInfoBeforeFile, m_btnInfoAfterFile; CButton m_btnMessagesFile; LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { m_btnMessagesFile.Attach(GetDlgItem(IDC_LANGUAGES_MESSAGESFILE2)); _L(m_hWnd,"Languages"); for(int nPos=0;nPos<m_list.GetSize();nPos++) { CScriptLine* pLine = m_list[nPos]; if(m_strName.CompareNoCase(SAFESTR(pLine->GetParameter("Name")))) m_strName.Empty(); if(m_strMessagesFile.CompareNoCase(SAFESTR(pLine->GetParameter("MessagesFile")))) m_strMessagesFile.Empty(); if(m_strLicenseFile.CompareNoCase(SAFESTR(pLine->GetParameter("LicenseFile")))) m_strLicenseFile.Empty(); if(m_strInfoBeforeFile.CompareNoCase(SAFESTR(pLine->GetParameter("InfoBeforeFile")))) m_strInfoBeforeFile.Empty(); if(m_strInfoAfterFile.CompareNoCase(SAFESTR(pLine->GetParameter("InfoAfterFile")))) m_strInfoAfterFile.Empty(); } DoDataExchange(DDX_LOAD); return TRUE; } LRESULT OnApply() { DoDataExchange(DDX_SAVE); const bool bForce = m_list.GetSize()==1; if(bForce && m_strName.IsEmpty()) { AtlMessageBox(m_hWnd,_L("You must enter a name."),IDR_MAINFRAME,MB_OK|MB_ICONERROR); return PSNRET_INVALID; } if(bForce && m_strMessagesFile.IsEmpty()) { AtlMessageBox(m_hWnd,_L("You must enter a messages file."),IDR_MAINFRAME,MB_OK|MB_ICONERROR); return PSNRET_INVALID; } for(int nPos=0;nPos<m_list.GetSize();nPos++) { CScriptLine* pLine = m_list[nPos]; CInnoScriptEx::SetString(pLine,bForce,"Name",m_strName); CInnoScriptEx::SetString(pLine,bForce,"MessagesFile",m_strMessagesFile); CInnoScriptEx::SetString(pLine,bForce,"LicenseFile",m_strLicenseFile); CInnoScriptEx::SetString(pLine,bForce,"InfoBeforeFile",m_strInfoBeforeFile); CInnoScriptEx::SetString(pLine,bForce,"InfoAfterFile",m_strInfoAfterFile); } return PSNRET_NOERROR; } LRESULT OnModified(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { if(!m_bNew) SetModified(); return 0; } LRESULT OnSelectLanguageFiles(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { DoDataExchange(DDX_SAVE,IDC_LANGUAGES_MESSAGESFILE); CDlgSelectLanguageFiles dlg(m_strMessagesFile); if(dlg.DoModal(m_hWnd)==IDOK) { m_strMessagesFile = dlg.m_strResult; DoDataExchange(DDX_LOAD,IDC_LANGUAGES_MESSAGESFILE); if(!m_bNew) SetModified(); } return 0; } CString m_strTitle; CPageLanguages(CScriptList& list,CMyDoc* pDoc,const bool bNew) : m_pDoc(pDoc), m_bNew(bNew), m_list(list), // m_btnMessagesFile(true,"Message Files (*.isl)|*.isl|All Files (*.*)|*.*||"), m_btnLicenseFile(true,"License Files (.txt;.rtf)|*.txt;*.rtf|All Files (*.*)|*.*||"), m_btnInfoBeforeFile(true,"Info Files (.txt;.rtf)|*.txt;*.rtf|All Files (*.*)|*.*||"), m_btnInfoAfterFile(true,"Info Files (.txt;.rtf)|*.txt;*.rtf|All Files (*.*)|*.*||") { m_strTitle = _L("DialogTitles|Language","Language"); SetTitle((LPCTSTR)m_strTitle); for(int nPos=0;nPos<m_list.GetSize();nPos++) { CScriptLine* pLine = m_list[nPos]; m_strName = pLine->GetParameter("Name"); m_strMessagesFile = pLine->GetParameter("MessagesFile"); m_strLicenseFile = pLine->GetParameter("LicenseFile"); m_strInfoBeforeFile = pLine->GetParameter("InfoBeforeFile"); m_strInfoAfterFile = pLine->GetParameter("InfoAfterFile"); break; } } CScriptList& m_list; CMyDoc* m_pDoc; const bool m_bNew; BEGIN_TOOLTIP_MAP() TOOLTIP_HANDLER(IDC_LANGUAGES_LICENSEFILE2,"Specifies the name of an optional license agreement file, in .txt or .rtf (rich text) format, which is displayed before the user selects the destination directory for the program. This file must be located in your installation's source directory when running the Setup Compiler, unless a fully qualified pathname is specified or the pathname is prefixed by \"compiler:\", in which case it looks for the file in the Compiler directory.") TOOLTIP_HANDLER(IDC_LANGUAGES_INFOBEFOREFILE2,"Click this button to select a file.") TOOLTIP_HANDLER(IDC_LANGUAGES_INFOAFTERFILE2,"Click this button to select a file.") TOOLTIP_HANDLER(IDC_LANGUAGES_NAME,"The internal name of the language, which you can set to anything you like. This can used as a prefix on [LangOptions] or [Messages] section entries to have the entries apply to only one language. The {language} constant returns the internal name of the selected language.") TOOLTIP_HANDLER(IDC_LANGUAGES_MESSAGESFILE,"Specifies the name(s) of file(s) to read the default messages from. The file(s) must be located in your installation's source directory when running the Setup Compiler, unless a fully qualified pathname is specified or the pathname is prefixed by \"compiler:\", in which case it looks for the file in the Compiler directory") TOOLTIP_HANDLER(IDC_LANGUAGES_LICENSEFILE,"Specifies the name of an optional license agreement file, in .txt or .rtf (rich text) format, which is displayed before the user selects the destination directory for the program. This file must be located in your installation's source directory when running the Setup Compiler, unless a fully qualified pathname is specified or the pathname is prefixed by \"compiler:\", in which case it looks for the file in the Compiler directory.") TOOLTIP_HANDLER(IDC_LANGUAGES_INFOBEFOREFILE,"Specifies the name of an optional \"readme\" file, in .txt or .rtf (rich text) format, which is displayed before the user selects the destination directory for the program. This file must be located in your installation's source directory when running the Setup Compiler, unless a fully qualified pathname is specified or the pathname is prefixed by \"compiler:\", in which case it looks for the file in the Compiler directory.") TOOLTIP_HANDLER(IDC_LANGUAGES_INFOAFTERFILE,"Specifies the name of an optional \"readme\" file, in .txt or .rtf (rich text) format, which is displayed after a successful install. This file must be located in your installation's source directory when running the Setup Compiler, unless a fully qualified pathname is specified or the pathname is prefixed by \"compiler:\", in which case it looks for the file in the Compiler directory.\r\n\r\nThis differs from isreadme files in that this text is displayed as a page of the wizard, instead of in a separate Notepad window.") TOOLTIP_HANDLER(IDC_LANGUAGES_MESSAGESFILE2,"Click this button to select one or more language files.") END_TOOLTIP_MAP() };
56.190476
574
0.772397
ba2a5dae3598f98abac384ef20150c2e230203cf
863
h
C
native/java_header/org_apache_hadoop_hdfs_server_datanode_BlockSender.h
rhli/Degraded-First-Scheduler
aac85775c6d5236fb64dff1855f39fa81dd6479a
[ "Apache-2.0" ]
1
2015-08-11T06:57:22.000Z
2015-08-11T06:57:22.000Z
native/java_header/org_apache_hadoop_hdfs_server_datanode_BlockSender.h
rhli/Degraded-First-Scheduler
aac85775c6d5236fb64dff1855f39fa81dd6479a
[ "Apache-2.0" ]
null
null
null
native/java_header/org_apache_hadoop_hdfs_server_datanode_BlockSender.h
rhli/Degraded-First-Scheduler
aac85775c6d5236fb64dff1855f39fa81dd6479a
[ "Apache-2.0" ]
null
null
null
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class org_apache_hadoop_hdfs_server_datanode_BlockSender */ #ifndef _Included_org_apache_hadoop_hdfs_server_datanode_BlockSender #define _Included_org_apache_hadoop_hdfs_server_datanode_BlockSender #ifdef __cplusplus extern "C" { #endif #undef org_apache_hadoop_hdfs_server_datanode_BlockSender_MIN_BUFFER_WITH_TRANSFERTO #define org_apache_hadoop_hdfs_server_datanode_BlockSender_MIN_BUFFER_WITH_TRANSFERTO 65536L /* * Class: org_apache_hadoop_hdfs_server_datanode_BlockSender * Method: pmREncode * Signature: (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;III[I)V */ JNIEXPORT void JNICALL Java_org_apache_hadoop_hdfs_server_datanode_BlockSender_pmREncode (JNIEnv *, jobject, jobject, jobject, jint, jint, jint, jint, jintArray); #ifdef __cplusplus } #endif #endif
35.958333
92
0.841251
b5dc66a3069e5ed3f13b4612362e6fe5abc07ffb
479
h
C
Spy/Spy.h
appunite/Spy
5f5af7fc06e0e1f5f6d1c345e3cc401c50c92711
[ "MIT" ]
11
2020-01-25T12:02:18.000Z
2021-07-28T14:11:25.000Z
Spy/Spy.h
appunite/Spy
5f5af7fc06e0e1f5f6d1c345e3cc401c50c92711
[ "MIT" ]
8
2020-01-29T21:42:44.000Z
2020-07-28T08:31:38.000Z
Spy/Spy.h
appunite/Spy
5f5af7fc06e0e1f5f6d1c345e3cc401c50c92711
[ "MIT" ]
1
2020-01-23T19:01:18.000Z
2020-01-23T19:01:18.000Z
// // Spy.h // Spy // // Created by Tomasz Lewandowski on 22/01/2020. // Copyright © 2020 AppUnite Sp. z o.o. All rights reserved. // #import <Foundation/Foundation.h> //! Project version number for Spy. FOUNDATION_EXPORT double SpyVersionNumber; //! Project version string for Spy. FOUNDATION_EXPORT const unsigned char SpyVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <Spy/PublicHeader.h>
25.210526
128
0.743215
db4fddc92aeecba4710433e1be04cac89cebb880
956
h
C
src/Blob.h
shantha-a/vehicle-counting
8ce9fb13763536b71dea38cad3051cb60a43f55a
[ "MIT" ]
122
2017-08-23T06:31:41.000Z
2022-03-30T18:49:41.000Z
src/Blob.h
shantha-a/vehicle-counting
8ce9fb13763536b71dea38cad3051cb60a43f55a
[ "MIT" ]
5
2017-09-09T14:07:16.000Z
2021-02-06T16:28:24.000Z
src/Blob.h
shantha-a/vehicle-counting
8ce9fb13763536b71dea38cad3051cb60a43f55a
[ "MIT" ]
53
2017-08-08T06:12:51.000Z
2022-03-31T08:22:35.000Z
/* ---------------------------------------------- --- Author : Ahmet Özlü --- Mail : ahmetozlu93@gmail.com --- Date : 1st August 2017 --- Version : 1.0 --- OpenCV Version : 2.4.10 --- Demo Video : https://youtu.be/3uMKK28bMuY ---------------------------------------------- */ #ifndef MY_BLOB #define MY_BLOB #include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> class Blob { public: // member variables std::vector<cv::Point> currentContour; cv::Rect currentBoundingRect; std::vector<cv::Point> centerPositions; double dblCurrentDiagonalSize; double dblCurrentAspectRatio; bool blnCurrentMatchFoundOrNewBlob; bool blnStillBeingTracked; int intNumOfConsecutiveFramesWithoutAMatch; cv::Point predictedNextPosition; // function prototypes Blob(std::vector<cv::Point> _contour); void predictNextPosition(void); }; #endif // MY_BLOB
25.157895
49
0.635983
ca1028e7ab455abf1c3c06ada249c0097f707eb9
76,494
c
C
kernel/msm-4.14_1/drivers/dma/qcom/gpi.c
clovadevice/clockplus
156ba1d7a75aa3d45569916d02610737ca38cce0
[ "Apache-2.0" ]
null
null
null
kernel/msm-4.14_1/drivers/dma/qcom/gpi.c
clovadevice/clockplus
156ba1d7a75aa3d45569916d02610737ca38cce0
[ "Apache-2.0" ]
null
null
null
kernel/msm-4.14_1/drivers/dma/qcom/gpi.c
clovadevice/clockplus
156ba1d7a75aa3d45569916d02610737ca38cce0
[ "Apache-2.0" ]
1
2021-06-29T01:29:23.000Z
2021-06-29T01:29:23.000Z
/* Copyright (c) 2017-2019, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <asm/dma-iommu.h> #include <linux/atomic.h> #include <linux/completion.h> #include <linux/debugfs.h> #include <linux/device.h> #include <linux/dma-mapping.h> #include <linux/dmaengine.h> #include <linux/io.h> #include <linux/iommu.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/ipc_logging.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_address.h> #include <linux/of_dma.h> #include <linux/of_irq.h> #include <linux/platform_device.h> #include <linux/scatterlist.h> #include <linux/sched/clock.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <asm/cacheflush.h> #include <linux/msm_gpi.h> #include "../dmaengine.h" #include "../virt-dma.h" #include "msm_gpi_mmio.h" /* global logging macros */ #define GPI_LOG(gpi_dev, fmt, ...) do { \ if (gpi_dev->klog_lvl != LOG_LVL_MASK_ALL) \ dev_dbg(gpi_dev->dev, "%s: " fmt, __func__, ##__VA_ARGS__); \ if (gpi_dev->ilctxt && gpi_dev->ipc_log_lvl != LOG_LVL_MASK_ALL) \ ipc_log_string(gpi_dev->ilctxt, \ "%s: " fmt, __func__, ##__VA_ARGS__); \ } while (0) #define GPI_ERR(gpi_dev, fmt, ...) do { \ if (gpi_dev->klog_lvl >= LOG_LVL_ERROR) \ dev_err(gpi_dev->dev, "%s: " fmt, __func__, ##__VA_ARGS__); \ if (gpi_dev->ilctxt && gpi_dev->ipc_log_lvl >= LOG_LVL_ERROR) \ ipc_log_string(gpi_dev->ilctxt, \ "%s: " fmt, __func__, ##__VA_ARGS__); \ } while (0) /* gpii specific logging macros */ #define GPII_INFO(gpii, ch, fmt, ...) do { \ if (gpii->klog_lvl >= LOG_LVL_INFO) \ pr_info("%s:%u:%s: " fmt, gpii->label, ch, \ __func__, ##__VA_ARGS__); \ if (gpii->ilctxt && gpii->ipc_log_lvl >= LOG_LVL_INFO) \ ipc_log_string(gpii->ilctxt, \ "ch:%u %s: " fmt, ch, \ __func__, ##__VA_ARGS__); \ } while (0) #define GPII_ERR(gpii, ch, fmt, ...) do { \ if (gpii->klog_lvl >= LOG_LVL_ERROR) \ pr_err("%s:%u:%s: " fmt, gpii->label, ch, \ __func__, ##__VA_ARGS__); \ if (gpii->ilctxt && gpii->ipc_log_lvl >= LOG_LVL_ERROR) \ ipc_log_string(gpii->ilctxt, \ "ch:%u %s: " fmt, ch, \ __func__, ##__VA_ARGS__); \ } while (0) #define GPII_CRITIC(gpii, ch, fmt, ...) do { \ if (gpii->klog_lvl >= LOG_LVL_CRITICAL) \ pr_err("%s:%u:%s: " fmt, gpii->label, ch, \ __func__, ##__VA_ARGS__); \ if (gpii->ilctxt && gpii->ipc_log_lvl >= LOG_LVL_CRITICAL) \ ipc_log_string(gpii->ilctxt, \ "ch:%u %s: " fmt, ch, \ __func__, ##__VA_ARGS__); \ } while (0) enum DEBUG_LOG_LVL { LOG_LVL_MASK_ALL, LOG_LVL_CRITICAL, LOG_LVL_ERROR, LOG_LVL_INFO, LOG_LVL_VERBOSE, LOG_LVL_REG_ACCESS, }; enum EV_PRIORITY { EV_PRIORITY_ISR, EV_PRIORITY_TASKLET, }; #define GPI_DMA_DRV_NAME "gpi_dma" #define DEFAULT_KLOG_LVL (LOG_LVL_CRITICAL) #ifdef CONFIG_QCOM_GPI_DMA_DEBUG #define DEFAULT_IPC_LOG_LVL (LOG_LVL_VERBOSE) #define IPC_LOG_PAGES (40) #define GPI_DBG_LOG_SIZE (SZ_1K) /* size must be power of 2 */ #define CMD_TIMEOUT_MS (1000) #define GPII_REG(gpii, ch, fmt, ...) do { \ if (gpii->klog_lvl >= LOG_LVL_REG_ACCESS) \ pr_info("%s:%u:%s: " fmt, gpii->label, \ ch, __func__, ##__VA_ARGS__); \ if (gpii->ilctxt && gpii->ipc_log_lvl >= LOG_LVL_REG_ACCESS) \ ipc_log_string(gpii->ilctxt, \ "ch:%u %s: " fmt, ch, \ __func__, ##__VA_ARGS__); \ } while (0) #define GPII_VERB(gpii, ch, fmt, ...) do { \ if (gpii->klog_lvl >= LOG_LVL_VERBOSE) \ pr_info("%s:%u:%s: " fmt, gpii->label, \ ch, __func__, ##__VA_ARGS__); \ if (gpii->ilctxt && gpii->ipc_log_lvl >= LOG_LVL_VERBOSE) \ ipc_log_string(gpii->ilctxt, \ "ch:%u %s: " fmt, ch, \ __func__, ##__VA_ARGS__); \ } while (0) #else #define IPC_LOG_PAGES (2) #define GPI_DBG_LOG_SIZE (0) /* size must be power of 2 */ #define DEFAULT_IPC_LOG_LVL (LOG_LVL_ERROR) #define CMD_TIMEOUT_MS (250) /* verbose and register logging are disabled if !debug */ #define GPII_REG(gpii, ch, fmt, ...) #define GPII_VERB(gpii, ch, fmt, ...) #endif #define GPI_LABEL_SIZE (256) #define GPI_DBG_COMMON (99) #define MAX_CHANNELS_PER_GPII (2) #define GPI_TX_CHAN (0) #define GPI_RX_CHAN (1) #define STATE_IGNORE (U32_MAX) #define REQ_OF_DMA_ARGS (5) /* # of arguments required from client */ struct __packed gpi_error_log_entry { u32 routine : 4; u32 type : 4; u32 reserved0 : 4; u32 code : 4; u32 reserved1 : 3; u32 chid : 5; u32 reserved2 : 1; u32 chtype : 1; u32 ee : 1; }; struct __packed xfer_compl_event { u64 ptr; u32 length : 24; u8 code; u16 status; u8 type; u8 chid; }; struct __packed immediate_data_event { u8 data_bytes[8]; u8 length : 4; u8 resvd : 4; u16 tre_index; u8 code; u16 status; u8 type; u8 chid; }; struct __packed qup_notif_event { u32 status; u32 time; u32 count :24; u8 resvd; u16 resvd1; u8 type; u8 chid; }; struct __packed gpi_ere { u32 dword[4]; }; enum GPI_EV_TYPE { XFER_COMPLETE_EV_TYPE = 0x22, IMMEDIATE_DATA_EV_TYPE = 0x30, QUP_NOTIF_EV_TYPE = 0x31, STALE_EV_TYPE = 0xFF, }; union __packed gpi_event { struct __packed xfer_compl_event xfer_compl_event; struct __packed immediate_data_event immediate_data_event; struct __packed qup_notif_event qup_notif_event; struct __packed gpi_ere gpi_ere; }; enum gpii_irq_settings { DEFAULT_IRQ_SETTINGS, MASK_IEOB_SETTINGS, }; enum gpi_ev_state { DEFAULT_EV_CH_STATE = 0, EV_STATE_NOT_ALLOCATED = DEFAULT_EV_CH_STATE, EV_STATE_ALLOCATED, MAX_EV_STATES }; static const char *const gpi_ev_state_str[MAX_EV_STATES] = { [EV_STATE_NOT_ALLOCATED] = "NOT ALLOCATED", [EV_STATE_ALLOCATED] = "ALLOCATED", }; #define TO_GPI_EV_STATE_STR(state) ((state >= MAX_EV_STATES) ? \ "INVALID" : gpi_ev_state_str[state]) enum gpi_ch_state { DEFAULT_CH_STATE = 0x0, CH_STATE_NOT_ALLOCATED = DEFAULT_CH_STATE, CH_STATE_ALLOCATED = 0x1, CH_STATE_STARTED = 0x2, CH_STATE_STOPPED = 0x3, CH_STATE_STOP_IN_PROC = 0x4, CH_STATE_ERROR = 0xf, MAX_CH_STATES }; static const char *const gpi_ch_state_str[MAX_CH_STATES] = { [CH_STATE_NOT_ALLOCATED] = "NOT ALLOCATED", [CH_STATE_ALLOCATED] = "ALLOCATED", [CH_STATE_STARTED] = "STARTED", [CH_STATE_STOPPED] = "STOPPED", [CH_STATE_STOP_IN_PROC] = "STOP IN PROCESS", [CH_STATE_ERROR] = "ERROR", }; #define TO_GPI_CH_STATE_STR(state) ((state >= MAX_CH_STATES) ? \ "INVALID" : gpi_ch_state_str[state]) enum gpi_cmd { GPI_CH_CMD_BEGIN, GPI_CH_CMD_ALLOCATE = GPI_CH_CMD_BEGIN, GPI_CH_CMD_START, GPI_CH_CMD_STOP, GPI_CH_CMD_RESET, GPI_CH_CMD_DE_ALLOC, GPI_CH_CMD_UART_SW_STALE, GPI_CH_CMD_UART_RFR_READY, GPI_CH_CMD_UART_RFR_NOT_READY, GPI_CH_CMD_END = GPI_CH_CMD_UART_RFR_NOT_READY, GPI_EV_CMD_BEGIN, GPI_EV_CMD_ALLOCATE = GPI_EV_CMD_BEGIN, GPI_EV_CMD_RESET, GPI_EV_CMD_DEALLOC, GPI_EV_CMD_END = GPI_EV_CMD_DEALLOC, GPI_MAX_CMD, }; #define IS_CHAN_CMD(cmd) (cmd <= GPI_CH_CMD_END) static const char *const gpi_cmd_str[GPI_MAX_CMD] = { [GPI_CH_CMD_ALLOCATE] = "CH ALLOCATE", [GPI_CH_CMD_START] = "CH START", [GPI_CH_CMD_STOP] = "CH STOP", [GPI_CH_CMD_RESET] = "CH_RESET", [GPI_CH_CMD_DE_ALLOC] = "DE ALLOC", [GPI_CH_CMD_UART_SW_STALE] = "UART SW STALE", [GPI_CH_CMD_UART_RFR_READY] = "UART RFR READY", [GPI_CH_CMD_UART_RFR_NOT_READY] = "UART RFR NOT READY", [GPI_EV_CMD_ALLOCATE] = "EV ALLOCATE", [GPI_EV_CMD_RESET] = "EV RESET", [GPI_EV_CMD_DEALLOC] = "EV DEALLOC", }; #define TO_GPI_CMD_STR(cmd) ((cmd >= GPI_MAX_CMD) ? "INVALID" : \ gpi_cmd_str[cmd]) static const char *const gpi_cb_event_str[MSM_GPI_QUP_MAX_EVENT] = { [MSM_GPI_QUP_NOTIFY] = "NOTIFY", [MSM_GPI_QUP_ERROR] = "GLOBAL ERROR", [MSM_GPI_QUP_CH_ERROR] = "CHAN ERROR", [MSM_GPI_QUP_PENDING_EVENT] = "PENDING EVENT", [MSM_GPI_QUP_EOT_DESC_MISMATCH] = "EOT/DESC MISMATCH", [MSM_GPI_QUP_SW_ERROR] = "SW ERROR", }; #define TO_GPI_CB_EVENT_STR(event) ((event >= MSM_GPI_QUP_MAX_EVENT) ? \ "INVALID" : gpi_cb_event_str[event]) enum se_protocol { SE_PROTOCOL_SPI = 1, SE_PROTOCOL_UART = 2, SE_PROTOCOL_I2C = 3, SE_MAX_PROTOCOL }; /* * @DISABLE_STATE: no register access allowed * @CONFIG_STATE: client has configured the channel * @PREP_HARDWARE: register access is allowed * however, no processing EVENTS * @ACTIVE_STATE: channels are fully operational * @PREPARE_TERIMNATE: graceful termination of channels * register access is allowed * @PAUSE_STATE: channels are active, but not processing any events */ enum gpi_pm_state { DISABLE_STATE, CONFIG_STATE, PREPARE_HARDWARE, ACTIVE_STATE, PREPARE_TERMINATE, PAUSE_STATE, MAX_PM_STATE }; #define REG_ACCESS_VALID(pm_state) (pm_state >= PREPARE_HARDWARE) static const char *const gpi_pm_state_str[MAX_PM_STATE] = { [DISABLE_STATE] = "DISABLE", [CONFIG_STATE] = "CONFIG", [PREPARE_HARDWARE] = "PREPARE HARDWARE", [ACTIVE_STATE] = "ACTIVE", [PREPARE_TERMINATE] = "PREPARE TERMINATE", [PAUSE_STATE] = "PAUSE", }; #define TO_GPI_PM_STR(state) ((state >= MAX_PM_STATE) ? \ "INVALID" : gpi_pm_state_str[state]) static const struct { enum gpi_cmd gpi_cmd; u32 opcode; u32 state; u32 timeout_ms; } gpi_cmd_info[GPI_MAX_CMD] = { { GPI_CH_CMD_ALLOCATE, GPI_GPII_n_CH_CMD_ALLOCATE, CH_STATE_ALLOCATED, CMD_TIMEOUT_MS, }, { GPI_CH_CMD_START, GPI_GPII_n_CH_CMD_START, CH_STATE_STARTED, CMD_TIMEOUT_MS, }, { GPI_CH_CMD_STOP, GPI_GPII_n_CH_CMD_STOP, CH_STATE_STOPPED, CMD_TIMEOUT_MS, }, { GPI_CH_CMD_RESET, GPI_GPII_n_CH_CMD_RESET, CH_STATE_ALLOCATED, CMD_TIMEOUT_MS, }, { GPI_CH_CMD_DE_ALLOC, GPI_GPII_n_CH_CMD_DE_ALLOC, CH_STATE_NOT_ALLOCATED, CMD_TIMEOUT_MS, }, { GPI_CH_CMD_UART_SW_STALE, GPI_GPII_n_CH_CMD_UART_SW_STALE, STATE_IGNORE, CMD_TIMEOUT_MS, }, { GPI_CH_CMD_UART_RFR_READY, GPI_GPII_n_CH_CMD_UART_RFR_READY, STATE_IGNORE, CMD_TIMEOUT_MS, }, { GPI_CH_CMD_UART_RFR_NOT_READY, GPI_GPII_n_CH_CMD_UART_RFR_NOT_READY, STATE_IGNORE, CMD_TIMEOUT_MS, }, { GPI_EV_CMD_ALLOCATE, GPI_GPII_n_EV_CH_CMD_ALLOCATE, EV_STATE_ALLOCATED, CMD_TIMEOUT_MS, }, { GPI_EV_CMD_RESET, GPI_GPII_n_EV_CH_CMD_RESET, EV_STATE_ALLOCATED, CMD_TIMEOUT_MS, }, { GPI_EV_CMD_DEALLOC, GPI_GPII_n_EV_CH_CMD_DE_ALLOC, EV_STATE_NOT_ALLOCATED, CMD_TIMEOUT_MS, }, }; struct gpi_ring { void *pre_aligned; size_t alloc_size; phys_addr_t phys_addr; dma_addr_t dma_handle; void *base; void *wp; void *rp; u32 len; u32 el_size; u32 elements; bool configured; }; struct sg_tre { void *ptr; void *wp; /* store chan wp for debugging */ }; struct gpi_dbg_log { void *addr; u64 time; u32 val; bool read; }; struct gpi_dev { struct dma_device dma_device; struct device *dev; struct resource *res; void __iomem *regs; void __iomem *ee_base; /*ee register base address*/ u32 max_gpii; /* maximum # of gpii instances available per gpi block */ u32 gpii_mask; /* gpii instances available for apps */ u32 ev_factor; /* ev ring length factor */ u32 smmu_cfg; dma_addr_t iova_base; size_t iova_size; struct gpii *gpiis; void *ilctxt; u32 ipc_log_lvl; u32 klog_lvl; struct dentry *dentry; }; struct gpii_chan { struct virt_dma_chan vc; u32 chid; u32 seid; enum se_protocol protocol; enum EV_PRIORITY priority; /* comes from clients DT node */ struct gpii *gpii; enum gpi_ch_state ch_state; enum gpi_pm_state pm_state; void __iomem *ch_cntxt_base_reg; void __iomem *ch_cntxt_db_reg; void __iomem *ch_ring_base_lsb_reg, *ch_ring_rp_lsb_reg, *ch_ring_wp_lsb_reg; void __iomem *ch_cmd_reg; u32 req_tres; /* # of tre's client requested */ u32 dir; struct gpi_ring ch_ring; struct gpi_client_info client_info; }; struct gpii { u32 gpii_id; struct gpii_chan gpii_chan[MAX_CHANNELS_PER_GPII]; struct gpi_dev *gpi_dev; enum EV_PRIORITY ev_priority; enum se_protocol protocol; int irq; void __iomem *regs; /* points to gpi top */ void __iomem *ev_cntxt_base_reg; void __iomem *ev_cntxt_db_reg; void __iomem *ev_ring_base_lsb_reg, *ev_ring_rp_lsb_reg, *ev_ring_wp_lsb_reg; void __iomem *ev_cmd_reg; void __iomem *ieob_src_reg; void __iomem *ieob_clr_reg; struct mutex ctrl_lock; enum gpi_ev_state ev_state; bool configured_irq; enum gpi_pm_state pm_state; rwlock_t pm_lock; struct gpi_ring ev_ring; struct tasklet_struct ev_task; /* event processing tasklet */ struct completion cmd_completion; enum gpi_cmd gpi_cmd; u32 cntxt_type_irq_msk; void *ilctxt; u32 ipc_log_lvl; u32 klog_lvl; struct gpi_dbg_log dbg_log[GPI_DBG_LOG_SIZE]; atomic_t dbg_index; char label[GPI_LABEL_SIZE]; struct dentry *dentry; }; struct gpi_desc { struct virt_dma_desc vd; void *wp; /* points to TRE last queued during issue_pending */ void *db; /* DB register to program */ struct gpii_chan *gpii_chan; }; #define GPI_SMMU_ATTACH BIT(0) #define GPI_SMMU_S1_BYPASS BIT(1) #define GPI_SMMU_FAST BIT(2) #define GPI_SMMU_ATOMIC BIT(3) const u32 GPII_CHAN_DIR[MAX_CHANNELS_PER_GPII] = { GPI_CHTYPE_DIR_OUT, GPI_CHTYPE_DIR_IN }; struct dentry *pdentry; static irqreturn_t gpi_handle_irq(int irq, void *data); static void gpi_ring_recycle_ev_element(struct gpi_ring *ring); static int gpi_ring_add_element(struct gpi_ring *ring, void **wp); static void gpi_process_events(struct gpii *gpii); static inline struct gpii_chan *to_gpii_chan(struct dma_chan *dma_chan) { return container_of(dma_chan, struct gpii_chan, vc.chan); } static inline struct gpi_desc *to_gpi_desc(struct virt_dma_desc *vd) { return container_of(vd, struct gpi_desc, vd); } static inline phys_addr_t to_physical(const struct gpi_ring *const ring, void *addr) { return ring->phys_addr + (addr - ring->base); } static inline void *to_virtual(const struct gpi_ring *const ring, phys_addr_t addr) { return ring->base + (addr - ring->phys_addr); } #ifdef CONFIG_QCOM_GPI_DMA_DEBUG static inline u32 gpi_read_reg(struct gpii *gpii, void __iomem *addr) { u64 time = sched_clock(); unsigned int index = atomic_inc_return(&gpii->dbg_index) - 1; u32 val; val = readl_relaxed(addr); index &= (GPI_DBG_LOG_SIZE - 1); (gpii->dbg_log + index)->addr = addr; (gpii->dbg_log + index)->time = time; (gpii->dbg_log + index)->val = val; (gpii->dbg_log + index)->read = true; GPII_REG(gpii, GPI_DBG_COMMON, "offset:0x%lx val:0x%x\n", addr - gpii->regs, val); return val; } static inline void gpi_write_reg(struct gpii *gpii, void __iomem *addr, u32 val) { u64 time = sched_clock(); unsigned int index = atomic_inc_return(&gpii->dbg_index) - 1; index &= (GPI_DBG_LOG_SIZE - 1); (gpii->dbg_log + index)->addr = addr; (gpii->dbg_log + index)->time = time; (gpii->dbg_log + index)->val = val; (gpii->dbg_log + index)->read = false; GPII_REG(gpii, GPI_DBG_COMMON, "offset:0x%lx val:0x%x\n", addr - gpii->regs, val); writel_relaxed(val, addr); } #else static inline u32 gpi_read_reg(struct gpii *gpii, void __iomem *addr) { u32 val = readl_relaxed(addr); GPII_REG(gpii, GPI_DBG_COMMON, "offset:0x%lx val:0x%x\n", addr - gpii->regs, val); return val; } static inline void gpi_write_reg(struct gpii *gpii, void __iomem *addr, u32 val) { GPII_REG(gpii, GPI_DBG_COMMON, "offset:0x%lx val:0x%x\n", addr - gpii->regs, val); writel_relaxed(val, addr); } #endif /* gpi_write_reg_field - write to specific bit field */ static inline void gpi_write_reg_field(struct gpii *gpii, void __iomem *addr, u32 mask, u32 shift, u32 val) { u32 tmp = gpi_read_reg(gpii, addr); tmp &= ~mask; val = tmp | ((val << shift) & mask); gpi_write_reg(gpii, addr, val); } static void gpi_disable_interrupts(struct gpii *gpii) { struct { u32 offset; u32 mask; u32 shift; u32 val; } default_reg[] = { { GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_BMSK, GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_SHFT, 0, }, { GPI_GPII_n_CNTXT_SRC_IEOB_IRQ_MSK_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_SRC_IEOB_IRQ_MSK_BMSK, GPI_GPII_n_CNTXT_SRC_IEOB_IRQ_MSK_SHFT, 0, }, { GPI_GPII_n_CNTXT_SRC_CH_IRQ_MSK_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_SRC_CH_IRQ_MSK_BMSK, GPI_GPII_n_CNTXT_SRC_CH_IRQ_MSK_SHFT, 0, }, { GPI_GPII_n_CNTXT_SRC_EV_CH_IRQ_MSK_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_SRC_EV_CH_IRQ_MSK_BMSK, GPI_GPII_n_CNTXT_SRC_EV_CH_IRQ_MSK_SHFT, 0, }, { GPI_GPII_n_CNTXT_GLOB_IRQ_EN_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_GLOB_IRQ_EN_BMSK, GPI_GPII_n_CNTXT_GLOB_IRQ_EN_SHFT, 0, }, { GPI_GPII_n_CNTXT_GPII_IRQ_EN_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_GPII_IRQ_EN_BMSK, GPI_GPII_n_CNTXT_GPII_IRQ_EN_SHFT, 0, }, { GPI_GPII_n_CNTXT_INTSET_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_INTSET_BMSK, GPI_GPII_n_CNTXT_INTSET_SHFT, 0, }, { 0 }, }; int i; for (i = 0; default_reg[i].offset; i++) gpi_write_reg_field(gpii, gpii->regs + default_reg[i].offset, default_reg[i].mask, default_reg[i].shift, default_reg[i].val); gpii->cntxt_type_irq_msk = 0; devm_free_irq(gpii->gpi_dev->dev, gpii->irq, gpii); gpii->configured_irq = false; } /* configure and enable interrupts */ static int gpi_config_interrupts(struct gpii *gpii, enum gpii_irq_settings settings, bool mask) { int ret; int i; const u32 def_type = (GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_GENERAL | GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_IEOB | GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_GLOB | GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_EV_CTRL | GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_CH_CTRL); struct { u32 offset; u32 mask; u32 shift; u32 val; } default_reg[] = { { GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_BMSK, GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_SHFT, def_type, }, { GPI_GPII_n_CNTXT_SRC_IEOB_IRQ_MSK_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_SRC_IEOB_IRQ_MSK_BMSK, GPI_GPII_n_CNTXT_SRC_IEOB_IRQ_MSK_SHFT, GPI_GPII_n_CNTXT_SRC_IEOB_IRQ_MSK_BMSK, }, { GPI_GPII_n_CNTXT_SRC_CH_IRQ_MSK_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_SRC_CH_IRQ_MSK_BMSK, GPI_GPII_n_CNTXT_SRC_CH_IRQ_MSK_SHFT, GPI_GPII_n_CNTXT_SRC_CH_IRQ_MSK_BMSK, }, { GPI_GPII_n_CNTXT_SRC_EV_CH_IRQ_MSK_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_SRC_EV_CH_IRQ_MSK_BMSK, GPI_GPII_n_CNTXT_SRC_EV_CH_IRQ_MSK_SHFT, GPI_GPII_n_CNTXT_SRC_EV_CH_IRQ_MSK_BMSK, }, { GPI_GPII_n_CNTXT_GLOB_IRQ_EN_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_GLOB_IRQ_EN_BMSK, GPI_GPII_n_CNTXT_GLOB_IRQ_EN_SHFT, GPI_GPII_n_CNTXT_GLOB_IRQ_EN_ERROR_INT, }, { GPI_GPII_n_CNTXT_GPII_IRQ_EN_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_GPII_IRQ_EN_BMSK, GPI_GPII_n_CNTXT_GPII_IRQ_EN_SHFT, GPI_GPII_n_CNTXT_GPII_IRQ_EN_BMSK, }, { GPI_GPII_n_CNTXT_MSI_BASE_LSB_OFFS (gpii->gpii_id), U32_MAX, 0, 0x0, }, { GPI_GPII_n_CNTXT_MSI_BASE_MSB_OFFS (gpii->gpii_id), U32_MAX, 0, 0x0, }, { GPI_GPII_n_CNTXT_SCRATCH_0_OFFS (gpii->gpii_id), U32_MAX, 0, 0x0, }, { GPI_GPII_n_CNTXT_SCRATCH_1_OFFS (gpii->gpii_id), U32_MAX, 0, 0x0, }, { GPI_GPII_n_CNTXT_INTSET_OFFS (gpii->gpii_id), GPI_GPII_n_CNTXT_INTSET_BMSK, GPI_GPII_n_CNTXT_INTSET_SHFT, 0x01, }, { GPI_GPII_n_ERROR_LOG_OFFS (gpii->gpii_id), U32_MAX, 0, 0x00, }, { 0 }, }; GPII_VERB(gpii, GPI_DBG_COMMON, "configured:%c setting:%s mask:%c\n", (gpii->configured_irq) ? 'F' : 'T', (settings == DEFAULT_IRQ_SETTINGS) ? "default" : "user_spec", (mask) ? 'T' : 'F'); if (gpii->configured_irq == false) { ret = devm_request_irq(gpii->gpi_dev->dev, gpii->irq, gpi_handle_irq, IRQF_TRIGGER_HIGH, gpii->label, gpii); if (ret < 0) { GPII_CRITIC(gpii, GPI_DBG_COMMON, "error request irq:%d ret:%d\n", gpii->irq, ret); return ret; } } if (settings == MASK_IEOB_SETTINGS) { /* * GPII only uses one EV ring per gpii so we can globally * enable/disable IEOB interrupt */ if (mask) gpii->cntxt_type_irq_msk |= GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_IEOB; else gpii->cntxt_type_irq_msk &= ~(GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_IEOB); gpi_write_reg_field(gpii, gpii->regs + GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_OFFS(gpii->gpii_id), GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_BMSK, GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_SHFT, gpii->cntxt_type_irq_msk); } else { for (i = 0; default_reg[i].offset; i++) gpi_write_reg_field(gpii, gpii->regs + default_reg[i].offset, default_reg[i].mask, default_reg[i].shift, default_reg[i].val); gpii->cntxt_type_irq_msk = def_type; }; gpii->configured_irq = true; return 0; } /* Sends gpii event or channel command */ static int gpi_send_cmd(struct gpii *gpii, struct gpii_chan *gpii_chan, enum gpi_cmd gpi_cmd) { u32 chid = MAX_CHANNELS_PER_GPII; u32 cmd; unsigned long timeout; void __iomem *cmd_reg; if (gpi_cmd >= GPI_MAX_CMD) return -EINVAL; if (IS_CHAN_CMD(gpi_cmd)) chid = gpii_chan->chid; GPII_INFO(gpii, chid, "sending cmd: %s\n", TO_GPI_CMD_STR(gpi_cmd)); /* send opcode and wait for completion */ reinit_completion(&gpii->cmd_completion); gpii->gpi_cmd = gpi_cmd; cmd_reg = IS_CHAN_CMD(gpi_cmd) ? gpii_chan->ch_cmd_reg : gpii->ev_cmd_reg; cmd = IS_CHAN_CMD(gpi_cmd) ? GPI_GPII_n_CH_CMD(gpi_cmd_info[gpi_cmd].opcode, chid) : GPI_GPII_n_EV_CH_CMD(gpi_cmd_info[gpi_cmd].opcode, 0); gpi_write_reg(gpii, cmd_reg, cmd); timeout = wait_for_completion_timeout(&gpii->cmd_completion, msecs_to_jiffies(gpi_cmd_info[gpi_cmd].timeout_ms)); if (!timeout) { GPII_ERR(gpii, chid, "cmd: %s completion timeout\n", TO_GPI_CMD_STR(gpi_cmd)); return -EIO; } /* confirm new ch state is correct , if the cmd is a state change cmd */ if (gpi_cmd_info[gpi_cmd].state == STATE_IGNORE) return 0; if (IS_CHAN_CMD(gpi_cmd) && gpii_chan->ch_state == gpi_cmd_info[gpi_cmd].state) return 0; if (!IS_CHAN_CMD(gpi_cmd) && gpii->ev_state == gpi_cmd_info[gpi_cmd].state) return 0; return -EIO; } /* program transfer ring DB register */ static inline void gpi_write_ch_db(struct gpii_chan *gpii_chan, struct gpi_ring *ring, void *wp) { struct gpii *gpii = gpii_chan->gpii; phys_addr_t p_wp; p_wp = to_physical(ring, wp); gpi_write_reg(gpii, gpii_chan->ch_cntxt_db_reg, (u32)p_wp); } /* program event ring DB register */ static inline void gpi_write_ev_db(struct gpii *gpii, struct gpi_ring *ring, void *wp) { phys_addr_t p_wp; p_wp = ring->phys_addr + (wp - ring->base); gpi_write_reg(gpii, gpii->ev_cntxt_db_reg, (u32)p_wp); } /* notify client with generic event */ static void gpi_generate_cb_event(struct gpii_chan *gpii_chan, enum msm_gpi_cb_event event, u64 status) { struct gpii *gpii = gpii_chan->gpii; struct gpi_client_info *client_info = &gpii_chan->client_info; struct msm_gpi_cb msm_gpi_cb = {0}; GPII_ERR(gpii, gpii_chan->chid, "notifying event:%s with status:%llu\n", TO_GPI_CB_EVENT_STR(event), status); msm_gpi_cb.cb_event = event; msm_gpi_cb.status = status; msm_gpi_cb.timestamp = sched_clock(); client_info->callback(&gpii_chan->vc.chan, &msm_gpi_cb, client_info->cb_param); } /* process transfer completion interrupt */ static void gpi_process_ieob(struct gpii *gpii) { gpi_write_reg(gpii, gpii->ieob_clr_reg, BIT(0)); /* process events based on priority */ if (likely(gpii->ev_priority >= EV_PRIORITY_TASKLET)) { GPII_VERB(gpii, GPI_DBG_COMMON, "scheduling tasklet\n"); gpi_config_interrupts(gpii, MASK_IEOB_SETTINGS, 0); tasklet_schedule(&gpii->ev_task); } else { GPII_VERB(gpii, GPI_DBG_COMMON, "processing events from isr\n"); gpi_process_events(gpii); } } /* process channel control interrupt */ static void gpi_process_ch_ctrl_irq(struct gpii *gpii) { u32 gpii_id = gpii->gpii_id; u32 offset = GPI_GPII_n_CNTXT_SRC_GPII_CH_IRQ_OFFS(gpii_id); u32 ch_irq = gpi_read_reg(gpii, gpii->regs + offset); u32 chid; struct gpii_chan *gpii_chan; u32 state; /* clear the status */ offset = GPI_GPII_n_CNTXT_SRC_CH_IRQ_CLR_OFFS(gpii_id); gpi_write_reg(gpii, gpii->regs + offset, (u32)ch_irq); for (chid = 0; chid < MAX_CHANNELS_PER_GPII; chid++) { if (!(BIT(chid) & ch_irq)) continue; gpii_chan = &gpii->gpii_chan[chid]; GPII_VERB(gpii, chid, "processing channel ctrl irq\n"); state = gpi_read_reg(gpii, gpii_chan->ch_cntxt_base_reg + CNTXT_0_CONFIG); state = (state & GPI_GPII_n_CH_k_CNTXT_0_CHSTATE_BMSK) >> GPI_GPII_n_CH_k_CNTXT_0_CHSTATE_SHFT; /* * CH_CMD_DEALLOC cmd always successful. However cmd does * not change hardware status. So overwriting software state * to default state. */ if (gpii->gpi_cmd == GPI_CH_CMD_DE_ALLOC) state = DEFAULT_CH_STATE; gpii_chan->ch_state = state; GPII_VERB(gpii, chid, "setting channel to state:%s\n", TO_GPI_CH_STATE_STR(gpii_chan->ch_state)); /* * Triggering complete all if ch_state is not a stop in process. * Stop in process is a transition state and we will wait for * stop interrupt before notifying. */ if (gpii_chan->ch_state != CH_STATE_STOP_IN_PROC) complete_all(&gpii->cmd_completion); /* notifying clients if in error state */ if (gpii_chan->ch_state == CH_STATE_ERROR) gpi_generate_cb_event(gpii_chan, MSM_GPI_QUP_CH_ERROR, __LINE__); } } /* processing gpi level error interrupts */ static void gpi_process_glob_err_irq(struct gpii *gpii) { u32 gpii_id = gpii->gpii_id; u32 offset = GPI_GPII_n_CNTXT_GLOB_IRQ_STTS_OFFS(gpii_id); u32 irq_stts = gpi_read_reg(gpii, gpii->regs + offset); u32 error_log; u32 chid; struct gpii_chan *gpii_chan; struct gpi_client_info *client_info; struct msm_gpi_cb msm_gpi_cb; struct gpi_error_log_entry *log_entry = (struct gpi_error_log_entry *)&error_log; offset = GPI_GPII_n_CNTXT_GLOB_IRQ_CLR_OFFS(gpii_id); gpi_write_reg(gpii, gpii->regs + offset, irq_stts); /* only error interrupt should be set */ if (irq_stts & ~GPI_GLOB_IRQ_ERROR_INT_MSK) { GPII_ERR(gpii, GPI_DBG_COMMON, "invalid error status:0x%x\n", irq_stts); goto error_irq; } offset = GPI_GPII_n_ERROR_LOG_OFFS(gpii_id); error_log = gpi_read_reg(gpii, gpii->regs + offset); gpi_write_reg(gpii, gpii->regs + offset, 0); /* get channel info */ chid = ((struct gpi_error_log_entry *)&error_log)->chid; if (unlikely(chid >= MAX_CHANNELS_PER_GPII)) { GPII_ERR(gpii, GPI_DBG_COMMON, "invalid chid reported:%u\n", chid); goto error_irq; } gpii_chan = &gpii->gpii_chan[chid]; client_info = &gpii_chan->client_info; /* notify client with error log */ msm_gpi_cb.cb_event = MSM_GPI_QUP_ERROR; msm_gpi_cb.error_log.routine = log_entry->routine; msm_gpi_cb.error_log.type = log_entry->type; msm_gpi_cb.error_log.error_code = log_entry->code; GPII_INFO(gpii, gpii_chan->chid, "sending CB event:%s\n", TO_GPI_CB_EVENT_STR(msm_gpi_cb.cb_event)); GPII_ERR(gpii, gpii_chan->chid, "ee:%u chtype:%u routine:%u type:%u error_code:%u\n", log_entry->ee, log_entry->chtype, msm_gpi_cb.error_log.routine, msm_gpi_cb.error_log.type, msm_gpi_cb.error_log.error_code); client_info->callback(&gpii_chan->vc.chan, &msm_gpi_cb, client_info->cb_param); return; error_irq: for (chid = 0, gpii_chan = gpii->gpii_chan; chid < MAX_CHANNELS_PER_GPII; chid++, gpii_chan++) gpi_generate_cb_event(gpii_chan, MSM_GPI_QUP_FW_ERROR, irq_stts); } /* gpii interrupt handler */ static irqreturn_t gpi_handle_irq(int irq, void *data) { struct gpii *gpii = data; u32 type; unsigned long flags; u32 offset; u32 gpii_id = gpii->gpii_id; GPII_VERB(gpii, GPI_DBG_COMMON, "enter\n"); read_lock_irqsave(&gpii->pm_lock, flags); /* * States are out of sync to receive interrupt * while software state is in DISABLE state, bailing out. */ if (!REG_ACCESS_VALID(gpii->pm_state)) { GPII_CRITIC(gpii, GPI_DBG_COMMON, "receive interrupt while in %s state\n", TO_GPI_PM_STR(gpii->pm_state)); goto exit_irq; } offset = GPI_GPII_n_CNTXT_TYPE_IRQ_OFFS(gpii->gpii_id); type = gpi_read_reg(gpii, gpii->regs + offset); do { GPII_VERB(gpii, GPI_DBG_COMMON, "CNTXT_TYPE_IRQ:0x%08x\n", type); /* global gpii error */ if (type & GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_GLOB) { GPII_ERR(gpii, GPI_DBG_COMMON, "processing global error irq\n"); gpi_process_glob_err_irq(gpii); type &= ~(GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_GLOB); } /* transfer complete interrupt */ if (type & GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_IEOB) { GPII_VERB(gpii, GPI_DBG_COMMON, "process IEOB interrupts\n"); gpi_process_ieob(gpii); type &= ~GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_IEOB; } /* event control irq */ if (type & GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_EV_CTRL) { u32 ev_state; u32 ev_ch_irq; GPII_INFO(gpii, GPI_DBG_COMMON, "processing EV CTRL interrupt\n"); offset = GPI_GPII_n_CNTXT_SRC_EV_CH_IRQ_OFFS(gpii_id); ev_ch_irq = gpi_read_reg(gpii, gpii->regs + offset); offset = GPI_GPII_n_CNTXT_SRC_EV_CH_IRQ_CLR_OFFS (gpii_id); gpi_write_reg(gpii, gpii->regs + offset, ev_ch_irq); ev_state = gpi_read_reg(gpii, gpii->ev_cntxt_base_reg + CNTXT_0_CONFIG); ev_state &= GPI_GPII_n_EV_CH_k_CNTXT_0_CHSTATE_BMSK; ev_state >>= GPI_GPII_n_EV_CH_k_CNTXT_0_CHSTATE_SHFT; /* * CMD EV_CMD_DEALLOC is always successful. However * cmd does not change hardware status. So overwriting * software state to default state. */ if (gpii->gpi_cmd == GPI_EV_CMD_DEALLOC) ev_state = DEFAULT_EV_CH_STATE; gpii->ev_state = ev_state; GPII_INFO(gpii, GPI_DBG_COMMON, "setting EV state to %s\n", TO_GPI_EV_STATE_STR(gpii->ev_state)); complete_all(&gpii->cmd_completion); type &= ~(GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_EV_CTRL); } /* channel control irq */ if (type & GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_CH_CTRL) { GPII_INFO(gpii, GPI_DBG_COMMON, "process CH CTRL interrupts\n"); gpi_process_ch_ctrl_irq(gpii); type &= ~(GPI_GPII_n_CNTXT_TYPE_IRQ_MSK_CH_CTRL); } if (type) { GPII_CRITIC(gpii, GPI_DBG_COMMON, "Unhandled interrupt status:0x%x\n", type); goto exit_irq; } offset = GPI_GPII_n_CNTXT_TYPE_IRQ_OFFS(gpii->gpii_id); type = gpi_read_reg(gpii, gpii->regs + offset); } while (type); exit_irq: read_unlock_irqrestore(&gpii->pm_lock, flags); GPII_VERB(gpii, GPI_DBG_COMMON, "exit\n"); return IRQ_HANDLED; } /* process qup notification events */ static void gpi_process_qup_notif_event(struct gpii_chan *gpii_chan, struct qup_notif_event *notif_event) { struct gpi_client_info *client_info = &gpii_chan->client_info; struct msm_gpi_cb msm_gpi_cb; GPII_VERB(gpii_chan->gpii, gpii_chan->chid, "status:0x%x time:0x%x count:0x%x\n", notif_event->status, notif_event->time, notif_event->count); msm_gpi_cb.cb_event = MSM_GPI_QUP_NOTIFY; msm_gpi_cb.status = notif_event->status; msm_gpi_cb.timestamp = notif_event->time; msm_gpi_cb.count = notif_event->count; GPII_VERB(gpii_chan->gpii, gpii_chan->chid, "sending CB event:%s\n", TO_GPI_CB_EVENT_STR(msm_gpi_cb.cb_event)); client_info->callback(&gpii_chan->vc.chan, &msm_gpi_cb, client_info->cb_param); } /* process DMA Immediate completion data events */ static void gpi_process_imed_data_event(struct gpii_chan *gpii_chan, struct immediate_data_event *imed_event) { struct gpii *gpii = gpii_chan->gpii; struct gpi_ring *ch_ring = &gpii_chan->ch_ring; struct virt_dma_desc *vd; struct gpi_desc *gpi_desc; void *tre = ch_ring->base + (ch_ring->el_size * imed_event->tre_index); struct msm_gpi_dma_async_tx_cb_param *tx_cb_param; unsigned long flags; /* * If channel not active don't process event but let * client know pending event is available */ if (gpii_chan->pm_state != ACTIVE_STATE) { GPII_ERR(gpii, gpii_chan->chid, "skipping processing event because ch @ %s state\n", TO_GPI_PM_STR(gpii_chan->pm_state)); gpi_generate_cb_event(gpii_chan, MSM_GPI_QUP_PENDING_EVENT, __LINE__); return; } spin_lock_irqsave(&gpii_chan->vc.lock, flags); vd = vchan_next_desc(&gpii_chan->vc); if (!vd) { struct gpi_ere *gpi_ere; struct msm_gpi_tre *gpi_tre; spin_unlock_irqrestore(&gpii_chan->vc.lock, flags); GPII_ERR(gpii, gpii_chan->chid, "event without a pending descriptor!\n"); gpi_ere = (struct gpi_ere *)imed_event; GPII_ERR(gpii, gpii_chan->chid, "Event: %08x %08x %08x %08x\n", gpi_ere->dword[0], gpi_ere->dword[1], gpi_ere->dword[2], gpi_ere->dword[3]); gpi_tre = tre; GPII_ERR(gpii, gpii_chan->chid, "Pending TRE: %08x %08x %08x %08x\n", gpi_tre->dword[0], gpi_tre->dword[1], gpi_tre->dword[2], gpi_tre->dword[3]); gpi_generate_cb_event(gpii_chan, MSM_GPI_QUP_EOT_DESC_MISMATCH, __LINE__); return; } gpi_desc = to_gpi_desc(vd); /* Event TR RP gen. don't match descriptor TR */ if (gpi_desc->wp != tre) { spin_unlock_irqrestore(&gpii_chan->vc.lock, flags); GPII_ERR(gpii, gpii_chan->chid, "EOT/EOB received for wrong TRE 0x%0llx != 0x%0llx\n", to_physical(ch_ring, gpi_desc->wp), to_physical(ch_ring, tre)); gpi_generate_cb_event(gpii_chan, MSM_GPI_QUP_EOT_DESC_MISMATCH, __LINE__); return; } list_del(&vd->node); spin_unlock_irqrestore(&gpii_chan->vc.lock, flags); /* * RP pointed by Event is to last TRE processed, * we need to update ring rp to tre + 1 */ tre += ch_ring->el_size; if (tre >= (ch_ring->base + ch_ring->len)) tre = ch_ring->base; ch_ring->rp = tre; /* make sure rp updates are immediately visible to all cores */ smp_wmb(); tx_cb_param = vd->tx.callback_param; if (vd->tx.callback && tx_cb_param) { struct msm_gpi_tre *imed_tre = &tx_cb_param->imed_tre; GPII_VERB(gpii, gpii_chan->chid, "cb_length:%u compl_code:0x%x status:0x%x\n", imed_event->length, imed_event->code, imed_event->status); /* Update immediate data if any from event */ *imed_tre = *((struct msm_gpi_tre *)imed_event); tx_cb_param->length = imed_event->length; tx_cb_param->completion_code = imed_event->code; tx_cb_param->status = imed_event->status; vd->tx.callback(tx_cb_param); } kfree(gpi_desc); } /* processing transfer completion events */ static void gpi_process_xfer_compl_event(struct gpii_chan *gpii_chan, struct xfer_compl_event *compl_event) { struct gpii *gpii = gpii_chan->gpii; struct gpi_ring *ch_ring = &gpii_chan->ch_ring; void *ev_rp = to_virtual(ch_ring, compl_event->ptr); struct virt_dma_desc *vd; struct msm_gpi_dma_async_tx_cb_param *tx_cb_param; struct gpi_desc *gpi_desc; unsigned long flags; /* only process events on active channel */ if (unlikely(gpii_chan->pm_state != ACTIVE_STATE)) { GPII_ERR(gpii, gpii_chan->chid, "skipping processing event because ch @ %s state\n", TO_GPI_PM_STR(gpii_chan->pm_state)); gpi_generate_cb_event(gpii_chan, MSM_GPI_QUP_PENDING_EVENT, __LINE__); return; } spin_lock_irqsave(&gpii_chan->vc.lock, flags); vd = vchan_next_desc(&gpii_chan->vc); if (!vd) { struct gpi_ere *gpi_ere; spin_unlock_irqrestore(&gpii_chan->vc.lock, flags); GPII_ERR(gpii, gpii_chan->chid, "Event without a pending descriptor!\n"); gpi_ere = (struct gpi_ere *)compl_event; GPII_ERR(gpii, gpii_chan->chid, "Event: %08x %08x %08x %08x\n", gpi_ere->dword[0], gpi_ere->dword[1], gpi_ere->dword[2], gpi_ere->dword[3]); gpi_generate_cb_event(gpii_chan, MSM_GPI_QUP_EOT_DESC_MISMATCH, __LINE__); return; } gpi_desc = to_gpi_desc(vd); /* TRE Event generated didn't match descriptor's TRE */ if (gpi_desc->wp != ev_rp) { spin_unlock_irqrestore(&gpii_chan->vc.lock, flags); GPII_ERR(gpii, gpii_chan->chid, "EOT\EOB received for wrong TRE 0x%0llx != 0x%0llx\n", to_physical(ch_ring, gpi_desc->wp), to_physical(ch_ring, ev_rp)); gpi_generate_cb_event(gpii_chan, MSM_GPI_QUP_EOT_DESC_MISMATCH, __LINE__); return; } list_del(&vd->node); spin_unlock_irqrestore(&gpii_chan->vc.lock, flags); /* * RP pointed by Event is to last TRE processed, * we need to update ring rp to ev_rp + 1 */ ev_rp += ch_ring->el_size; if (ev_rp >= (ch_ring->base + ch_ring->len)) ev_rp = ch_ring->base; ch_ring->rp = ev_rp; /* update must be visible to other cores */ smp_wmb(); tx_cb_param = vd->tx.callback_param; if (vd->tx.callback && tx_cb_param) { GPII_VERB(gpii, gpii_chan->chid, "cb_length:%u compl_code:0x%x status:0x%x\n", compl_event->length, compl_event->code, compl_event->status); tx_cb_param->length = compl_event->length; tx_cb_param->completion_code = compl_event->code; tx_cb_param->status = compl_event->status; vd->tx.callback(tx_cb_param); } kfree(gpi_desc); } /* process all events */ static void gpi_process_events(struct gpii *gpii) { struct gpi_ring *ev_ring = &gpii->ev_ring; phys_addr_t cntxt_rp, local_rp; void *rp; union gpi_event *gpi_event; struct gpii_chan *gpii_chan; u32 chid, type; cntxt_rp = gpi_read_reg(gpii, gpii->ev_ring_rp_lsb_reg); rp = to_virtual(ev_ring, cntxt_rp); local_rp = to_physical(ev_ring, ev_ring->rp); GPII_VERB(gpii, GPI_DBG_COMMON, "cntxt_rp:%pa local_rp:%pa\n", &cntxt_rp, &local_rp); do { while (rp != ev_ring->rp) { gpi_event = ev_ring->rp; chid = gpi_event->xfer_compl_event.chid; type = gpi_event->xfer_compl_event.type; GPII_VERB(gpii, GPI_DBG_COMMON, "chid:%u type:0x%x %08x %08x %08x %08x\n", chid, type, gpi_event->gpi_ere.dword[0], gpi_event->gpi_ere.dword[1], gpi_event->gpi_ere.dword[2], gpi_event->gpi_ere.dword[3]); switch (type) { case XFER_COMPLETE_EV_TYPE: gpii_chan = &gpii->gpii_chan[chid]; gpi_process_xfer_compl_event(gpii_chan, &gpi_event->xfer_compl_event); break; case STALE_EV_TYPE: GPII_VERB(gpii, GPI_DBG_COMMON, "stale event, not processing\n"); break; case IMMEDIATE_DATA_EV_TYPE: gpii_chan = &gpii->gpii_chan[chid]; gpi_process_imed_data_event(gpii_chan, &gpi_event->immediate_data_event); break; case QUP_NOTIF_EV_TYPE: gpii_chan = &gpii->gpii_chan[chid]; gpi_process_qup_notif_event(gpii_chan, &gpi_event->qup_notif_event); break; default: GPII_VERB(gpii, GPI_DBG_COMMON, "not supported event type:0x%x\n", type); } gpi_ring_recycle_ev_element(ev_ring); } gpi_write_ev_db(gpii, ev_ring, ev_ring->wp); /* clear pending IEOB events */ gpi_write_reg(gpii, gpii->ieob_clr_reg, BIT(0)); cntxt_rp = gpi_read_reg(gpii, gpii->ev_ring_rp_lsb_reg); rp = to_virtual(ev_ring, cntxt_rp); } while (rp != ev_ring->rp); GPII_VERB(gpii, GPI_DBG_COMMON, "exit: c_rp:%pa\n", &cntxt_rp); } /* processing events using tasklet */ static void gpi_ev_tasklet(unsigned long data) { struct gpii *gpii = (struct gpii *)data; GPII_VERB(gpii, GPI_DBG_COMMON, "enter\n"); read_lock_bh(&gpii->pm_lock); if (!REG_ACCESS_VALID(gpii->pm_state)) { read_unlock_bh(&gpii->pm_lock); GPII_ERR(gpii, GPI_DBG_COMMON, "not processing any events, pm_state:%s\n", TO_GPI_PM_STR(gpii->pm_state)); return; } /* process the events */ gpi_process_events(gpii); /* enable IEOB, switching back to interrupts */ gpi_config_interrupts(gpii, MASK_IEOB_SETTINGS, 1); read_unlock_bh(&gpii->pm_lock); GPII_VERB(gpii, GPI_DBG_COMMON, "exit\n"); } /* marks all pending events for the channel as stale */ void gpi_mark_stale_events(struct gpii_chan *gpii_chan) { struct gpii *gpii = gpii_chan->gpii; struct gpi_ring *ev_ring = &gpii->ev_ring; void *ev_rp; u32 cntxt_rp, local_rp; GPII_INFO(gpii, gpii_chan->chid, "Enter\n"); cntxt_rp = gpi_read_reg(gpii, gpii->ev_ring_rp_lsb_reg); ev_rp = ev_ring->rp; local_rp = (u32)to_physical(ev_ring, ev_rp); while (local_rp != cntxt_rp) { union gpi_event *gpi_event = ev_rp; u32 chid = gpi_event->xfer_compl_event.chid; if (chid == gpii_chan->chid) gpi_event->xfer_compl_event.type = STALE_EV_TYPE; ev_rp += ev_ring->el_size; if (ev_rp >= (ev_ring->base + ev_ring->len)) ev_rp = ev_ring->base; cntxt_rp = gpi_read_reg(gpii, gpii->ev_ring_rp_lsb_reg); local_rp = (u32)to_physical(ev_ring, ev_rp); } } /* reset sw state and issue channel reset or de-alloc */ static int gpi_reset_chan(struct gpii_chan *gpii_chan, enum gpi_cmd gpi_cmd) { struct gpii *gpii = gpii_chan->gpii; struct gpi_ring *ch_ring = &gpii_chan->ch_ring; unsigned long flags; LIST_HEAD(list); int ret; GPII_INFO(gpii, gpii_chan->chid, "Enter\n"); ret = gpi_send_cmd(gpii, gpii_chan, gpi_cmd); if (ret) { GPII_ERR(gpii, gpii_chan->chid, "Error with cmd:%s ret:%d\n", TO_GPI_CMD_STR(gpi_cmd), ret); return ret; } /* initialize the local ring ptrs */ ch_ring->rp = ch_ring->base; ch_ring->wp = ch_ring->base; /* visible to other cores */ smp_wmb(); /* check event ring for any stale events */ write_lock_irq(&gpii->pm_lock); gpi_mark_stale_events(gpii_chan); /* remove all async descriptors */ spin_lock_irqsave(&gpii_chan->vc.lock, flags); vchan_get_all_descriptors(&gpii_chan->vc, &list); spin_unlock_irqrestore(&gpii_chan->vc.lock, flags); write_unlock_irq(&gpii->pm_lock); vchan_dma_desc_free_list(&gpii_chan->vc, &list); return 0; } static int gpi_start_chan(struct gpii_chan *gpii_chan) { struct gpii *gpii = gpii_chan->gpii; int ret; GPII_INFO(gpii, gpii_chan->chid, "Enter\n"); ret = gpi_send_cmd(gpii, gpii_chan, GPI_CH_CMD_START); if (ret) { GPII_ERR(gpii, gpii_chan->chid, "Error with cmd:%s ret:%d\n", TO_GPI_CMD_STR(GPI_CH_CMD_START), ret); return ret; } /* gpii CH is active now */ write_lock_irq(&gpii->pm_lock); gpii_chan->pm_state = ACTIVE_STATE; write_unlock_irq(&gpii->pm_lock); return 0; } /* allocate and configure the transfer channel */ static int gpi_alloc_chan(struct gpii_chan *gpii_chan, bool send_alloc_cmd) { struct gpii *gpii = gpii_chan->gpii; struct gpi_ring *ring = &gpii_chan->ch_ring; int i; int ret; struct { void *base; int offset; u32 val; } ch_reg[] = { { gpii_chan->ch_cntxt_base_reg, CNTXT_0_CONFIG, GPI_GPII_n_CH_k_CNTXT_0(ring->el_size, 0, gpii_chan->dir, GPI_CHTYPE_PROTO_GPI), }, { gpii_chan->ch_cntxt_base_reg, CNTXT_1_R_LENGTH, ring->len, }, { gpii_chan->ch_cntxt_base_reg, CNTXT_2_RING_BASE_LSB, (u32)ring->phys_addr, }, { gpii_chan->ch_cntxt_base_reg, CNTXT_3_RING_BASE_MSB, (u32)(ring->phys_addr >> 32), }, { /* program MSB of DB register with ring base */ gpii_chan->ch_cntxt_db_reg, CNTXT_5_RING_RP_MSB - CNTXT_4_RING_RP_LSB, (u32)(ring->phys_addr >> 32), }, { gpii->regs, GPI_GPII_n_CH_k_SCRATCH_0_OFFS(gpii->gpii_id, gpii_chan->chid), GPI_GPII_n_CH_K_SCRATCH_0(!gpii_chan->chid, gpii_chan->protocol, gpii_chan->seid), }, { gpii->regs, GPI_GPII_n_CH_k_SCRATCH_1_OFFS(gpii->gpii_id, gpii_chan->chid), 0, }, { gpii->regs, GPI_GPII_n_CH_k_SCRATCH_2_OFFS(gpii->gpii_id, gpii_chan->chid), 0, }, { gpii->regs, GPI_GPII_n_CH_k_SCRATCH_3_OFFS(gpii->gpii_id, gpii_chan->chid), 0, }, { gpii->regs, GPI_GPII_n_CH_k_QOS_OFFS(gpii->gpii_id, gpii_chan->chid), 1, }, { NULL }, }; GPII_INFO(gpii, gpii_chan->chid, "Enter\n"); if (send_alloc_cmd) { ret = gpi_send_cmd(gpii, gpii_chan, GPI_CH_CMD_ALLOCATE); if (ret) { GPII_ERR(gpii, gpii_chan->chid, "Error with cmd:%s ret:%d\n", TO_GPI_CMD_STR(GPI_CH_CMD_ALLOCATE), ret); return ret; } } /* program channel cntxt registers */ for (i = 0; ch_reg[i].base; i++) gpi_write_reg(gpii, ch_reg[i].base + ch_reg[i].offset, ch_reg[i].val); /* flush all the writes */ wmb(); return 0; } /* allocate and configure event ring */ static int gpi_alloc_ev_chan(struct gpii *gpii) { struct gpi_ring *ring = &gpii->ev_ring; int i; int ret; struct { void *base; int offset; u32 val; } ev_reg[] = { { gpii->ev_cntxt_base_reg, CNTXT_0_CONFIG, GPI_GPII_n_EV_CH_k_CNTXT_0(ring->el_size, GPI_INTTYPE_IRQ, GPI_CHTYPE_GPI_EV), }, { gpii->ev_cntxt_base_reg, CNTXT_1_R_LENGTH, ring->len, }, { gpii->ev_cntxt_base_reg, CNTXT_2_RING_BASE_LSB, (u32)ring->phys_addr, }, { gpii->ev_cntxt_base_reg, CNTXT_3_RING_BASE_MSB, (u32)(ring->phys_addr >> 32), }, { /* program db msg with ring base msb */ gpii->ev_cntxt_db_reg, CNTXT_5_RING_RP_MSB - CNTXT_4_RING_RP_LSB, (u32)(ring->phys_addr >> 32), }, { gpii->ev_cntxt_base_reg, CNTXT_8_RING_INT_MOD, 0, }, { gpii->ev_cntxt_base_reg, CNTXT_10_RING_MSI_LSB, 0, }, { gpii->ev_cntxt_base_reg, CNTXT_11_RING_MSI_MSB, 0, }, { gpii->ev_cntxt_base_reg, CNTXT_8_RING_INT_MOD, 0, }, { gpii->ev_cntxt_base_reg, CNTXT_12_RING_RP_UPDATE_LSB, 0, }, { gpii->ev_cntxt_base_reg, CNTXT_13_RING_RP_UPDATE_MSB, 0, }, { NULL }, }; GPII_INFO(gpii, GPI_DBG_COMMON, "enter\n"); ret = gpi_send_cmd(gpii, NULL, GPI_EV_CMD_ALLOCATE); if (ret) { GPII_ERR(gpii, GPI_DBG_COMMON, "error with cmd:%s ret:%d\n", TO_GPI_CMD_STR(GPI_EV_CMD_ALLOCATE), ret); return ret; } /* program event context */ for (i = 0; ev_reg[i].base; i++) gpi_write_reg(gpii, ev_reg[i].base + ev_reg[i].offset, ev_reg[i].val); /* add events to ring */ ring->wp = (ring->base + ring->len - ring->el_size); /* flush all the writes */ wmb(); /* gpii is active now */ write_lock_irq(&gpii->pm_lock); gpii->pm_state = ACTIVE_STATE; write_unlock_irq(&gpii->pm_lock); gpi_write_ev_db(gpii, ring, ring->wp); return 0; } /* calculate # of ERE/TRE available to queue */ static int gpi_ring_num_elements_avail(const struct gpi_ring * const ring) { int elements = 0; if (ring->wp < ring->rp) elements = ((ring->rp - ring->wp) / ring->el_size) - 1; else { elements = (ring->rp - ring->base) / ring->el_size; elements += ((ring->base + ring->len - ring->wp) / ring->el_size) - 1; } return elements; } static int gpi_ring_add_element(struct gpi_ring *ring, void **wp) { if (gpi_ring_num_elements_avail(ring) <= 0) return -ENOMEM; *wp = ring->wp; ring->wp += ring->el_size; if (ring->wp >= (ring->base + ring->len)) ring->wp = ring->base; /* visible to other cores */ smp_wmb(); return 0; } static void gpi_ring_recycle_ev_element(struct gpi_ring *ring) { /* Update the WP */ ring->wp += ring->el_size; if (ring->wp >= (ring->base + ring->len)) ring->wp = ring->base; /* Update the RP */ ring->rp += ring->el_size; if (ring->rp >= (ring->base + ring->len)) ring->rp = ring->base; /* visible to other cores */ smp_wmb(); } static void gpi_free_ring(struct gpi_ring *ring, struct gpii *gpii) { dma_free_coherent(gpii->gpi_dev->dev, ring->alloc_size, ring->pre_aligned, ring->dma_handle); memset(ring, 0, sizeof(*ring)); } /* allocate memory for transfer and event rings */ static int gpi_alloc_ring(struct gpi_ring *ring, u32 elements, u32 el_size, struct gpii *gpii) { u64 len = elements * el_size; int bit; /* ring len must be power of 2 */ bit = find_last_bit((unsigned long *)&len, 32); if (((1 << bit) - 1) & len) bit++; len = 1 << bit; ring->alloc_size = (len + (len - 1)); GPII_INFO(gpii, GPI_DBG_COMMON, "#el:%u el_size:%u len:%u actual_len:%llu alloc_size:%lu\n", elements, el_size, (elements * el_size), len, ring->alloc_size); ring->pre_aligned = dma_alloc_coherent(gpii->gpi_dev->dev, ring->alloc_size, &ring->dma_handle, GFP_KERNEL); if (!ring->pre_aligned) { GPII_CRITIC(gpii, GPI_DBG_COMMON, "could not alloc size:%lu mem for ring\n", ring->alloc_size); return -ENOMEM; } /* align the physical mem */ ring->phys_addr = (ring->dma_handle + (len - 1)) & ~(len - 1); ring->base = ring->pre_aligned + (ring->phys_addr - ring->dma_handle); ring->rp = ring->base; ring->wp = ring->base; ring->len = len; ring->el_size = el_size; ring->elements = ring->len / ring->el_size; memset(ring->base, 0, ring->len); ring->configured = true; /* update to other cores */ smp_wmb(); GPII_INFO(gpii, GPI_DBG_COMMON, "phy_pre:0x%0llx phy_alig:0x%0llx len:%u el_size:%u elements:%u\n", ring->dma_handle, ring->phys_addr, ring->len, ring->el_size, ring->elements); return 0; } /* copy tre into transfer ring */ static void gpi_queue_xfer(struct gpii *gpii, struct gpii_chan *gpii_chan, struct msm_gpi_tre *gpi_tre, void **wp) { struct msm_gpi_tre *ch_tre; int ret; /* get next tre location we can copy */ ret = gpi_ring_add_element(&gpii_chan->ch_ring, (void **)&ch_tre); if (unlikely(ret)) { GPII_CRITIC(gpii, gpii_chan->chid, "Error adding ring element to xfer ring\n"); return; } /* copy the tre info */ memcpy(ch_tre, gpi_tre, sizeof(*ch_tre)); *wp = ch_tre; } /* reset and restart transfer channel */ int gpi_terminate_all(struct dma_chan *chan) { struct gpii_chan *gpii_chan = to_gpii_chan(chan); struct gpii *gpii = gpii_chan->gpii; int schid, echid, i; int ret = 0; GPII_INFO(gpii, gpii_chan->chid, "Enter\n"); mutex_lock(&gpii->ctrl_lock); /* * treat both channels as a group if its protocol is not UART * STOP, RESET, or START needs to be in lockstep */ schid = (gpii->protocol == SE_PROTOCOL_UART) ? gpii_chan->chid : 0; echid = (gpii->protocol == SE_PROTOCOL_UART) ? schid + 1 : MAX_CHANNELS_PER_GPII; /* stop the channel */ for (i = schid; i < echid; i++) { gpii_chan = &gpii->gpii_chan[i]; /* disable ch state so no more TRE processing */ write_lock_irq(&gpii->pm_lock); gpii_chan->pm_state = PREPARE_TERMINATE; write_unlock_irq(&gpii->pm_lock); /* send command to Stop the channel */ ret = gpi_send_cmd(gpii, gpii_chan, GPI_CH_CMD_STOP); if (ret) GPII_ERR(gpii, gpii_chan->chid, "Error Stopping Channel:%d resetting anyway\n", ret); } /* reset the channels (clears any pending tre) */ for (i = schid; i < echid; i++) { gpii_chan = &gpii->gpii_chan[i]; ret = gpi_reset_chan(gpii_chan, GPI_CH_CMD_RESET); if (ret) { GPII_ERR(gpii, gpii_chan->chid, "Error resetting channel ret:%d\n", ret); goto terminate_exit; } /* reprogram channel CNTXT */ ret = gpi_alloc_chan(gpii_chan, false); if (ret) { GPII_ERR(gpii, gpii_chan->chid, "Error alloc_channel ret:%d\n", ret); goto terminate_exit; } } /* restart the channels */ for (i = schid; i < echid; i++) { gpii_chan = &gpii->gpii_chan[i]; ret = gpi_start_chan(gpii_chan); if (ret) { GPII_ERR(gpii, gpii_chan->chid, "Error Starting Channel ret:%d\n", ret); goto terminate_exit; } } terminate_exit: mutex_unlock(&gpii->ctrl_lock); return ret; } /* pause dma transfer for all channels */ static int gpi_pause(struct dma_chan *chan) { struct gpii_chan *gpii_chan = to_gpii_chan(chan); struct gpii *gpii = gpii_chan->gpii; int i, ret; GPII_INFO(gpii, gpii_chan->chid, "Enter\n"); mutex_lock(&gpii->ctrl_lock); /* * pause/resume are per gpii not per channel, so * client needs to call pause only once */ if (gpii->pm_state == PAUSE_STATE) { GPII_INFO(gpii, gpii_chan->chid, "channel is already paused\n"); mutex_unlock(&gpii->ctrl_lock); return 0; } /* send stop command to stop the channels */ for (i = 0; i < MAX_CHANNELS_PER_GPII; i++) { ret = gpi_send_cmd(gpii, &gpii->gpii_chan[i], GPI_CH_CMD_STOP); if (ret) { GPII_ERR(gpii, gpii->gpii_chan[i].chid, "Error stopping chan, ret:%d\n", ret); mutex_unlock(&gpii->ctrl_lock); return ret; } } disable_irq(gpii->irq); /* Wait for threads to complete out */ tasklet_kill(&gpii->ev_task); write_lock_irq(&gpii->pm_lock); gpii->pm_state = PAUSE_STATE; write_unlock_irq(&gpii->pm_lock); mutex_unlock(&gpii->ctrl_lock); return 0; } /* resume dma transfer */ static int gpi_resume(struct dma_chan *chan) { struct gpii_chan *gpii_chan = to_gpii_chan(chan); struct gpii *gpii = gpii_chan->gpii; int i; int ret; GPII_INFO(gpii, gpii_chan->chid, "enter\n"); mutex_lock(&gpii->ctrl_lock); if (gpii->pm_state == ACTIVE_STATE) { GPII_INFO(gpii, gpii_chan->chid, "channel is already active\n"); mutex_unlock(&gpii->ctrl_lock); return 0; } enable_irq(gpii->irq); /* send start command to start the channels */ for (i = 0; i < MAX_CHANNELS_PER_GPII; i++) { ret = gpi_send_cmd(gpii, &gpii->gpii_chan[i], GPI_CH_CMD_START); if (ret) { GPII_ERR(gpii, gpii->gpii_chan[i].chid, "Erro starting chan, ret:%d\n", ret); mutex_unlock(&gpii->ctrl_lock); return ret; } } write_lock_irq(&gpii->pm_lock); gpii->pm_state = ACTIVE_STATE; write_unlock_irq(&gpii->pm_lock); mutex_unlock(&gpii->ctrl_lock); return 0; } void gpi_desc_free(struct virt_dma_desc *vd) { struct gpi_desc *gpi_desc = to_gpi_desc(vd); kfree(gpi_desc); } /* copy tre into transfer ring */ struct dma_async_tx_descriptor *gpi_prep_slave_sg(struct dma_chan *chan, struct scatterlist *sgl, unsigned int sg_len, enum dma_transfer_direction direction, unsigned long flags, void *context) { struct gpii_chan *gpii_chan = to_gpii_chan(chan); struct gpii *gpii = gpii_chan->gpii; u32 nr; u32 nr_req = 0; int i, j; struct scatterlist *sg; struct gpi_ring *ch_ring = &gpii_chan->ch_ring; void *tre, *wp = NULL; const gfp_t gfp = GFP_ATOMIC; struct gpi_desc *gpi_desc; GPII_VERB(gpii, gpii_chan->chid, "enter\n"); if (!is_slave_direction(direction)) { GPII_ERR(gpii, gpii_chan->chid, "invalid dma direction: %d\n", direction); return NULL; } /* calculate # of elements required & available */ nr = gpi_ring_num_elements_avail(ch_ring); for_each_sg(sgl, sg, sg_len, i) { GPII_VERB(gpii, gpii_chan->chid, "%d of %u len:%u\n", i, sg_len, sg->length); nr_req += (sg->length / ch_ring->el_size); } GPII_VERB(gpii, gpii_chan->chid, "el avail:%u req:%u\n", nr, nr_req); if (nr < nr_req) { GPII_ERR(gpii, gpii_chan->chid, "not enough space in ring, avail:%u required:%u\n", nr, nr_req); return NULL; } gpi_desc = kzalloc(sizeof(*gpi_desc), gfp); if (!gpi_desc) { GPII_ERR(gpii, gpii_chan->chid, "out of memory for descriptor\n"); return NULL; } /* copy each tre into transfer ring */ for_each_sg(sgl, sg, sg_len, i) for (j = 0, tre = sg_virt(sg); j < sg->length; j += ch_ring->el_size, tre += ch_ring->el_size) gpi_queue_xfer(gpii, gpii_chan, tre, &wp); /* set up the descriptor */ gpi_desc->db = ch_ring->wp; gpi_desc->wp = wp; gpi_desc->gpii_chan = gpii_chan; GPII_VERB(gpii, gpii_chan->chid, "exit wp:0x%0llx rp:0x%0llx\n", to_physical(ch_ring, ch_ring->wp), to_physical(ch_ring, ch_ring->rp)); return vchan_tx_prep(&gpii_chan->vc, &gpi_desc->vd, flags); } /* rings transfer ring db to being transfer */ static void gpi_issue_pending(struct dma_chan *chan) { struct gpii_chan *gpii_chan = to_gpii_chan(chan); struct gpii *gpii = gpii_chan->gpii; unsigned long flags, pm_lock_flags; struct virt_dma_desc *vd = NULL; struct gpi_desc *gpi_desc; GPII_VERB(gpii, gpii_chan->chid, "Enter\n"); read_lock_irqsave(&gpii->pm_lock, pm_lock_flags); /* move all submitted discriptors to issued list */ spin_lock_irqsave(&gpii_chan->vc.lock, flags); if (vchan_issue_pending(&gpii_chan->vc)) vd = list_last_entry(&gpii_chan->vc.desc_issued, struct virt_dma_desc, node); spin_unlock_irqrestore(&gpii_chan->vc.lock, flags); /* nothing to do list is empty */ if (!vd) { read_unlock_irqrestore(&gpii->pm_lock, pm_lock_flags); GPII_VERB(gpii, gpii_chan->chid, "no descriptors submitted\n"); return; } gpi_desc = to_gpi_desc(vd); gpi_write_ch_db(gpii_chan, &gpii_chan->ch_ring, gpi_desc->db); read_unlock_irqrestore(&gpii->pm_lock, pm_lock_flags); } /* configure or issue async command */ static int gpi_config(struct dma_chan *chan, struct dma_slave_config *config) { struct gpii_chan *gpii_chan = to_gpii_chan(chan); struct gpii *gpii = gpii_chan->gpii; struct msm_gpi_ctrl *gpi_ctrl = chan->private; const int ev_factor = gpii->gpi_dev->ev_factor; u32 elements; int i = 0; int ret = 0; GPII_INFO(gpii, gpii_chan->chid, "enter\n"); if (!gpi_ctrl) { GPII_ERR(gpii, gpii_chan->chid, "no config ctrl data provided"); return -EINVAL; } mutex_lock(&gpii->ctrl_lock); switch (gpi_ctrl->cmd) { case MSM_GPI_INIT: GPII_INFO(gpii, gpii_chan->chid, "cmd: msm_gpi_init\n"); gpii_chan->client_info.callback = gpi_ctrl->init.callback; gpii_chan->client_info.cb_param = gpi_ctrl->init.cb_param; gpii_chan->pm_state = CONFIG_STATE; /* check if both channels are configured before continue */ for (i = 0; i < MAX_CHANNELS_PER_GPII; i++) if (gpii->gpii_chan[i].pm_state != CONFIG_STATE) goto exit_gpi_init; /* configure to highest priority from two channels */ gpii->ev_priority = min(gpii->gpii_chan[0].priority, gpii->gpii_chan[1].priority); /* protocol must be same for both channels */ if (gpii->gpii_chan[0].protocol != gpii->gpii_chan[1].protocol) { GPII_ERR(gpii, gpii_chan->chid, "protocol did not match protocol %u != %u\n", gpii->gpii_chan[0].protocol, gpii->gpii_chan[1].protocol); ret = -EINVAL; goto exit_gpi_init; } gpii->protocol = gpii_chan->protocol; /* allocate memory for event ring */ elements = max(gpii->gpii_chan[0].req_tres, gpii->gpii_chan[1].req_tres); ret = gpi_alloc_ring(&gpii->ev_ring, elements << ev_factor, sizeof(union gpi_event), gpii); if (ret) { GPII_ERR(gpii, gpii_chan->chid, "error allocating mem for ev ring\n"); goto exit_gpi_init; } /* configure interrupts */ write_lock_irq(&gpii->pm_lock); gpii->pm_state = PREPARE_HARDWARE; write_unlock_irq(&gpii->pm_lock); ret = gpi_config_interrupts(gpii, DEFAULT_IRQ_SETTINGS, 0); if (ret) { GPII_ERR(gpii, gpii_chan->chid, "error config. interrupts, ret:%d\n", ret); goto error_config_int; } /* allocate event rings */ ret = gpi_alloc_ev_chan(gpii); if (ret) { GPII_ERR(gpii, gpii_chan->chid, "error alloc_ev_chan:%d\n", ret); goto error_alloc_ev_ring; } /* Allocate all channels */ for (i = 0; i < MAX_CHANNELS_PER_GPII; i++) { ret = gpi_alloc_chan(&gpii->gpii_chan[i], true); if (ret) { GPII_ERR(gpii, gpii->gpii_chan[i].chid, "Error allocating chan:%d\n", ret); goto error_alloc_chan; } } /* start channels */ for (i = 0; i < MAX_CHANNELS_PER_GPII; i++) { ret = gpi_start_chan(&gpii->gpii_chan[i]); if (ret) { GPII_ERR(gpii, gpii->gpii_chan[i].chid, "Error start chan:%d\n", ret); goto error_start_chan; } } break; case MSM_GPI_CMD_UART_SW_STALE: GPII_INFO(gpii, gpii_chan->chid, "sending UART SW STALE cmd\n"); ret = gpi_send_cmd(gpii, gpii_chan, GPI_CH_CMD_UART_SW_STALE); break; case MSM_GPI_CMD_UART_RFR_READY: GPII_INFO(gpii, gpii_chan->chid, "sending UART RFR READY cmd\n"); ret = gpi_send_cmd(gpii, gpii_chan, GPI_CH_CMD_UART_RFR_READY); break; case MSM_GPI_CMD_UART_RFR_NOT_READY: GPII_INFO(gpii, gpii_chan->chid, "sending UART RFR READY NOT READY cmd\n"); ret = gpi_send_cmd(gpii, gpii_chan, GPI_CH_CMD_UART_RFR_NOT_READY); break; default: GPII_ERR(gpii, gpii_chan->chid, "unsupported ctrl cmd:%d\n", gpi_ctrl->cmd); ret = -EINVAL; } mutex_unlock(&gpii->ctrl_lock); return ret; error_start_chan: for (i = i - 1; i >= 0; i++) { gpi_send_cmd(gpii, gpii_chan, GPI_CH_CMD_STOP); gpi_send_cmd(gpii, gpii_chan, GPI_CH_CMD_RESET); } i = 2; error_alloc_chan: for (i = i - 1; i >= 0; i--) gpi_reset_chan(gpii_chan, GPI_CH_CMD_DE_ALLOC); error_alloc_ev_ring: gpi_disable_interrupts(gpii); error_config_int: gpi_free_ring(&gpii->ev_ring, gpii); exit_gpi_init: mutex_unlock(&gpii->ctrl_lock); return ret; } /* release all channel resources */ static void gpi_free_chan_resources(struct dma_chan *chan) { struct gpii_chan *gpii_chan = to_gpii_chan(chan); struct gpii *gpii = gpii_chan->gpii; enum gpi_pm_state cur_state; int ret, i; GPII_INFO(gpii, gpii_chan->chid, "enter\n"); mutex_lock(&gpii->ctrl_lock); cur_state = gpii_chan->pm_state; /* disable ch state so no more TRE processing for this channel */ write_lock_irq(&gpii->pm_lock); gpii_chan->pm_state = PREPARE_TERMINATE; write_unlock_irq(&gpii->pm_lock); /* attemp to do graceful hardware shutdown */ if (cur_state == ACTIVE_STATE) { ret = gpi_send_cmd(gpii, gpii_chan, GPI_CH_CMD_STOP); if (ret) GPII_ERR(gpii, gpii_chan->chid, "error stopping channel:%d\n", ret); ret = gpi_send_cmd(gpii, gpii_chan, GPI_CH_CMD_RESET); if (ret) GPII_ERR(gpii, gpii_chan->chid, "error resetting channel:%d\n", ret); gpi_reset_chan(gpii_chan, GPI_CH_CMD_DE_ALLOC); } /* free all allocated memory */ gpi_free_ring(&gpii_chan->ch_ring, gpii); vchan_free_chan_resources(&gpii_chan->vc); write_lock_irq(&gpii->pm_lock); gpii_chan->pm_state = DISABLE_STATE; write_unlock_irq(&gpii->pm_lock); /* if other rings are still active exit */ for (i = 0; i < MAX_CHANNELS_PER_GPII; i++) if (gpii->gpii_chan[i].ch_ring.configured) goto exit_free; GPII_INFO(gpii, gpii_chan->chid, "disabling gpii\n"); /* deallocate EV Ring */ cur_state = gpii->pm_state; write_lock_irq(&gpii->pm_lock); gpii->pm_state = PREPARE_TERMINATE; write_unlock_irq(&gpii->pm_lock); /* wait for threads to complete out */ tasklet_kill(&gpii->ev_task); /* send command to de allocate event ring */ if (cur_state == ACTIVE_STATE) gpi_send_cmd(gpii, NULL, GPI_EV_CMD_DEALLOC); gpi_free_ring(&gpii->ev_ring, gpii); /* disable interrupts */ if (cur_state == ACTIVE_STATE) gpi_disable_interrupts(gpii); /* set final state to disable */ write_lock_irq(&gpii->pm_lock); gpii->pm_state = DISABLE_STATE; write_unlock_irq(&gpii->pm_lock); exit_free: mutex_unlock(&gpii->ctrl_lock); } /* allocate channel resources */ static int gpi_alloc_chan_resources(struct dma_chan *chan) { struct gpii_chan *gpii_chan = to_gpii_chan(chan); struct gpii *gpii = gpii_chan->gpii; int ret; GPII_INFO(gpii, gpii_chan->chid, "enter\n"); mutex_lock(&gpii->ctrl_lock); /* allocate memory for transfer ring */ ret = gpi_alloc_ring(&gpii_chan->ch_ring, gpii_chan->req_tres, sizeof(struct msm_gpi_tre), gpii); if (ret) { GPII_ERR(gpii, gpii_chan->chid, "error allocating xfer ring, ret:%d\n", ret); goto xfer_alloc_err; } mutex_unlock(&gpii->ctrl_lock); return 0; xfer_alloc_err: mutex_unlock(&gpii->ctrl_lock); return ret; } static int gpi_find_avail_gpii(struct gpi_dev *gpi_dev, u32 seid) { int gpii; struct gpii_chan *tx_chan, *rx_chan; /* check if same seid is already configured for another chid */ for (gpii = 0; gpii < gpi_dev->max_gpii; gpii++) { if (!((1 << gpii) & gpi_dev->gpii_mask)) continue; tx_chan = &gpi_dev->gpiis[gpii].gpii_chan[GPI_TX_CHAN]; rx_chan = &gpi_dev->gpiis[gpii].gpii_chan[GPI_RX_CHAN]; if (rx_chan->vc.chan.client_count && rx_chan->seid == seid) return gpii; if (tx_chan->vc.chan.client_count && tx_chan->seid == seid) return gpii; } /* no channels configured with same seid, return next avail gpii */ for (gpii = 0; gpii < gpi_dev->max_gpii; gpii++) { if (!((1 << gpii) & gpi_dev->gpii_mask)) continue; tx_chan = &gpi_dev->gpiis[gpii].gpii_chan[GPI_TX_CHAN]; rx_chan = &gpi_dev->gpiis[gpii].gpii_chan[GPI_RX_CHAN]; /* check if gpii is configured */ if (tx_chan->vc.chan.client_count || rx_chan->vc.chan.client_count) continue; /* found a free gpii */ return gpii; } /* no gpii instance available to use */ return -EIO; } /* gpi_of_dma_xlate: open client requested channel */ static struct dma_chan *gpi_of_dma_xlate(struct of_phandle_args *args, struct of_dma *of_dma) { struct gpi_dev *gpi_dev = (struct gpi_dev *)of_dma->of_dma_data; u32 seid, chid; int gpii; struct gpii_chan *gpii_chan; if (args->args_count < REQ_OF_DMA_ARGS) { GPI_ERR(gpi_dev, "gpii require minimum 6 args, client passed:%d args\n", args->args_count); return NULL; } chid = args->args[0]; if (chid >= MAX_CHANNELS_PER_GPII) { GPI_ERR(gpi_dev, "gpii channel:%d not valid\n", chid); return NULL; } seid = args->args[1]; /* find next available gpii to use */ gpii = gpi_find_avail_gpii(gpi_dev, seid); if (gpii < 0) { GPI_ERR(gpi_dev, "no available gpii instances\n"); return NULL; } gpii_chan = &gpi_dev->gpiis[gpii].gpii_chan[chid]; if (gpii_chan->vc.chan.client_count) { GPI_ERR(gpi_dev, "gpii:%d chid:%d seid:%d already configured\n", gpii, chid, gpii_chan->seid); return NULL; } /* get ring size, protocol, se_id, and priority */ gpii_chan->seid = seid; gpii_chan->protocol = args->args[2]; gpii_chan->req_tres = args->args[3]; gpii_chan->priority = args->args[4]; GPI_LOG(gpi_dev, "client req. gpii:%u chid:%u #_tre:%u priority:%u protocol:%u\n", gpii, chid, gpii_chan->req_tres, gpii_chan->priority, gpii_chan->protocol); return dma_get_slave_channel(&gpii_chan->vc.chan); } /* gpi_setup_debug - setup debug capabilities */ static void gpi_setup_debug(struct gpi_dev *gpi_dev) { char node_name[GPI_LABEL_SIZE]; const umode_t mode = 0600; int i; snprintf(node_name, sizeof(node_name), "%s%llx", GPI_DMA_DRV_NAME, (u64)gpi_dev->res->start); gpi_dev->ilctxt = ipc_log_context_create(IPC_LOG_PAGES, node_name, 0); gpi_dev->ipc_log_lvl = DEFAULT_IPC_LOG_LVL; if (!IS_ERR_OR_NULL(pdentry)) { snprintf(node_name, sizeof(node_name), "%llx", (u64)gpi_dev->res->start); gpi_dev->dentry = debugfs_create_dir(node_name, pdentry); if (!IS_ERR_OR_NULL(gpi_dev->dentry)) { debugfs_create_u32("ipc_log_lvl", mode, gpi_dev->dentry, &gpi_dev->ipc_log_lvl); debugfs_create_u32("klog_lvl", mode, gpi_dev->dentry, &gpi_dev->klog_lvl); } } for (i = 0; i < gpi_dev->max_gpii; i++) { struct gpii *gpii; if (!((1 << i) & gpi_dev->gpii_mask)) continue; gpii = &gpi_dev->gpiis[i]; snprintf(gpii->label, sizeof(gpii->label), "%s%llx_gpii%d", GPI_DMA_DRV_NAME, (u64)gpi_dev->res->start, i); gpii->ilctxt = ipc_log_context_create(IPC_LOG_PAGES, gpii->label, 0); gpii->ipc_log_lvl = DEFAULT_IPC_LOG_LVL; gpii->klog_lvl = DEFAULT_KLOG_LVL; if (IS_ERR_OR_NULL(gpi_dev->dentry)) continue; snprintf(node_name, sizeof(node_name), "gpii%d", i); gpii->dentry = debugfs_create_dir(node_name, gpi_dev->dentry); if (IS_ERR_OR_NULL(gpii->dentry)) continue; debugfs_create_u32("ipc_log_lvl", mode, gpii->dentry, &gpii->ipc_log_lvl); debugfs_create_u32("klog_lvl", mode, gpii->dentry, &gpii->klog_lvl); } } static struct dma_iommu_mapping *gpi_create_mapping(struct gpi_dev *gpi_dev) { dma_addr_t base; size_t size; /* * If S1_BYPASS enabled then iommu space is not used, however framework * still require clients to create a mapping space before attaching. So * set to smallest size required by iommu framework. */ if (gpi_dev->smmu_cfg & GPI_SMMU_S1_BYPASS) { base = 0; size = PAGE_SIZE; } else { base = gpi_dev->iova_base; size = gpi_dev->iova_size; } GPI_LOG(gpi_dev, "Creating iommu mapping of base:0x%llx size:%lu\n", base, size); return arm_iommu_create_mapping(&platform_bus_type, base, size); } static int gpi_smmu_init(struct gpi_dev *gpi_dev) { struct dma_iommu_mapping *mapping = NULL; int ret; if (gpi_dev->smmu_cfg) { /* create mapping table */ mapping = gpi_create_mapping(gpi_dev); if (IS_ERR(mapping)) { GPI_ERR(gpi_dev, "Failed to create iommu mapping, ret:%ld\n", PTR_ERR(mapping)); return PTR_ERR(mapping); } if (gpi_dev->smmu_cfg & GPI_SMMU_S1_BYPASS) { int s1_bypass = 1; ret = iommu_domain_set_attr(mapping->domain, DOMAIN_ATTR_S1_BYPASS, &s1_bypass); if (ret) { GPI_ERR(gpi_dev, "Failed to set attr S1_BYPASS, ret:%d\n", ret); goto release_mapping; } } if (gpi_dev->smmu_cfg & GPI_SMMU_FAST) { int fast = 1; ret = iommu_domain_set_attr(mapping->domain, DOMAIN_ATTR_FAST, &fast); if (ret) { GPI_ERR(gpi_dev, "Failed to set attr FAST, ret:%d\n", ret); goto release_mapping; } } if (gpi_dev->smmu_cfg & GPI_SMMU_ATOMIC) { int atomic = 1; ret = iommu_domain_set_attr(mapping->domain, DOMAIN_ATTR_ATOMIC, &atomic); if (ret) { GPI_ERR(gpi_dev, "Failed to set attr ATOMIC, ret:%d\n", ret); goto release_mapping; } } ret = arm_iommu_attach_device(gpi_dev->dev, mapping); if (ret) { GPI_ERR(gpi_dev, "Failed with iommu_attach, ret:%d\n", ret); goto release_mapping; } } GPI_LOG(gpi_dev, "Setting dma mask to 64\n"); ret = dma_set_mask(gpi_dev->dev, DMA_BIT_MASK(64)); if (ret) { GPI_ERR(gpi_dev, "Error setting dma_mask to 64, ret:%d\n", ret); goto error_set_mask; } return ret; error_set_mask: if (gpi_dev->smmu_cfg) arm_iommu_detach_device(gpi_dev->dev); release_mapping: if (mapping) arm_iommu_release_mapping(mapping); return ret; } static int gpi_probe(struct platform_device *pdev) { struct gpi_dev *gpi_dev; int ret, i; u32 gpi_ee_offset; gpi_dev = devm_kzalloc(&pdev->dev, sizeof(*gpi_dev), GFP_KERNEL); if (!gpi_dev) return -ENOMEM; gpi_dev->dev = &pdev->dev; gpi_dev->klog_lvl = DEFAULT_KLOG_LVL; gpi_dev->res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "gpi-top"); if (!gpi_dev->res) { GPI_ERR(gpi_dev, "missing 'reg' DT node\n"); return -EINVAL; } gpi_dev->regs = devm_ioremap_nocache(gpi_dev->dev, gpi_dev->res->start, resource_size(gpi_dev->res)); if (!gpi_dev->regs) { GPI_ERR(gpi_dev, "IO remap failed\n"); return -EFAULT; } gpi_dev->ee_base = gpi_dev->regs; ret = of_property_read_u32(gpi_dev->dev->of_node, "qcom,max-num-gpii", &gpi_dev->max_gpii); if (ret) { GPI_ERR(gpi_dev, "missing 'max-no-gpii' DT node\n"); return ret; } ret = of_property_read_u32(gpi_dev->dev->of_node, "qcom,gpii-mask", &gpi_dev->gpii_mask); if (ret) { GPI_ERR(gpi_dev, "missing 'gpii-mask' DT node\n"); return ret; } ret = of_property_read_u32(gpi_dev->dev->of_node, "qcom,gpi-ee-offset", &gpi_ee_offset); if (ret) GPI_LOG(gpi_dev, "No variable ee offset present\n"); else gpi_dev->ee_base = gpi_dev->ee_base - gpi_ee_offset; ret = of_property_read_u32(gpi_dev->dev->of_node, "qcom,ev-factor", &gpi_dev->ev_factor); if (ret) { GPI_ERR(gpi_dev, "missing 'qcom,ev-factor' DT node\n"); return ret; } ret = of_property_read_u32(gpi_dev->dev->of_node, "qcom,smmu-cfg", &gpi_dev->smmu_cfg); if (ret) { GPI_ERR(gpi_dev, "missing 'qcom,smmu-cfg' DT node\n"); return ret; } if (gpi_dev->smmu_cfg && !(gpi_dev->smmu_cfg & GPI_SMMU_S1_BYPASS)) { u64 iova_range[2]; ret = of_property_count_elems_of_size(gpi_dev->dev->of_node, "qcom,iova-range", sizeof(iova_range)); if (ret != 1) { GPI_ERR(gpi_dev, "missing or incorrect 'qcom,iova-range' DT node ret:%d\n", ret); } ret = of_property_read_u64_array(gpi_dev->dev->of_node, "qcom,iova-range", iova_range, sizeof(iova_range) / sizeof(u64)); if (ret) { GPI_ERR(gpi_dev, "could not read DT prop 'qcom,iova-range\n"); return ret; } gpi_dev->iova_base = iova_range[0]; gpi_dev->iova_size = iova_range[1]; } ret = gpi_smmu_init(gpi_dev); if (ret) { GPI_ERR(gpi_dev, "error configuring smmu, ret:%d\n", ret); return ret; } gpi_dev->gpiis = devm_kzalloc(gpi_dev->dev, sizeof(*gpi_dev->gpiis) * gpi_dev->max_gpii, GFP_KERNEL); if (!gpi_dev->gpiis) return -ENOMEM; /* setup all the supported gpii */ INIT_LIST_HEAD(&gpi_dev->dma_device.channels); for (i = 0; i < gpi_dev->max_gpii; i++) { struct gpii *gpii = &gpi_dev->gpiis[i]; int chan; if (!((1 << i) & gpi_dev->gpii_mask)) continue; /* set up ev cntxt register map */ gpii->ev_cntxt_base_reg = gpi_dev->ee_base + GPI_GPII_n_EV_CH_k_CNTXT_0_OFFS(i, 0); gpii->ev_cntxt_db_reg = gpi_dev->ee_base + GPI_GPII_n_EV_CH_k_DOORBELL_0_OFFS(i, 0); gpii->ev_ring_base_lsb_reg = gpii->ev_cntxt_base_reg + CNTXT_2_RING_BASE_LSB; gpii->ev_ring_rp_lsb_reg = gpii->ev_cntxt_base_reg + CNTXT_4_RING_RP_LSB; gpii->ev_ring_wp_lsb_reg = gpii->ev_cntxt_base_reg + CNTXT_6_RING_WP_LSB; gpii->ev_cmd_reg = gpi_dev->ee_base + GPI_GPII_n_EV_CH_CMD_OFFS(i); gpii->ieob_src_reg = gpi_dev->ee_base + GPI_GPII_n_CNTXT_SRC_IEOB_IRQ_OFFS(i); gpii->ieob_clr_reg = gpi_dev->ee_base + GPI_GPII_n_CNTXT_SRC_IEOB_IRQ_CLR_OFFS(i); /* set up irq */ ret = platform_get_irq(pdev, i); if (ret < 0) { GPI_ERR(gpi_dev, "could not req. irq for gpii%d ret:%d", i, ret); return ret; } gpii->irq = ret; /* set up channel specific register info */ for (chan = 0; chan < MAX_CHANNELS_PER_GPII; chan++) { struct gpii_chan *gpii_chan = &gpii->gpii_chan[chan]; /* set up ch cntxt register map */ gpii_chan->ch_cntxt_base_reg = gpi_dev->ee_base + GPI_GPII_n_CH_k_CNTXT_0_OFFS(i, chan); gpii_chan->ch_cntxt_db_reg = gpi_dev->ee_base + GPI_GPII_n_CH_k_DOORBELL_0_OFFS(i, chan); gpii_chan->ch_ring_base_lsb_reg = gpii_chan->ch_cntxt_base_reg + CNTXT_2_RING_BASE_LSB; gpii_chan->ch_ring_rp_lsb_reg = gpii_chan->ch_cntxt_base_reg + CNTXT_4_RING_RP_LSB; gpii_chan->ch_ring_wp_lsb_reg = gpii_chan->ch_cntxt_base_reg + CNTXT_6_RING_WP_LSB; gpii_chan->ch_cmd_reg = gpi_dev->ee_base + GPI_GPII_n_CH_CMD_OFFS(i); /* vchan setup */ vchan_init(&gpii_chan->vc, &gpi_dev->dma_device); gpii_chan->vc.desc_free = gpi_desc_free; gpii_chan->chid = chan; gpii_chan->gpii = gpii; gpii_chan->dir = GPII_CHAN_DIR[chan]; } mutex_init(&gpii->ctrl_lock); rwlock_init(&gpii->pm_lock); tasklet_init(&gpii->ev_task, gpi_ev_tasklet, (unsigned long)gpii); init_completion(&gpii->cmd_completion); gpii->gpii_id = i; gpii->regs = gpi_dev->ee_base; gpii->gpi_dev = gpi_dev; atomic_set(&gpii->dbg_index, 0); } platform_set_drvdata(pdev, gpi_dev); /* clear and Set capabilities */ dma_cap_zero(gpi_dev->dma_device.cap_mask); dma_cap_set(DMA_SLAVE, gpi_dev->dma_device.cap_mask); /* configure dmaengine apis */ gpi_dev->dma_device.directions = BIT(DMA_DEV_TO_MEM) | BIT(DMA_MEM_TO_DEV); gpi_dev->dma_device.residue_granularity = DMA_RESIDUE_GRANULARITY_DESCRIPTOR; gpi_dev->dma_device.src_addr_widths = DMA_SLAVE_BUSWIDTH_8_BYTES; gpi_dev->dma_device.dst_addr_widths = DMA_SLAVE_BUSWIDTH_8_BYTES; gpi_dev->dma_device.device_alloc_chan_resources = gpi_alloc_chan_resources; gpi_dev->dma_device.device_free_chan_resources = gpi_free_chan_resources; gpi_dev->dma_device.device_tx_status = dma_cookie_status; gpi_dev->dma_device.device_issue_pending = gpi_issue_pending; gpi_dev->dma_device.device_prep_slave_sg = gpi_prep_slave_sg; gpi_dev->dma_device.device_config = gpi_config; gpi_dev->dma_device.device_terminate_all = gpi_terminate_all; gpi_dev->dma_device.dev = gpi_dev->dev; gpi_dev->dma_device.device_pause = gpi_pause; gpi_dev->dma_device.device_resume = gpi_resume; /* register with dmaengine framework */ ret = dma_async_device_register(&gpi_dev->dma_device); if (ret) { GPI_ERR(gpi_dev, "async_device_register failed ret:%d", ret); return ret; } ret = of_dma_controller_register(gpi_dev->dev->of_node, gpi_of_dma_xlate, gpi_dev); if (ret) { GPI_ERR(gpi_dev, "of_dma_controller_reg failed ret:%d", ret); return ret; } /* setup debug capabilities */ gpi_setup_debug(gpi_dev); GPI_LOG(gpi_dev, "probe success\n"); return ret; } static const struct of_device_id gpi_of_match[] = { { .compatible = "qcom,gpi-dma" }, {} }; MODULE_DEVICE_TABLE(of, gpi_of_match); static struct platform_driver gpi_driver = { .probe = gpi_probe, .driver = { .name = GPI_DMA_DRV_NAME, .of_match_table = gpi_of_match, }, }; static int __init gpi_init(void) { pdentry = debugfs_create_dir(GPI_DMA_DRV_NAME, NULL); return platform_driver_register(&gpi_driver); } module_init(gpi_init) MODULE_DESCRIPTION("QCOM GPI DMA engine driver"); MODULE_LICENSE("GPL v2");
26.450207
80
0.702081