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
f6ad6b01017463444d355ac46c3e574ac566a174
7,074
c
C
presentations/network/creative-packets/yersinia/yersinia-0.7/src/ncurses-gui.c
spl0w/security-courses
dbb76ec8491346eba8fc796ca09729bb12bc8a6f
[ "BSD-3-Clause" ]
1
2021-12-07T13:16:38.000Z
2021-12-07T13:16:38.000Z
presentations/network/creative-packets/yersinia/yersinia-0.7/src/ncurses-gui.c
spl0w/security-courses
dbb76ec8491346eba8fc796ca09729bb12bc8a6f
[ "BSD-3-Clause" ]
null
null
null
presentations/network/creative-packets/yersinia/yersinia-0.7/src/ncurses-gui.c
spl0w/security-courses
dbb76ec8491346eba8fc796ca09729bb12bc8a6f
[ "BSD-3-Clause" ]
null
null
null
/* ncurses-gui.c * Implementation for ncurses GUI * * Yersinia * By David Barroso <tomac@wasahero.org> and Alfredo Andres <slay@wasahero.org> * Copyright 2005 Alfredo Andres and David Barroso * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef lint static const char rcsid[] = "$Id: ncurses-gui.c 15 2006-04-10 20:42:06Z tomac $"; #endif #ifdef HAVE_CONFIG_H #include <config.h> #endif #define _REENTRANT #include <stdio.h> #include <errno.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include <sys/socket.h> #ifdef HAVE_NETINET_IN_SYSTM_H #include <netinet/in_systm.h> #else #ifdef HAVE_NETINET_IN_SYSTEM_H #include <netinet/in_system.h> #endif #endif #include <netinet/in.h> #include <arpa/inet.h> #include <signal.h> #include <time.h> #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_STRINGS_H #include <strings.h> #endif #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #ifdef STDC_HEADERS #include <stdlib.h> #endif #include <stdarg.h> #include <netinet/tcp.h> #ifdef SOLARIS #include <pthread.h> #include <thread.h> #else #include <pthread.h> #endif #include "ncurses-gui.h" #include "ncurses-interface.h" #include "ncurses-callbacks.h" /* * Initialization routines for the GUI */ void ncurses_gui(void *args) { int tmp; WINDOW *my_wins[NCURSES_MAX_WINDOWS]; PANEL *my_panels[NCURSES_MAX_WINDOWS]; struct term_node *term_node = NULL; time_t this_time; sigset_t mask; struct interface_data *iface_data=NULL, *iface; terms->work_state = RUNNING; pthread_mutex_lock(&terms->gui_th.finished); write_log(0,"\n ncurses_gui_th = %d\n",(int)pthread_self()); sigfillset(&mask); if (pthread_sigmask(SIG_BLOCK, &mask, NULL)) { thread_error("ncurses_gui_th pthread_sigmask()",errno); ncurses_gui_th_exit(NULL); } if (pthread_mutex_lock(&terms->mutex) != 0) { thread_error("ncurses_gui_th pthread_mutex_lock",errno); ncurses_gui_th_exit(NULL); } if (term_add_node(&term_node, TERM_CON, (int)NULL, pthread_self()) < 0) { if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("ncurses_gui_th pthread_mutex_unlock",errno); ncurses_gui_th_exit(NULL); } if (term_node == NULL) { write_log(0, "Ouch!! No more than %d %s accepted!!\n", term_type[TERM_CON].max, term_type[TERM_CON].name); if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("ncurses_gui_th pthread_mutex_unlock",errno); ncurses_gui_th_exit(NULL); } this_time = time(NULL); #ifdef HAVE_CTIME_R #ifdef SOLARIS ctime_r(&this_time,term_node->since, sizeof(term_node->since)); #else ctime_r(&this_time,term_node->since); #endif #else pthread_mutex_lock(&mutex_ctime); strncpy(term_node->since, ctime(&this_time), sizeof(term_node->since)); pthread_mutex_unlock(&mutex_ctime); #endif /* Just to remove the cr+lf...*/ term_node->since[sizeof(term_node->since)-2] = 0; /* This is a console so, man... ;) */ strncpy(term_node->from_ip, "127.0.0.1", sizeof(term_node->from_ip)); /* Parse config file */ if (strlen(tty_tmp->config_file)) if (parser_read_config_file(tty_tmp, term_node) < 0) { write_log(0, "Error reading configuration file\n"); /* ncurses_gui_th_exit(term_node); */ } if (pthread_mutex_unlock(&terms->mutex) != 0) { thread_error("ncurses_gui_th pthread_mutex_unlock",errno); ncurses_gui_th_exit(term_node); } if (ncurses_i_init(my_wins, my_panels, term_node) < 0) ncurses_gui_th_exit(term_node); if (interfaces->list) iface_data = dlist_data(interfaces->list); else { ncurses_i_error_window(0, "Hmm... you don't have any valid interface. \ %s is useless. Go and get a life!", PACKAGE); ncurses_gui_th_exit(term_node); } /* take the first valid interface */ if (strlen(iface_data->ifname)) { if (ncurses_i_error_window(0, "Warning: interface %s selected as the default one", iface_data->ifname) < 0) ncurses_gui_th_exit(term_node); if ((tmp = interfaces_enable(iface_data->ifname)) == -1) { if (ncurses_i_error_window(1, "Unable to use interface %s!! (Maybe nonexistent?)\n\n", iface_data->ifname) < 0) ncurses_gui_th_exit(term_node); } else { iface = (struct interface_data *) calloc(1, sizeof(struct interface_data)); memcpy((void *)iface, (void *)iface_data, sizeof(struct interface_data)); term_node->used_ints->list = dlist_append(term_node->used_ints->list, iface); } } else { if (ncurses_i_error_window(1, "Hmm... you don't have any valid interface. \ %s is useless. Go and get a life!", PACKAGE) < 0) ncurses_gui_th_exit(term_node); } ncurses_c_engine(my_wins, my_panels, term_node); ncurses_gui_th_exit(term_node); } /* * GUI destroy. End */ void ncurses_gui_th_exit(struct term_node *term_node) { dlist_t *p; struct interface_data *iface_data; if (endwin() == ERR) thread_error("Error in endwin", errno); write_log(0, "\n ncurses_gui_th_exit start...\n"); if (term_node) { for (p = term_node->used_ints->list; p; p = dlist_next(term_node->used_ints->list, p)) { iface_data = (struct interface_data *) dlist_data(p); interfaces_disable(iface_data->ifname); } attack_kill_th(term_node,ALL_ATTACK_THREADS); if (pthread_mutex_lock(&terms->mutex) != 0) thread_error("ncurses_gui_th pthread_mutex_lock",errno); term_delete_node(term_node, NOKILL_THREAD); if (pthread_mutex_unlock(&terms->mutex) != 0) thread_error("ncurses_gui_th pthread_mutex_unlock",errno); } write_log(0," ncurses_gui_th_exit finish...\n"); if (pthread_mutex_unlock(&terms->gui_th.finished) != 0) thread_error("ncurses_gui_th pthread_mutex_unlock",errno); terms->work_state = STOPPED; terms->gui_th.id = 0; pthread_exit(NULL); }
26.69434
94
0.665253
8ce65aeca48037973edb1b8ccb6eb3e859ba3ace
2,862
c
C
ios_kernel/source/utils.c
zsrtp/TPHD-BetaQuest
5a10d3c332ddd5ff6a403a9ca841d96fe41570ef
[ "MIT" ]
3
2019-07-11T14:10:01.000Z
2020-08-16T18:46:00.000Z
ios_kernel/source/utils.c
zsrtp/TPHD-BetaQuest
5a10d3c332ddd5ff6a403a9ca841d96fe41570ef
[ "MIT" ]
null
null
null
ios_kernel/source/utils.c
zsrtp/TPHD-BetaQuest
5a10d3c332ddd5ff6a403a9ca841d96fe41570ef
[ "MIT" ]
2
2020-07-19T19:41:01.000Z
2022-03-06T16:20:51.000Z
/*************************************************************************** * Copyright (C) 2016 * by Dimok * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any * damages arising from the use of this software. * * Permission is granted to anyone to use this software for any * purpose, including commercial applications, and to alter it and * redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you * must not claim that you wrote the original software. If you use * this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and * must not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. ***************************************************************************/ // this memcpy is optimized for speed and to work with MEM1 32 bit access alignment requirement void reverse_memcpy(void* dst, const void* src, unsigned int size) { const unsigned char *src_p; unsigned char *dst_p; if((size >= 4) && !((dst - src) & 3)) { const unsigned int *src_p32; unsigned int *dst_p32; unsigned int endDst = ((unsigned int)dst) + size; unsigned int endRest = endDst & 3; if(endRest) { src_p = ((const unsigned char*)(src + size)) - 1; dst_p = ((unsigned char*)endDst) - 1; size -= endRest; while(endRest--) *dst_p-- = *src_p--; } src_p32 = ((const unsigned int*)(src + size)) - 1; dst_p32 = ((unsigned int*)(dst + size)) - 1; unsigned int size32 = size >> 5; if(size32) { size &= 0x1F; while(size32--) { src_p32 -= 8; dst_p32 -= 8; dst_p32[8] = src_p32[8]; dst_p32[7] = src_p32[7]; dst_p32[6] = src_p32[6]; dst_p32[5] = src_p32[5]; dst_p32[4] = src_p32[4]; dst_p32[3] = src_p32[3]; dst_p32[2] = src_p32[2]; dst_p32[1] = src_p32[1]; } } unsigned int size4 = size >> 2; if(size4) { size &= 3; while(size4--) *dst_p32-- = *src_p32--; } dst_p = ((unsigned char*)dst_p32) + 3; src_p = ((const unsigned char*)src_p32) + 3; } else { dst_p = ((unsigned char*)dst) + size - 1; src_p = ((const unsigned char*)src) + size - 1; } while(size--) *dst_p-- = *src_p--; }
30.774194
95
0.521314
493e878b27251255d1a4ec02dc4f176c7446f74b
21,442
h
C
ref-impl/src/impl/ImplAAFTypeDefsGen.h
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
ref-impl/src/impl/ImplAAFTypeDefsGen.h
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
ref-impl/src/impl/ImplAAFTypeDefsGen.h
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
#ifndef __ImplAAFTypeDefsGen_h__ #define __ImplAAFTypeDefsGen_h__ //=---------------------------------------------------------------------= // // $Id$ $Name$ // // The contents of this file are subject to the AAF SDK Public Source // License Agreement Version 2.0 (the "License"); You may not use this // file except in compliance with the License. The License is available // in AAFSDKPSL.TXT, or you may obtain a copy of the License from the // Advanced Media Workflow Association, Inc., or its successor. // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and limitations // under the License. Refer to Section 3.3 of the License for proper use // of this Exhibit. // // WARNING: Please contact the Advanced Media Workflow Association, // Inc., for more information about any additional licenses to // intellectual property covering the AAF Standard that may be required // to create and distribute AAF compliant products. // (http://www.amwa.tv/policies). // // Copyright Notices: // The Original Code of this file is Copyright 1998-2009, licensor of the // Advanced Media Workflow Association. All rights reserved. // // The Initial Developer of the Original Code of this file and the // licensor of the Advanced Media Workflow Association is // Avid Technology. // All rights reserved. // //=---------------------------------------------------------------------= #include "AAFTypes.h" #include "AAFUtils.h" // Get guids for types we'll use #define TYPE_GUID_NAME(type) kAAFTypeID_##type #include "AAFTypeDefUIDs.h" #include "AAFPropertyDefs.h" // // Pass 0: Do stuff for characters. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeCharacter \ { \ const wchar_t * typeName; \ aafUID_t typeID; \ int isValid; \ }; \ \ static TypeCharacter s_AAFAllTypeCharacters [] = { #define AAF_TYPE_DEFINITION_CHARACTER(name, id) {L"aaf" L###name, id, 1}, #if defined(_MSC_VER) && (_MSC_VER <= 1200) #define AAF_TYPE_TABLE_END() 0 }; #else #define AAF_TYPE_TABLE_END() {0, kNullUID, 0} }; #endif #include "AAFMetaDictionary.h" // // Pass 1: Do stuff for integers. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeInteger \ { \ const wchar_t * typeName; \ aafUID_t typeID; \ aafUInt8 size; \ aafBool isSigned; \ int isValid; \ }; \ \ static TypeInteger s_AAFAllTypeIntegers [] = { #define AAF_TYPE_DEFINITION_INTEGER(name, id, size, signed) {L"aaf" L###name, id, size, kAAF##signed, 1}, #define AAF_TYPE_TABLE_END() {0, kNullUID, 0, kAAFFalse, 0} }; #include "AAFMetaDictionary.h" // // pass 2: For enumerations, define individual enumeration fields // // // Define structs to describe each member of an enumeration typedef, // and to describe the entire enumeration typedef. // #define AAF_TYPE_TABLE_BEGIN() \ \ struct TypeEnumerationMember \ { \ const wchar_t * memberName; \ aafInt64 memberValue; \ }; \ \ struct TypeEnumeration \ { \ aafUID_t typeID; \ const wchar_t * typeName; \ const aafUID_t * pElementTypeId; \ aafUInt32 size; \ TypeEnumerationMember ** members; \ }; #define AAF_TYPE_DEFINITION_ENUMERATION_MEMBER(name, value, parent) \ static const TypeEnumerationMember s_TypeEnumerationMember_##parent##_##name = \ { L###name, \ value \ }; #define AAF_TYPE(x) aaf##x##_t #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #include "AAFMetaDictionary.h" // // pass 3: For enumerations, create the (null-terminated) field list for // each enumeration // #define AAF_TYPE_DEFINITION_ENUMERATION(name, id, type) \ static const TypeEnumerationMember *s_TypeEnumerationMembers_##name[] = { #define AAF_TYPE_DEFINITION_ENUMERATION_MEMBER(name, value, parent) \ &s_TypeEnumerationMember_##parent##_##name, #define AAF_TYPE_DEFINITION_ENUMERATION_END(name, id, type) \ 0 } ; #define AAF_TYPE(x) _aaf##x##_t #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #include "AAFMetaDictionary.h" // // pass 4: For enumerations, create each enumeration definition // #define AAF_TYPE_DEFINITION_ENUMERATION(name, id, type) \ static const TypeEnumeration s_TypeEnumeration_##name = \ { id, \ L###name, \ /*(aafUID_t *)*/& TYPE_GUID_NAME(type), \ sizeof (aaf##name##_t), \ (TypeEnumerationMember **) s_TypeEnumerationMembers_##name, \ }; #define AAF_TYPE(x) x // #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) // #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #include "AAFMetaDictionary.h" // // pass 5: For enumerations, create a master null-terminated list of all // type def enumerations // #define AAF_TYPE_TABLE_BEGIN() \ static TypeEnumeration * s_AAFAllTypeEnumerations [] = { #define AAF_TYPE_DEFINITION_ENUMERATION(name, id, type) \ (TypeEnumeration*)& s_TypeEnumeration_##name, #define AAF_TYPE_TABLE_END() \ 0 }; #define AAF_TYPE(x) _aaf##x##_t #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #include "AAFMetaDictionary.h" // // Done with enumerations. // // // pass 6: For records, define individual record fields // // // Define structs to describe each member of a record typedef, and to // describe the entire record typedef. // #define AAF_TYPE_TABLE_BEGIN() \ \ struct TypeRecordMember \ { \ const aafUID_t * pMemberTypeId; \ const wchar_t * memberName; \ aafUInt32 memberOffset; \ eAAFTypeCategory_t typeCat; \ }; \ \ struct TypeRecord \ { \ aafUID_t typeID; \ const wchar_t * typeName; \ aafUInt32 size; \ TypeRecordMember ** members; \ }; #define AAF_TYPE_RECORD_MEMBER(recordName, memberType, memberName) \ #define AAF_TYPE_DEFINITION_RECORD_FIELD(name, type, parent) \ static const TypeRecordMember s_TypeRecordMember_##parent##_##name = \ { (aafUID_t *)& TYPE_GUID_NAME(type), \ L###name, \ offsetof (aaf##parent##_t, name), \ kAAFTypeCatUnknown \ }; #define AAF_TYPE(x) x #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #include "AAFMetaDictionary.h" // // pass 7: For records, create the (null-terminated) field list for // each record // #define AAF_TYPE_DEFINITION_RECORD(name, id) \ static const TypeRecordMember *s_TypeRecordMembers_##name[] = { #define AAF_TYPE_DEFINITION_RECORD_FIELD(name, type, parent) \ &s_TypeRecordMember_##parent##_##name, #define AAF_TYPE_DEFINITION_RECORD_END(name, id) \ 0 } ; #define AAF_TYPE(x) _aaf##x##_t #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #include "AAFMetaDictionary.h" // // pass 8: For records, create each record definition // #define AAF_TYPE_DEFINITION_RECORD(name, id) \ static const TypeRecord s_TypeRecord_##name = \ { id, L###name, sizeof (AAF_TYPE(name)), (TypeRecordMember **) s_TypeRecordMembers_##name }; #define AAF_TYPE(x) aaf##x##_t #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #include "AAFMetaDictionary.h" // // pass 9: For records, create a master null-terminated list of all // type def records // #define AAF_TYPE_TABLE_BEGIN() \ static TypeRecord * s_AAFAllTypeRecords [] = { #define AAF_TYPE_DEFINITION_RECORD(name, id) \ (TypeRecord*)& s_TypeRecord_##name, #define AAF_TYPE_TABLE_END() \ 0 }; #define AAF_TYPE(x) _aaf##x##_t #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #include "AAFMetaDictionary.h" // // Done with records. // // // Pass 10: Do stuff for varying arrays. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeVaryingArray \ { \ const wchar_t * typeName; \ aafUID_t typeId; \ const aafUID_t * pBaseTypeId; \ int isValid; \ }; \ \ static TypeVaryingArray s_AAFAllTypeVaryingArrays [] = { #define AAF_TYPE(x) kAAFTypeID_##x #define AAF_TYPE_DEFINITION_VARYING_ARRAY(name, id, type) \ {L"aaf" L###name, id, &type, 1}, #define AAF_TYPE_TABLE_END() \ {0, kNullUID, 0, 0} }; #include "AAFMetaDictionary.h" // // Pass 11: Do stuff for fixed arrays. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeFixedArray \ { \ const wchar_t * typeName; \ aafUID_t typeId; \ const aafUID_t * pBaseTypeId; \ aafUInt32 count; \ int isValid; \ }; \ \ static TypeFixedArray s_AAFAllTypeFixedArrays [] = { #define AAF_TYPE(x) kAAFTypeID_##x #define AAF_TYPE_DEFINITION_FIXED_ARRAY(name, id, type, count) \ {L"aaf" L###name, id, &type, count, 1}, #define AAF_TYPE_TABLE_END() \ {0, kNullUID, 0, 0, 0}}; #include "AAFMetaDictionary.h" // // Pass 12: Do stuff for rename types. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeRename \ { \ const wchar_t * typeName; \ aafUID_t typeId; \ const aafUID_t * pBaseTypeId; \ int isValid; \ }; \ \ static TypeRename s_AAFAllTypeRenames [] = { #define AAF_TYPE(x) kAAFTypeID_##x #define AAF_TYPE_DEFINITION_RENAME(name, id, type) \ {L"aaf" L###name, id, (aafUID_t *)& AAF_TYPE(type), 1}, #define AAF_TYPE_TABLE_END() \ {0, kNullUID, 0, 0}}; #include "AAFMetaDictionary.h" // // Pass 13: Do stuff for string types. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeString \ { \ const wchar_t * typeName; \ aafUID_t typeId; \ const aafUID_t * pBaseTypeId; \ int isValid; \ }; \ \ static TypeString s_AAFAllTypeStrings [] = { #define AAF_TYPE(x) kAAFTypeID_##x #define AAF_TYPE_DEFINITION_STRING(name, id, type) \ {L"aaf" L###name, id, (aafUID_t *)& AAF_TYPE(type), 1}, #define AAF_TYPE_TABLE_END() \ {0, kNullUID, 0, 0}}; #include "AAFMetaDictionary.h" // // Pass 14: Do stuff for strong ref types. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeStrongRef \ { \ const wchar_t * typeName; \ aafUID_t typeId; \ const aafUID_t * pRefdTypeId; \ int isValid; \ }; \ \ static TypeStrongRef s_AAFAllTypeStrongRefs [] = { #define AAF_TYPE(x) AUID_AAF##x #define AAF_REFERENCE_TYPE(type, target) kAAFTypeID_target##type #define AAF_REFERENCE_TYPE_NAME(type, target) L"kAAFTypeID_" L###target L###type #define AAF_TYPE_DEFINITION_STRONG_REFERENCE(name, id, type) \ {name, id, (aafUID_t *)& type, 1}, #define AAF_TYPE_TABLE_END() \ {0, kNullUID, 0, 0}}; #include "AAFMetaDictionary.h" // // Pass 15: Do stuff for strong ref set types. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeStrongRefSet \ { \ const wchar_t * typeName; \ aafUID_t typeId; \ const aafUID_t * pRefdTypeId; \ int isValid; \ }; \ \ static TypeStrongRefSet s_AAFAllTypeStrongRefSets [] = { #define AAF_TYPE(x) kAAFTypeID_##x##StrongReference #define AAF_REFERENCE_TYPE_NAME(type, target) L"kAAFTypeID_" L###target L###type #define AAF_TYPE_DEFINITION_STRONG_REFERENCE_SET(name, id, type) \ {name, id, (aafUID_t *)& type, 1}, #define AAF_TYPE_TABLE_END() \ {0, kNullUID, 0, 0}}; #include "AAFMetaDictionary.h" // // Pass 16: Do stuff for strong ref vector types. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeStrongRefVector \ { \ const wchar_t * typeName; \ aafUID_t typeId; \ const aafUID_t * pRefdTypeId; \ int isValid; \ }; \ \ static TypeStrongRefVector s_AAFAllTypeStrongRefVectors [] = { #define AAF_TYPE(x) kAAFTypeID_##x##StrongReference #define AAF_REFERENCE_TYPE_NAME(type, target) L"kAAFTypeID_" L###target L###type #define AAF_TYPE_DEFINITION_STRONG_REFERENCE_VECTOR(name, id, type) \ {name, id, (aafUID_t *)& type, 1}, #define AAF_TYPE_TABLE_END() \ {0, kNullUID, 0, 0}}; #include "AAFMetaDictionary.h" // AAF_TYPE_DEFINITION_WEAK_REFERENCE_MEMBER(name, parent, container) // // Pass 17a: Do stuff for weak ref types. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeWeakRefMember \ { \ const aafUID_t * propertyId; \ }; \ \ struct TypeWeakRef \ { \ const wchar_t * typeName; \ aafUID_t typeId; \ const aafUID_t * pRefdTypeId; \ int isValid; \ aafUInt32 size; \ const TypeWeakRefMember * members; \ }; \ #define AAF_TYPE(name) name #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #define MY_PROPERTY_ID(name, parent) {&kAAFPropID_##parent##_##name} #define MY_ARRAY_NAME(name) s_TypeWeakRefMember_##name #define AAF_TYPE_DEFINITION_WEAK_REFERENCE(name, id, type) \ static const TypeWeakRefMember MY_ARRAY_NAME(name)[] = \ { \ #define AAF_TYPE_DEFINITION_WEAK_REFERENCE_MEMBER(name, parent, container) \ MY_PROPERTY_ID(name, parent), #define AAF_TYPE_DEFINITION_WEAK_REFERENCE_END(name, id, type) \ }; #include "AAFMetaDictionary.h" #undef MY_PROPERTY_ID // // Pass 17b: Do stuff for weak ref types. // #define AAF_TYPE_TABLE_BEGIN() \ static TypeWeakRef s_AAFAllTypeWeakRefs [] = { #define AAF_TYPE(x) AUID_AAF##x #define AAF_REFERENCE_TYPE(type, target) kAAFTypeID_target##type #define AAF_REFERENCE_TYPE_NAME(type, target) target##type #define MY_TYPE_NAME(name) L###name #define AAF_TYPE_DEFINITION_WEAK_REFERENCE(name, id, type) \ {MY_TYPE_NAME(name), id, (aafUID_t *)& type, 1, sizeof(MY_ARRAY_NAME(name))/sizeof(TypeWeakRefMember), MY_ARRAY_NAME(name)}, #define AAF_TYPE_TABLE_END() \ {0, kNullUID, 0, 0, 0, 0}}; #include "AAFMetaDictionary.h" #undef MY_ARRAY_NAME // // Pass 18: Do stuff for weak ref set types. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeWeakRefSet \ { \ const wchar_t * typeName; \ aafUID_t typeId; \ const aafUID_t * pRefdTypeId; \ int isValid; \ }; \ \ static TypeWeakRefSet s_AAFAllTypeWeakRefSets [] = { #define AAF_TYPE(x) kAAFTypeID_##x##WeakReference #define AAF_REFERENCE_TYPE_NAME(type, target) L"kAAFTypeID_" L###target L###type #define AAF_TYPE_DEFINITION_WEAK_REFERENCE_SET(name, id, type) \ {name, id, (aafUID_t *)& type, 1}, #define AAF_TYPE_TABLE_END() \ {0, kNullUID, 0, 0}}; #include "AAFMetaDictionary.h" // // Pass 19: Do stuff for weak ref vector types. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeWeakRefVector \ { \ const wchar_t * typeName; \ aafUID_t typeId; \ const aafUID_t * pRefdTypeId; \ int isValid; \ }; \ \ static TypeWeakRefVector s_AAFAllTypeWeakRefVectors [] = { #define AAF_TYPE(x) kAAFTypeID_##x##WeakReference #define AAF_REFERENCE_TYPE_NAME(type, target) L"kAAFTypeID_" L###target L###type #define AAF_TYPE_DEFINITION_WEAK_REFERENCE_VECTOR(name, id, type) \ {name, id, (aafUID_t *)& type, 1}, #define AAF_TYPE_TABLE_END() \ {0, kNullUID, 0, 0}}; #include "AAFMetaDictionary.h" // // pass 20: For extendible enumerations, define individual enumeration // fields // // // Define structs to describe each member of an extendible enumeration // typedef, and to describe the entire extendible enumeration typedef. // #define AAF_TYPE_TABLE_BEGIN() \ \ struct TypeExtEnumerationMember \ { \ const wchar_t * memberName; \ aafUID_t memberValue; \ }; \ \ struct TypeExtEnumeration \ { \ aafUID_t typeID; \ const wchar_t * typeName; \ TypeExtEnumerationMember ** members; \ }; #define AAF_TYPE_DEFINITION_EXTENDIBLE_ENUMERATION_MEMBER(name, auid, container) \ static const TypeExtEnumerationMember s_TypeExtEnumerationMember_##container##_##name = \ { L###name, \ auid \ }; #define AAF_TYPE(x) aaf##x##_t #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #include "AAFMetaDictionary.h" // // pass 21: For extendible enumerations, create the (null-terminated) // field list for each extendible enumeration // #define AAF_TYPE_DEFINITION_EXTENDIBLE_ENUMERATION(name, id) \ static const TypeExtEnumerationMember *s_TypeExtEnumerationMembers_##name[] = { #define AAF_TYPE_DEFINITION_EXTENDIBLE_ENUMERATION_MEMBER(name, value, container) \ &s_TypeExtEnumerationMember_##container##_##name, #define AAF_TYPE_DEFINITION_EXTENDIBLE_ENUMERATION_END(name, id) \ 0 } ; #define AAF_TYPE(x) _aaf##x##_t #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #include "AAFMetaDictionary.h" // // pass 22: For extendible enumerations, create each extendible // enumeration definition // #define AAF_TYPE_DEFINITION_EXTENDIBLE_ENUMERATION(name, id) \ static const TypeExtEnumeration s_TypeExtEnumeration_##name = \ { id, \ L###name, \ (TypeExtEnumerationMember **) s_TypeExtEnumerationMembers_##name, \ }; #define AAF_TYPE(x) x // #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) // #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #include "AAFMetaDictionary.h" // // pass 23: For extendible enumerations, create a master // null-terminated list of all type def extendible enumerations // #define AAF_TYPE_TABLE_BEGIN() \ static TypeExtEnumeration * s_AAFAllTypeExtEnumerations [] = { #define AAF_TYPE_DEFINITION_EXTENDIBLE_ENUMERATION(name, id) \ (TypeExtEnumeration*)& s_TypeExtEnumeration_##name, #define AAF_TYPE_TABLE_END() \ 0 }; #define AAF_TYPE(x) _aaf##x##_t #define AAF_REFERENCE_TYPE(type, target) AAF_TYPE(target##type) #define AAF_REFERENCE_TYPE_NAME(type, target) AAF_TYPE(target##type) #include "AAFMetaDictionary.h" // // Done with extendible enumerations. // // // pass 24: For stream types (transdel:2000-JUN-13) // struct TypeStream { TypeStream(aafUID_constptr id, const wchar_t * name) : typeID(id), typeName(name) {} aafUID_constptr typeID; const wchar_t * typeName; }; #define MY_TYPE_ID(name) &kAAFTypeID_##name #define MY_TYPE_NAME(name) L###name #define AAF_TYPE_TABLE_BEGIN() \ static TypeStream s_AAFAllTypeStreams [] = \ { #define AAF_TYPE_DEFINITION_STREAM(name, id) \ TypeStream(MY_TYPE_ID(name), MY_TYPE_NAME(name)), #define AAF_TYPE_TABLE_END() \ }; #include "AAFMetaDictionary.h" // // Pass 25: Do stuff for set types. // #define AAF_TYPE_TABLE_BEGIN() \ struct TypeSet \ { \ const wchar_t * typeName; \ aafUID_t typeId; \ const aafUID_t * pRefdTypeId; \ int isValid; \ }; \ \ static TypeSet s_AAFAllTypeSets [] = { #define AAF_TYPE(x) kAAFTypeID_##x #define AAF_TYPE_DEFINITION_SET(name, id, type) \ {L###name, id, (aafUID_t *)& type, 1}, #define AAF_TYPE_TABLE_END() \ {0, kNullUID, 0, 0}}; #include "AAFMetaDictionary.h" #undef MY_TYPE_ID #undef MY_TYPE_NAME #endif // ! __ImplAAFTypeDefsGen_h__
29.372603
126
0.625128
0b5e3bab0cc2777a961c28673188c88d7e3614b5
1,048
c
C
ActionLog/scripts/sorts/sortStop.c
HelpGiveThanks/ActionLog
5626bd43f871e072c00c8e221cbb2c742491b636
[ "Apache-2.0" ]
null
null
null
ActionLog/scripts/sorts/sortStop.c
HelpGiveThanks/ActionLog
5626bd43f871e072c00c8e221cbb2c742491b636
[ "Apache-2.0" ]
36
2016-01-04T05:25:08.000Z
2016-12-12T19:14:22.000Z
ActionLog/scripts/sorts/sortStop.c
HelpGiveThanks/ActionLog
5626bd43f871e072c00c8e221cbb2c742491b636
[ "Apache-2.0" ]
null
null
null
Sorts: sortStop #PURPOSE sort by stop time # # # If [ steward::chosenSort = "veto" ] Set Variable [ $$record; Value:brainstate::_lockBrainstateID ] Sort Records [ Specified Sort Order: day1::_keyDay; ascending day1::swStop; descending brainstate::description; ascending ] [ Restore; No dialog ] Set Field [ steward::chosenSort; "etov" ] Go to Record/Request/Page [ First ] Loop Exit Loop If [ $$record = brainstate::_lockBrainstateID ] Go to Record/Request/Page [ Next ] End Loop Set Variable [ $$record ] Go to Field [ ] Halt Script End If If [ steward::chosenSort ≠ "veto" ] Set Variable [ $$record; Value:brainstate::_lockBrainstateID ] Sort Records [ Specified Sort Order: day1::swStop; ascending brainstate::description; ascending ] [ Restore; No dialog ] Set Field [ steward::chosenSort; "veto" ] Go to Record/Request/Page [ First ] Loop Exit Loop If [ $$record = brainstate::_lockBrainstateID ] Go to Record/Request/Page [ Next ] End Loop Set Variable [ $$record ] Go to Field [ ] End If January 6, 平成26 0:49:08 ActionLog.fp7 - sortStop -1-
25.560976
62
0.728053
4c7e0e50aba6c6e331e215dd9fdfccbd174217c7
1,256
h
C
iOSOpenDev/frameworks/MusicLibrary.framework/Headers/XXUnknownSuperclass.h
bzxy/cydia
f8c838cdbd86e49dddf15792e7aa56e2af80548d
[ "MIT" ]
678
2017-11-17T08:33:19.000Z
2022-03-26T10:40:20.000Z
iOSOpenDev/frameworks/MusicLibrary.framework/Headers/XXUnknownSuperclass.h
chenfanfang/Cydia
5efce785bfd5f1064b9c0f0e29a9cc05aa24cad0
[ "MIT" ]
22
2019-04-16T05:51:53.000Z
2021-11-08T06:18:45.000Z
iOSOpenDev/frameworks/MusicLibrary.framework/Headers/XXUnknownSuperclass.h
chenfanfang/Cydia
5efce785bfd5f1064b9c0f0e29a9cc05aa24cad0
[ "MIT" ]
170
2018-06-10T07:59:20.000Z
2022-03-22T16:19:33.000Z
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/MusicLibrary.framework/MusicLibrary */ #import <MusicLibrary/MusicLibrary-Structs.h> #import <MusicLibrary/XXUnknownSuperclass.h> // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __XXUnknownSuperclass__ #define __XXUnknownSuperclass__ 1 @interface XXUnknownSuperclass : NSObject @end #endif @interface XXUnknownSuperclass (InsignificantCharacterFiltering) - (id)MLSortString; // 0x11b59 - (id)copyWithoutInsignificantCharacters; // 0x11b45 - (id)copyWithoutInsignificantPrefixAndCharacters; // 0x11b31 - (id)_copyWithoutInsignificantPrefix:(BOOL)prefix andCharacters:(BOOL)characters; // 0x11acd - (NSRange)_rangeWithoutInsignificantPrefix:(BOOL)prefix andCharacters:(BOOL)characters; // 0x11849 @end @interface XXUnknownSuperclass (ML3Additions) - (id)ML3StringForKey:(id)key; // 0x3e3d5 @end @interface XXUnknownSuperclass (ML3NameOrderAdditions) + (id)valueWithML3NameOrder:(XXStruct_Cy4r_A)ml3NameOrder; // 0x44a61 - (XXStruct_Cy4r_A)ML3NameOrderValue; // 0x44ac1 @end @interface XXUnknownSuperclass (ML3NondurableWriteSetAdditions) - (void)ML3GetValuesAsPersistentIDsUsingBlock:(id)block; // 0x45559 @end
33.945946
99
0.811306
4cd8be08558f0fb32d2759df9fd2961dff7af15e
1,055
h
C
olds/network/include/tcp_accept.h
PickMio/NetEase
913ec8d02caa0f02fb48ba0dfab11776bf2fb4ff
[ "MIT" ]
1
2019-11-05T05:14:02.000Z
2019-11-05T05:14:02.000Z
olds/network/include/tcp_accept.h
PickMio/NetEase
913ec8d02caa0f02fb48ba0dfab11776bf2fb4ff
[ "MIT" ]
null
null
null
olds/network/include/tcp_accept.h
PickMio/NetEase
913ec8d02caa0f02fb48ba0dfab11776bf2fb4ff
[ "MIT" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: tcp_accept.h * Author: admin * * Created on 2017年3月7日, 上午11:25 */ #ifndef TCP_ACCEPT_H #define TCP_ACCEPT_H #include "svr_define.h" #include "iplayer.h" #include "net_package.h" #include "epoll_svr.h" namespace easynet{ //监听服务器 class EPOLLSvr; using EPOLLSvrPtr = std::shared_ptr<EPOLLSvr>; class TCPAccept : public IPlayer { public: TCPAccept(int32_t port, EPOLLSvrPtr s); bool Listen(bool reuse = true); virtual void OnNetMessage(); ~TCPAccept(); virtual void SetHandler(On_Accept_Handler h); private: On_Accept_Handler accept_handler_; //接收事件后的回调函数 EPOLLSvrPtr svr_; //epoll svr }; using TCPAcceptPtr = std::shared_ptr<TCPAccept>; } #endif /* TCP_ACCEPT_H */
22.934783
79
0.616114
34d68d44bbe0b73a063b4d93dd2c714daa7fb32d
12,786
c
C
usr/contrib/ucb/csh/sh.func.c
doolinius/unix-v7-galileo
403dfb4fbb875095e84763553a952cfbc8d558fd
[ "MIT" ]
null
null
null
usr/contrib/ucb/csh/sh.func.c
doolinius/unix-v7-galileo
403dfb4fbb875095e84763553a952cfbc8d558fd
[ "MIT" ]
null
null
null
usr/contrib/ucb/csh/sh.func.c
doolinius/unix-v7-galileo
403dfb4fbb875095e84763553a952cfbc8d558fd
[ "MIT" ]
null
null
null
/* @(#)sh.func.c 2.1 SCCS id keyword */ /* Copyright (c) 1980 Regents of the University of California */ #include "sh.h" /* * C shell */ struct biltins * isbfunc(cp) register char *cp; { register char *dp; register struct biltins *bp; if (lastchr(cp) == ':') return ((struct biltins *) 1); for (bp = bfunc; dp = bp->bname; bp++) { if (dp[0] == cp[0] && eq(dp, cp)) return (bp); if (dp[0] > cp[0]) break; } return (0); } func(t) register struct command *t; { register struct biltins *bp; int i; bp = bfunc; if (lastchr(t->t_dcom[0]) == ':') { xechoit(t->t_dcom); if (!eq(t->t_dcom[0], ":") && t->t_dcom[1]) error("No args on labels"); return (1); } bp = isbfunc(t->t_dcom[0]); if (bp == 0) return (0); /* timed builtins must go in background if output is pipe, or &'ed */ if (eq(bp->bname, "time")) if ((t->t_dflg & FAND) || (t->t_dflg & FPOU)) return (0); if (eq(bp->bname, "nohup") && t->t_dcom[1]) return (0); xechoit(t->t_dcom); setname(bp->bname); i = blklen(t->t_dcom) - 1; if (i < bp->minargs) bferr("Too few arguments"); if (i > bp->maxargs) bferr("Too many arguments"); i = (*bp->bfunct)(t->t_dcom, t); /* time and nice may not do their deeds, all others guarantee too */ return (eq(bp->bname, "time") || eq(bp->bname, "nice") ? i : 1); } doonintr(v) char **v; { register char *cp; register char *vv = v[1]; if (parintr == SIG_IGN) return; if (setintr && intty) bferr("Can't from terminal"); cp = gointr, gointr = 0, xfree(cp); if (vv == 0) { signal(SIGINT, setintr ? SIG_IGN : SIG_DFL); gointr = 0; } else if (eq((vv = strip(vv)), "-")) { signal(SIGINT, SIG_IGN); gointr = "-"; } else { gointr = savestr(vv); signal(SIGINT, pintr); } } donohup() { if (intty) bferr("Can't from terminal"); if (setintr == 0) { signal(SIGHUP, SIG_IGN); #ifdef CC submit(getpid()); #endif } } dozip() { ; } chngd(vp) register char **vp; { register int i; register char *dp; register char **cdp; vp++; dp = *vp; if (dp) dp = globone(dp); else { dp = value("home"); if (*dp == 0) bferr("No home"); } i = chdir(dp); if (i < 0 && dp[0] != '/') { struct varent *c = adrof("cdpath"); if (c == 0) goto simple; for (cdp = c->vec; *cdp; cdp++) { char buf[BUFSIZ]; strcpy(buf, *cdp); strcat(buf, "/"); strcat(buf, dp); i = chdir(buf); if (i >= 0) goto simple; } } simple: if (i < 0 && adrof(dp)) { char *cp = value(dp); if (cp[0] == '/') i = chdir(cp); } if (*vp) xfree(dp); if (i < 0) Perror(dp); } prvars() { plist(&shvhed); } doalias(v) register char **v; { register struct varent *vp; register char *p; v++; p = *v++; if (p == 0) plist(&aliases); else if (*v == 0) { vp = adrof1(strip(p), &aliases); if (vp) blkpr(vp->vec), printf("\n"); } else { if (eq(p, "alias") || eq(p, "unalias")) { setname(p); bferr("Too dangerous to alias that"); } set1(strip(p), saveblk(v), &aliases); } } unalias(v) char **v; { unset1(v, &aliases); } dologout() { islogin(); goodbye(); } dologin(v) char **v; { islogin(); execl("/bin/login", "login", v[1], 0); exit(1); } donewgrp(v) char **v; { #ifndef V6 execlp("newgrp", "newgrp", v[1], 0); #endif execl("/bin/newgrp", "newgrp", v[1], 0); /* just in case */ execl("/usr/bin/newgrp", "newgrp", v[1], 0); } islogin() { if (loginsh) return; error("Not login shell"); } doif(v, kp) char **v; struct command *kp; { register int i; register char **vv; v++; i = exp(&v); vv = v; if (*vv && eq(*vv, "then")) { vv++; if (*vv) bferr("Improper then"); setname("then"); /* * If expression was zero, then scan to else, * otherwise just fall into following code. */ if (!i) search(ZIF, 0); return; } /* * Simple command attached to this if. * Left shift the node in this tree, munging it * so we can reexecute it. */ if (i) { lshift(kp->t_dcom, vv - kp->t_dcom); reexecute(kp); donefds(); } } /* * Reexecute a command, being careful not * to redo i/o redirection, which is already set up. */ reexecute(kp) register struct command *kp; { kp->t_dflg = FREDO; execute(kp); } doelse() { search(ZELSE, 0); } dogoto(v) char **v; { register struct whyle *wp; char *lp; /* * While we still can, locate any unknown ends of existing loops. * This obscure code is the WORST result of the fact that we * don't really parse. */ for (wp = whyles; wp; wp = wp->w_next) if (wp->w_end == 0) wp->w_end = search(ZBREAK, 0); else bseek(wp->w_end); search(ZGOTO, 0, lp = globone(v[1])); xfree(lp); /* * Eliminate loops which were exited. */ wfree(); } doswitch(v) register char **v; { register char *cp, *lp; v++; if (!*v || *(*v++) != '(') goto syntax; cp = **v == ')' ? "" : *v++; if (*(*v++) != ')') v--; if (*v) syntax: error("Syntax error"); search(ZSWITCH, 0, lp = globone(cp)); xfree(lp); } dobreak() { if (whyles) toend(); else bferr("Not in while/foreach"); } doexit(v) char **v; { /* * Don't DEMAND parentheses here either. */ v++; if (*v) { set("status", putn(exp(&v))); if (*v) bferr("Expression syntax"); } btoeof(); if (intty) close(SHIN); } doforeach(v) register char **v; { register char *cp; register struct whyle *nwp; v++; cp = strip(*v); while (*cp && letter(*cp)) cp++; if (*cp || strlen(*v) >= 20) bferr("Invalid variable"); cp = *v++; if (v[0][0] != '(' || v[blklen(v) - 1][0] != ')') bferr("Words not ()'ed"); v++; gflag = 0, rscan(v, tglob); v = glob(v); if (v == 0) bferr("No match"); nwp = (struct whyle *) calloc(1, sizeof *nwp); nwp->w_fe = nwp->w_fe0 = v; gargv = 0; nwp->w_start = btell(); nwp->w_fename = savestr(cp); nwp->w_next = whyles; whyles = nwp; /* * Pre-read the loop so as to be more * comprehensible to a terminal user. */ if (intty) preread(); doagain(); } dowhile(v) char **v; { register int status; register bool again = whyles && whyles->w_start == lineloc && whyles->w_fename == 0; v++; /* * Implement prereading here also, taking care not to * evaluate the expression before the loop has been read up * from a terminal. */ if (intty && !again) status = !exp0(&v, 1); else status = !exp(&v); if (*v) bferr("Expression syntax"); if (!again) { register struct whyle *nwp = (struct whyle *) calloc(1, sizeof (*nwp)); nwp->w_start = lineloc; nwp->w_end = 0; nwp->w_next = whyles; whyles = nwp; if (intty) { /* * The tty preread */ preread(); doagain(); return; } } if (status) /* We ain't gonna loop no more, no more! */ toend(); } preread() { register int (*oldint)(); whyles->w_end = -1; if (setintr) oldint = signal(SIGINT, pintr); search(ZBREAK, 0); if (setintr) signal(SIGINT, oldint); whyles->w_end = btell(); } doend() { if (!whyles) bferr("Not in while/foreach"); whyles->w_end = btell(); doagain(); } docontin() { if (!whyles) bferr("Not in while/foreach"); doagain(); } doagain() { /* Repeating a while is simple */ if (whyles->w_fename == 0) { bseek(whyles->w_start); return; } /* * The foreach variable list actually has a spurious word * ")" at the end of the w_fe list. Thus we are at the * of the list if one word beyond this is 0. */ if (!whyles->w_fe[1]) { dobreak(); return; } set(whyles->w_fename, savestr(*whyles->w_fe++)); bseek(whyles->w_start); } dorepeat(v, kp) char **v; struct command *kp; { register int i; register int (*saveintr)(); i = getn(v[1]); if (setintr) saveintr = signal(SIGINT, SIG_IGN); lshift(v, 2); while (i > 0) { if (setintr) signal(SIGINT, pintr); reexecute(kp); --i; } donefds(); if (setintr) signal(SIGINT, saveintr); } doswbrk() { search(ZBRKSW, 0); } srchx(cp) register char *cp; { register struct srch *sp; for (sp = srchn; sp->s_name; sp++) if (eq(cp, sp->s_name)) return (sp->s_value); return (-1); } char Stype; char *Sgoal; /*VARARGS2*/ search(type, level, goal) int type; register int level; char *goal; { char wordbuf[BUFSIZ]; register char *aword = wordbuf; register char *cp; Stype = type; Sgoal = goal; if (type == ZGOTO) bseek(0l); do { if (intty && fseekp == feobp) printf("? "), flush(); aword[0] = 0, getword(aword); switch (srchx(aword)) { case ZELSE: if (level == 0 && type == ZIF) return; break; case ZIF: while (getword(aword)) continue; if ((type == ZIF || type == ZELSE) && eq(aword, "then")) level++; break; case ZENDIF: if (type == ZIF || type == ZELSE) level--; break; case ZFOREACH: case ZWHILE: if (type == ZBREAK) level++; break; case ZEND: if (type == ZBREAK) level--; break; case ZSWITCH: if (type == ZSWITCH || type == ZBRKSW) level++; break; case ZENDSW: if (type == ZSWITCH || type == ZBRKSW) level--; break; case ZLABEL: if (type == ZGOTO && getword(aword) && eq(aword, goal)) level = -1; break; default: if (type != ZGOTO && (type != ZSWITCH || level != 0)) break; if (lastchr(aword) != ':') break; aword[strlen(aword) - 1] = 0; if (type == ZGOTO && eq(aword, goal) || type == ZSWITCH && eq(aword, "default")) level = -1; break; case ZCASE: if (type != ZSWITCH || level != 0) break; getword(aword); if (lastchr(aword) == ':') aword[strlen(aword) - 1] = 0; cp = strip(Dfix1(aword)); if (Gmatch(goal, cp)) level = -1; xfree(cp); break; case ZDEFAULT: if (type == ZSWITCH && level == 0) level = -1; break; } getword(0); } while (level >= 0); } getword(wp) register char *wp; { register int found = 0; register int c, d; c = readc(1); d = 0; do { while (c == ' ' || c == '\t') c = readc(1); if (c < 0) goto past; if (c == '\n') { if (wp) break; return (0); } unreadc(c); found = 1; do { c = readc(1); if (c == '\\' && (c = readc(1)) == '\n') c = ' '; if (any(c, "'\"")) if (d == 0) d = c; else if (d == c) d = 0; if (c < 0) goto past; if (wp) *wp++ = c; } while ((d || c != ' ' && c != '\t') && c != '\n'); } while (wp == 0); unreadc(c); if (found) *--wp = 0; return (found); past: switch (Stype) { case ZIF: bferr("then/endif not found"); case ZELSE: bferr("endif not found"); case ZBRKSW: case ZSWITCH: bferr("endsw not found"); case ZBREAK: bferr("end not found"); case ZGOTO: setname(Sgoal); bferr("label not found"); } /*NOTREACHED*/ } toend() { if (whyles->w_end == 0) { search(ZBREAK, 0); whyles->w_end = btell() - 1; } else bseek(whyles->w_end); wfree(); } wfree() { long o = btell(); while (whyles) { register struct whyle *wp = whyles; register struct whyle *nwp = wp->w_next; if (o >= wp->w_start && (wp->w_end == 0 || o < wp->w_end)) break; if (wp->w_fe0) blkfree(wp->w_fe0); if (wp->w_fename) xfree(wp->w_fename); xfree(wp); whyles = nwp; } } doecho(v) char **v; { echo(' ', v); } doglob(v) char **v; { echo(0, v); flush(); } echo(sep, v) char sep; register char **v; { register char *cp; int (*saveintr)(); if (setintr) saveintr = signal(SIGINT, pintr); v++; if (*v == 0) return; gflag = 0; rscan(v, tglob); if (gflag) { v = glob(v); if (v == 0) bferr("No match"); } else scan(v, trim); while (cp = *v++) { register int c; while (c = *cp++) { if (sep == ' ' && *cp && c == '\\') { c = *cp++; if (c == 'c') { flush(); return; } else if (c == 'n') c = '\n'; else putchar('\\'); } putchar(c | QUOTE); } if (*v) putchar(sep | QUOTE); } if (sep) putchar('\n'); if (setintr) signal(SIGINT, saveintr); if (gargv) blkfree(gargv), gargv = 0; } #ifndef V6 char **environ; dosetenv(v) register char **v; { char *lp = globone(v[2]); setenv(v[1], lp); if (eq(v[1], "PATH")) importpath(lp); xfree(lp); } setenv(name, value) char *name, *value; { register char **ep = environ; register char *cp, *dp; char *blk[2], **oep = ep; for (; *ep; ep++) { for (cp = name, dp = *ep; *cp && *cp == *dp; cp++, dp++) continue; if (*cp != 0 || *dp != '=') continue; cp = strspl("=", value); xfree(*ep); *ep = strspl(name, cp); xfree(cp); scan(ep, trim); return; } blk[0] = strspl(name, "="); blk[1] = 0; environ = blkspl(environ, blk); xfree(oep); setenv(name, value); } doumask(v) register char **v; { register char *cp = v[1]; register int i; if (cp == 0) { i = umask(0); umask(i); printf("%o\n", i); return; } i = 0; while (digit(*cp) && *cp != '8' && *cp != '9') i = i * 8 + *cp++ - '0'; if (*cp || i < 0 || i > 0777) bferr("Improper mask"); umask(i); } #endif
15.688344
85
0.54544
51fd756fd025dd7d8e0b0999daf4002a0ba1d116
3,943
c
C
api/tests/cactusFaceEndTest.c
Robin-Rounthwaite/cactus
3c612779b83b75cb42e08dc143b9cb81c257cf80
[ "MIT-0" ]
1
2020-12-16T07:08:29.000Z
2020-12-16T07:08:29.000Z
api/tests/cactusFaceEndTest.c
Robin-Rounthwaite/cactus
3c612779b83b75cb42e08dc143b9cb81c257cf80
[ "MIT-0" ]
null
null
null
api/tests/cactusFaceEndTest.c
Robin-Rounthwaite/cactus
3c612779b83b75cb42e08dc143b9cb81c257cf80
[ "MIT-0" ]
null
null
null
/* * Copyright (C) 2009-2011 by Benedict Paten (benedictpaten@gmail.com) * * Released under the MIT license, see LICENSE.txt */ #include "cactusFacesTestShared.h" /* * cactusFaceEndTest.c * * Created on: 10-May-2010 * Author: benedictpaten */ static void testTearDown(CuTest* testCase) { cactusFacesTestSharedTeardown(testCase); } static void testSetup(CuTest* testCase) { cactusFacesTestSharedSetup(testCase); } void testFaceEnd_construct(CuTest* testCase) { testSetup(testCase); assert(testCase != NULL); testTearDown(testCase); } void testFaceEnd_getTopNode(CuTest* testCase) { testSetup(testCase); FaceEnd *faceEnd1 = face_getFaceEndForTopNode(face, topCap1); CuAssertTrue(testCase, faceEnd_getTopNode(faceEnd1) == cap_getPositiveOrientation(topCap1)); FaceEnd *faceEnd2 = face_getFaceEndForTopNode(face, topCap2); CuAssertTrue(testCase, faceEnd_getTopNode(faceEnd2) == cap_getPositiveOrientation(topCap2)); FaceEnd *faceEnd3 = face_getFaceEndForTopNode(face, topCap3); CuAssertTrue(testCase, faceEnd_getTopNode(faceEnd3) == cap_getPositiveOrientation(topCap3)); FaceEnd *faceEnd4 = face_getFaceEndForTopNode(face, topCap4); CuAssertTrue(testCase, faceEnd_getTopNode(faceEnd4) == cap_getPositiveOrientation(topCap4)); testTearDown(testCase); } void testFaceEnd_getFace(CuTest* testCase) { testSetup(testCase); FaceEnd *faceEnd1 = face_getFaceEndForTopNode(face, topCap1); CuAssertTrue(testCase, faceEnd_getFace(faceEnd1) == face); FaceEnd *faceEnd2 = face_getFaceEndForTopNode(face, topCap2); CuAssertTrue(testCase, faceEnd_getFace(faceEnd2) == face); testTearDown(testCase); } void testFaceEnd_getNumberOfBottomNodes(CuTest* testCase) { testSetup(testCase); FaceEnd *faceEnd1 = face_getFaceEndForTopNode(face, topCap1); CuAssertTrue(testCase, faceEnd_getNumberOfBottomNodes(faceEnd1) == 1); FaceEnd *faceEnd2 = face_getFaceEndForTopNode(face, topCap2); CuAssertTrue(testCase, faceEnd_getNumberOfBottomNodes(faceEnd2) == 1); FaceEnd *faceEnd3 = face_getFaceEndForTopNode(face, topCap3); CuAssertTrue(testCase, faceEnd_getNumberOfBottomNodes(faceEnd3) == 1); FaceEnd *faceEnd4 = face_getFaceEndForTopNode(face, topCap4); CuAssertTrue(testCase, faceEnd_getNumberOfBottomNodes(faceEnd4) == 1); testTearDown(testCase); } void testFaceEnd_bottomNodeIterator(CuTest* testCase) { testSetup(testCase); FaceEnd *faceEnd1 = face_getFaceEndForTopNode(face, topCap1); CuAssertTrue(testCase, faceEnd_getNumberOfBottomNodes(faceEnd1) == 1); FaceEnd_BottomNodeIterator *iterator = faceEnd_getBottomNodeIterator(faceEnd1); CuAssertTrue(testCase, faceEnd_getNextBottomNode(iterator) == cap_getPositiveOrientation(bottomCap1)); CuAssertTrue(testCase, faceEnd_getNextBottomNode(iterator) == NULL); CuAssertTrue(testCase, faceEnd_getNextBottomNode(iterator) == NULL); FaceEnd_BottomNodeIterator *iterator2 = faceEnd_copyBottomNodeIterator(iterator); CuAssertTrue(testCase, faceEnd_getPreviousBottomNode(iterator) == cap_getPositiveOrientation(bottomCap1)); CuAssertTrue(testCase, faceEnd_getPreviousBottomNode(iterator) == NULL); CuAssertTrue(testCase, faceEnd_getNextBottomNode(iterator) == cap_getPositiveOrientation(bottomCap1)); //Test copied iterator CuAssertTrue(testCase, faceEnd_getNextBottomNode(iterator2) == NULL); CuAssertTrue(testCase, faceEnd_getPreviousBottomNode(iterator2) == cap_getPositiveOrientation(bottomCap1)); CuAssertTrue(testCase, faceEnd_getPreviousBottomNode(iterator2) == NULL); faceEnd_destructBottomNodeIterator(iterator); faceEnd_destructBottomNodeIterator(iterator2); testTearDown(testCase); } CuSuite* cactusFaceEndTestSuite(void) { CuSuite* suite = CuSuiteNew(); SUITE_ADD_TEST(suite, testFaceEnd_getTopNode); SUITE_ADD_TEST(suite, testFaceEnd_getFace); SUITE_ADD_TEST(suite, testFaceEnd_getNumberOfBottomNodes); SUITE_ADD_TEST(suite, testFaceEnd_bottomNodeIterator); SUITE_ADD_TEST(suite, testFaceEnd_construct); return suite; }
37.552381
108
0.81055
79fb3d4d7a5dccf57480c44de1f09e690c78c602
7,920
h
C
Modules/PolyData/include/irtkPolyDataSmoothing.h
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
3
2018-10-04T19:32:36.000Z
2021-09-02T07:37:30.000Z
Modules/PolyData/include/irtkPolyDataSmoothing.h
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
null
null
null
Modules/PolyData/include/irtkPolyDataSmoothing.h
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
4
2016-03-17T02:55:00.000Z
2018-02-03T05:40:05.000Z
/* The Image Registration Toolkit (IRTK) * * Copyright 2008-2015 Imperial College London * * 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 IRTKPOLYDATASMOOTHING_H_ #define IRTKPOLYDATASMOOTHING_H_ #include <irtkPolyDataFilter.h> class vtkDataArray; namespace irtk { namespace polydata { class irtkEdgeTable; /** * Smooth scalars and/or points of triangulated surface mesh */ class irtkPolyDataSmoothing : public irtkPolyDataFilter { irtkObjectMacro(irtkPolyDataSmoothing); // --------------------------------------------------------------------------- // Types public: /// Enumeration of smoothing kernel functions enum WeightFunction { Combinatorial, ///< Uniform node weights InverseDistance, ///< Inverse node distance Gaussian, ///< Gaussian node weights AnisotropicGaussian ///< Anisotropic Gaussian node weights }; /// List of point data array names typedef vector<string> ArrayNames; /// Vector of point data arrays to be smoothed typedef vector<vtkSmartPointer<vtkDataArray> > DataArrays; // --------------------------------------------------------------------------- // Attributes protected: /// Edge table of input mesh irtkPublicAggregateMacro(const irtkEdgeTable, EdgeTable); /// Whether edge table is to be destroyed by this filter irtkPublicAttributeMacro(bool, EdgeTableOwner); /// Number of smoothing iterations irtkPublicAttributeMacro(int, NumberOfIterations); /// Relaxation factor irtkPublicAttributeMacro(double, Lambda); /// Smoothing kernel parameter /// /// In case of a Gaussian smoothing kernel, if the sigma value is negative, /// the standard deviation of the Gaussian kernel is set to the average /// edge length times the absolute value of \c _Sigma. If _Sigma is zero, /// the average edge length is used as standard deviation. The _Sigma attribute /// is set to the actual used standard deviation after the filter execution. /// /// In case of the inverse distance weighting, the _Sigma value is added to /// the edge length before computing the inverse value. irtkPublicAttributeMacro(double, Sigma); /// Smoothing kernel parameter in direction of maximum curvature /// /// \note The direction of maximum principle curvature is orthogonal to the /// direction in which the surface is most bended! It is the direction /// with the most variance, i.e., along ridges, not orthogonal to these. /// /// This parameter is only used by the anisotropic Gaussian kernel. /// By default, i.e., when _Sigma2 = 0, the standard deviation along the /// direction of maximum change is half the standard deviation along the /// direction of minimum change. Hence, the surface points or data values are /// smoothed less in the direction of maximum change (i.e., maximum curvature). /// If the sigma value is negative, the standard deviation is set to the /// average edge length times the absolute value of \c _Sigma2. /// /// When an array of local geometry tensors is used instead of the direction /// of minimum and/or maximum change, the default is to use an isotropic /// Gaussian kernel in the local coordinate system defined by the tensor. /// In this case the axes of the local coordinate system are expected to be /// scaled anisotropically as in case of the curvature tensor, for example. irtkPublicAttributeMacro(double, MaximumDirectionSigma); /// Smoothing kernel function irtkPublicAttributeMacro(WeightFunction, Weighting); /// Name of input point data array with local geometry tensor used for anisotropic smoothing /// /// For example, the local curvature tensors can be computed using /// irtkPolyDataCurvature and used for anisotropic Gaussian smoothing. /// The input point data array is then named irtkPolyDataCurvature::TENSOR. irtkPublicAttributeMacro(string, GeometryTensorName); /// Name of input point data array with direction along which to smooth less /// \note This array is only used if no _GeometryTensorName is specified. irtkPublicAttributeMacro(string, MinimumDirectionName); /// Name of input point data array with direction along which to smooth more /// \note This array is only used if no _GeometryTensorName is specified. irtkPublicAttributeMacro(string, MaximumDirectionName); /// Whether to average values of adjacent nodes only or to /// also include the node's values themselves in the average /// /// \note In case of an InverseDistance node weighting, the values of the /// node itself are only included in the average if _Sigma > .0. irtkPublicAttributeMacro(bool, AdjacentValuesOnly); /// Whether to smooth the node positions, i.e., input geometry irtkPublicAttributeMacro(bool, SmoothPoints); /// Names of input point data arrays to be smoothed irtkPublicAttributeMacro(ArrayNames, SmoothArrays); /// Input point data arrays to be smoothed irtkAttributeMacro(DataArrays, InputArrays); /// Output point data arrays irtkAttributeMacro(DataArrays, OutputArrays); /// Copy attributes of this class from another instance void Copy(const irtkPolyDataSmoothing &); // --------------------------------------------------------------------------- // Construction/Destruction public: /// Constructor irtkPolyDataSmoothing(); /// Copy constructor irtkPolyDataSmoothing(const irtkPolyDataSmoothing &); /// Assignment operator irtkPolyDataSmoothing &operator =(const irtkPolyDataSmoothing &); /// Destructor virtual ~irtkPolyDataSmoothing(); /// Add named point data array to list of arrays to be smoothed void SmoothArray(const char *); // --------------------------------------------------------------------------- // Execution protected: /// Initialize filter after input and parameters are set virtual void Initialize(); /// Execute filter virtual void Execute(); /// Finalize filter execution virtual void Finalize(); // --------------------------------------------------------------------------- // Alternative VTK-like interface public: /// Set number of smoothing iterations irtkSetMacro(NumberOfIterations, int); /// Get number of smoothing iterations irtkGetMacro(NumberOfIterations, int); /// Set relaxation factor irtkSetMacro(Lambda, double); /// Get relaxation factor irtkGetMacro(Lambda, double); /// Set smoothing kernel standard deviation irtkSetMacro(Sigma, double); /// Get smoothing kernel standard deviation irtkGetMacro(Sigma, double); /// Set smoothing kernel standard deviation in direction of maximum curvature irtkSetMacro(MaximumDirectionSigma, double); /// Get smoothing kernel standard deviation in direction of maximum curvature irtkGetMacro(MaximumDirectionSigma, double); /// Enable/disable averaging of adjacent node values only irtkOnOffMacro(AdjacentValuesOnly); /// Enable/disable smoothing of node positions irtkOnOffMacro(SmoothPoints); }; //////////////////////////////////////////////////////////////////////////////// // Inline definitions //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- inline void irtkPolyDataSmoothing::SmoothArray(const char *name) { _SmoothArrays.push_back(name); } } } // namespace irtk::polydata #endif
34.137931
94
0.684848
edfb06a39168101f277ab4674336da9851f2d3fd
290
h
C
Lab12/Project1/Project1/Visitor.h
Amihaeseisergiu/OOP
b23401e18b5eb2cf6bcd656c122f068e55f70167
[ "Apache-2.0" ]
null
null
null
Lab12/Project1/Project1/Visitor.h
Amihaeseisergiu/OOP
b23401e18b5eb2cf6bcd656c122f068e55f70167
[ "Apache-2.0" ]
null
null
null
Lab12/Project1/Project1/Visitor.h
Amihaeseisergiu/OOP
b23401e18b5eb2cf6bcd656c122f068e55f70167
[ "Apache-2.0" ]
null
null
null
#pragma once using namespace std; class Lamaie; class Mar; class Grapefruit; class Portocala; class Visitor { public: virtual void visit(Portocala& orange) = 0; virtual void visit(Lamaie& lemon) = 0; virtual void visit(Grapefruit& grape) = 0; virtual void visit(Mar& apple) = 0; };
15.263158
43
0.724138
7916683af37e01364709bb5fea76db4bf4bb3278
1,735
h
C
Samples/AllJoyn/Common/Scenario1WinRTComponent/SecureInterfaceEventArgs.h
MartinRusk/Windows-universal-samples
338c5362c26d02db8a7bb20d0b9cb4c0571406df
[ "MIT" ]
null
null
null
Samples/AllJoyn/Common/Scenario1WinRTComponent/SecureInterfaceEventArgs.h
MartinRusk/Windows-universal-samples
338c5362c26d02db8a7bb20d0b9cb4c0571406df
[ "MIT" ]
null
null
null
Samples/AllJoyn/Common/Scenario1WinRTComponent/SecureInterfaceEventArgs.h
MartinRusk/Windows-universal-samples
338c5362c26d02db8a7bb20d0b9cb4c0571406df
[ "MIT" ]
null
null
null
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* //----------------------------------------------------------------------------- // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // // For more information, see: http://go.microsoft.com/fwlink/?LinkID=623246 // </auto-generated> //----------------------------------------------------------------------------- #pragma once namespace com { namespace microsoft { namespace Samples { namespace SecureInterface { // Signals public ref class SecureInterfaceTextSentReceivedEventArgs sealed { public: property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } void set(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ value) { m_messageInfo = value; } } property Platform::String^ Message { Platform::String^ get() { return m_interfaceMemberMessage; } internal: void set(_In_ Platform::String^ value) { m_interfaceMemberMessage = value; } } private: Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; Platform::String^ m_interfaceMemberMessage; }; } } } }
34.7
103
0.579827
256fa87bc57aeb75dc4df554ec0e2f3c9f331663
8,359
c
C
chacha20-avx2.c
MerryMage/mmCrypto
a9dee281bd4e2fe1b329f358d78d20ca7fde7304
[ "CC0-1.0" ]
2
2017-01-13T05:35:18.000Z
2017-01-15T01:49:12.000Z
chacha20-avx2.c
MerryMage/mmCrypto
a9dee281bd4e2fe1b329f358d78d20ca7fde7304
[ "CC0-1.0" ]
null
null
null
chacha20-avx2.c
MerryMage/mmCrypto
a9dee281bd4e2fe1b329f358d78d20ca7fde7304
[ "CC0-1.0" ]
null
null
null
/* This file is part of the mmCrypto project. * * Written in 2017 by MerryMage * * To the extent possible under law, the author(s) have dedicated all * copyright and related and neighboring rights to this software to * the public domain worldwide. This software is distributed without * any warranty. * * You should have received a copy of the CC0 Public Domain Dedication * along with this software. * If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. */ /* Literature References: * * Daniel J. Bernstein, "ChaCha, a variant of Salsa20", * <https://cr.yp.to/chacha/chacha-20080128.pdf>. * * M. Goll, S. Gueron, "Vectorization on ChaCha Stream Cipher", IEEE * Proceedings of 11th International Conference on Information * Technology: New Generations (ITNG 2014), 612-615 (2014). */ #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <x86intrin.h> #include "chacha20-avx2.h" #ifdef _MSC_VER #define forceinline __forceinline #else #define forceinline __attribute__((always_inline)) inline #endif forceinline static __m256i add_pi32(const __m256i a, const __m256i b) { return _mm256_add_epi32(a, b); } forceinline static __m256i xor_pi32(const __m256i a, const __m256i b) { return _mm256_xor_si256(a, b); } /* We special-case the rotation of 8 and 16 because pshufb is faster. */ forceinline static __m256i rotl_pi32(const __m256i value, size_t count) { count %= 32; if (count == 0) { return value; } if (count == 8) { const __m256i shuf = _mm256_set_epi8(14, 13, 12, 15, 10, 9, 8, 11, 6, 5, 4, 7, 2, 1, 0, 3, 14, 13, 12, 15, 10, 9, 8, 11, 6, 5, 4, 7, 2, 1, 0, 3); return _mm256_shuffle_epi8(value, shuf); } if (count == 16) { const __m256i shuf = _mm256_set_epi8(13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2, 13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2); return _mm256_shuffle_epi8(value, shuf); } __m256i hi = _mm256_slli_epi32(value, count); __m256i lo = _mm256_srli_epi32(value, 32-count); return _mm256_or_si256(hi, lo); } forceinline static __m256i rotl_vector(const __m256i vector, size_t count) { if (count % 4 == 0) return vector; if (count % 4 == 1) return _mm256_shuffle_epi32(vector, _MM_SHUFFLE(0,3,2,1)); if (count % 4 == 2) return _mm256_shuffle_epi32(vector, _MM_SHUFFLE(1,0,3,2)); if (count % 4 == 3) return _mm256_shuffle_epi32(vector, _MM_SHUFFLE(2,1,0,3)); abort(); } /* This is the core function. It performs 8 quarter-rounds on two matices in parallel. * {a, b, c, d} make up 2 matrices of 16x32-bit state words, like so: * a = {{ x0, x1, x2, x3},{ x0, x1, x2, x3}} * b = {{ x4, x5, x6, x7},{ x4, x5, x6, x7}} * c = {{ x8, x9,x10,x11},{ x8, x9,x10,x11}} * d = {{x12,x13,x14,x15},{x12,x13,x14,x15}} * i.e.: the upper and lower 128-bits of each vector belong to two different matrices. */ forceinline static void chacha20_double_round(__m256i *pa, __m256i *pb, __m256i *pc, __m256i *pd) { __m256i a = *pa, b = *pb, c = *pc, d = *pd; /* Column Rounds */ a = add_pi32(a, b); d = rotl_pi32(xor_pi32(d, a), 16); c = add_pi32(c, d); b = rotl_pi32(xor_pi32(b, c), 12); a = add_pi32(a, b); d = rotl_pi32(xor_pi32(d, a), 8); c = add_pi32(c, d); b = rotl_pi32(xor_pi32(b, c), 7); /* Diagonal Rounds */ b = rotl_vector(b, 1); c = rotl_vector(c, 2); d = rotl_vector(d, 3); a = add_pi32(a, b); d = rotl_pi32(xor_pi32(d, a), 16); c = add_pi32(c, d); b = rotl_pi32(xor_pi32(b, c), 12); a = add_pi32(a, b); d = rotl_pi32(xor_pi32(d, a), 8); c = add_pi32(c, d); b = rotl_pi32(xor_pi32(b, c), 7); b = rotl_vector(b, 3); c = rotl_vector(c, 2); d = rotl_vector(d, 1); *pa = a; *pb = b; *pc = c; *pd = d; } static __m128i load_i128_from_bytes(const void* bytes) { return _mm_loadu_si128((__m128i*)bytes); } static __m256i load_i256_from_bytes(const void* bytes) { return _mm256_loadu_si256((__m256i*)bytes); } static void store_i256_to_bytes(const void* bytes, __m256i value) { _mm256_storeu_si256((__m256i*)bytes, value); } static __m256i load_i256_with_nonce_and_counter( const uint8_t nonce[MMCRYPTO_CHACHA20_NONCE_BYTES], const uint64_t counter ) { union { __m256i vector; struct { uint64_t counter0; uint8_t nonce0[MMCRYPTO_CHACHA20_NONCE_BYTES]; uint64_t counter1; uint8_t nonce1[MMCRYPTO_CHACHA20_NONCE_BYTES]; } s; } u; u.s.counter0 = counter; u.s.counter1 = counter + 1; memcpy(u.s.nonce0, nonce, MMCRYPTO_CHACHA20_NONCE_BYTES); memcpy(u.s.nonce1, nonce, MMCRYPTO_CHACHA20_NONCE_BYTES); return u.vector; } void mmcrypto_chacha20( uint8_t *out, const uint8_t *in, size_t in_length, const uint8_t key[MMCRYPTO_CHACHA20_KEY_BYTES], const uint8_t nonce[MMCRYPTO_CHACHA20_NONCE_BYTES], const uint64_t counter ) { const __m256i im0 = _mm256_broadcastsi128_si256(load_i128_from_bytes("expand 32-byte k")); const __m256i im1 = _mm256_broadcastsi128_si256(load_i128_from_bytes(key)); const __m256i im2 = _mm256_broadcastsi128_si256(load_i128_from_bytes(key+16)); __m256i im3 = load_i256_with_nonce_and_counter(nonce, counter); for (; in_length >= 128; in_length -= 128, in += 128, out += 128) { __m256i v0 = im0, v1 = im1, v2 = im2, v3 = im3; /* 20 rounds = 10 doublerounds */ for (unsigned i = 0; i < 10; i++) { chacha20_double_round(&v0, &v1, &v2, &v3); } v0 = add_pi32(v0, im0); v1 = add_pi32(v1, im1); v2 = add_pi32(v2, im2); v3 = add_pi32(v3, im3); /* Permute keystream into byte-order */ __m256i f0 = _mm256_permute2x128_si256(v0, v1, _MM_SHUFFLE(0,2,0,0)); __m256i f1 = _mm256_permute2x128_si256(v2, v3, _MM_SHUFFLE(0,2,0,0)); __m256i f2 = _mm256_permute2x128_si256(v0, v1, _MM_SHUFFLE(0,3,0,1)); __m256i f3 = _mm256_permute2x128_si256(v2, v3, _MM_SHUFFLE(0,3,0,1)); /* xor the keystream with plaintext */ f0 = xor_pi32(f0, load_i256_from_bytes(in)); f1 = xor_pi32(f1, load_i256_from_bytes(in + 32)); f2 = xor_pi32(f2, load_i256_from_bytes(in + 64)); f3 = xor_pi32(f3, load_i256_from_bytes(in + 96)); store_i256_to_bytes(out, f0); store_i256_to_bytes(out + 32, f1); store_i256_to_bytes(out + 64, f2); store_i256_to_bytes(out + 96, f3); /* Increment counter */ im3 = _mm256_add_epi64(im3, _mm256_set_epi64x(0,2,0,2)); } if (in_length > 0) { __m256i v0 = im0, v1 = im1, v2 = im2, v3 = im3; /* 20 rounds = 10 doublerounds */ for (unsigned i = 0; i < 10; i++) { chacha20_double_round(&v0, &v1, &v2, &v3); } v0 = add_pi32(v0, im0); v1 = add_pi32(v1, im1); v2 = add_pi32(v2, im2); v3 = add_pi32(v3, im3); /* Permute keystream into byte-order */ __m256i f0 = _mm256_permute2x128_si256(v0, v1, _MM_SHUFFLE(0,2,0,0)); __m256i f1 = _mm256_permute2x128_si256(v2, v3, _MM_SHUFFLE(0,2,0,0)); __m256i f2 = _mm256_permute2x128_si256(v0, v1, _MM_SHUFFLE(0,3,0,1)); __m256i f3 = _mm256_permute2x128_si256(v2, v3, _MM_SHUFFLE(0,3,0,1)); uint8_t f[128] = {}; store_i256_to_bytes(f, f0); store_i256_to_bytes(f + 32, f1); store_i256_to_bytes(f + 64, f2); store_i256_to_bytes(f + 96, f3); for (size_t i = 0; i < in_length; i++) { out[i] = f[i] ^ in[i]; } } }
36.502183
99
0.575428
259fb406c5b3f9a0f421024d4a85a78f1cb4dc09
1,397
h
C
src/gausskernel/cbb/bbox/bbox.h
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
360
2020-06-30T14:47:34.000Z
2022-03-31T15:21:53.000Z
src/gausskernel/cbb/bbox/bbox.h
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
4
2020-06-30T15:09:16.000Z
2020-07-14T06:20:03.000Z
src/gausskernel/cbb/bbox/bbox.h
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
133
2020-06-30T14:47:36.000Z
2022-03-25T15:29:00.000Z
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * 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 PSL v2 for more details. * --------------------------------------------------------------------------------------- * * bbox.h * * IDENTIFICATION * src/include/bbox.h * * --------------------------------------------------------------------------------------- */ #ifndef __BBOX_H__ #define __BBOX_H__ #include "bbox_types.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #define BBOX_FAST_COMP_RATIO 1 #define BBOX_BEST_COMP_RATIO 9 extern s32 BBOX_SetCoredumpPath(const char* pszPath); extern s32 BBOX_SetCoreFileCount(s32 iCount); extern s32 BBOX_TakeSnapShot(char* file_name); extern s32 BBOX_CreateCoredump(char* file_name); extern s32 BBOX_AddBlackListAddress(void* address, u64 len); extern s32 BBOX_RmvBlackListAddress(void* address); extern s32 BBOX_SetCoreCompRatio(u32 uiRatio); #ifdef __cplusplus } #endif /* __cplusplus */ #endif
26.358491
90
0.647817
9fc5982d9ff45d3f12fda42a05bcc01cde76056d
370
h
C
include/Sauce/Common.h
bitsauce/NibbleSauce3D
79792388eaad659c241a292c470ee9fa6413d354
[ "MIT" ]
null
null
null
include/Sauce/Common.h
bitsauce/NibbleSauce3D
79792388eaad659c241a292c470ee9fa6413d354
[ "MIT" ]
null
null
null
include/Sauce/Common.h
bitsauce/NibbleSauce3D
79792388eaad659c241a292c470ee9fa6413d354
[ "MIT" ]
1
2021-04-25T09:58:46.000Z
2021-04-25T09:58:46.000Z
// Copyright (C) 2011-2020 // Made by Marcus "Bitsauce" Vergara // Distributed under the MIT license #pragma once #include <Sauce/Common/Engine.h> #include <Sauce/Common/Exception.h> #include <Sauce/Common/SauceObject.h> #include <Sauce/Common/SceneObject.h> #include <Sauce/Common/Event.h> #include <Sauce/Common/ResourceManager.h> #include <Sauce/Common/tinyxml2.h>
26.428571
41
0.762162
c735988cea8feb367c5d9a89a0bbabd4f1ccc79a
1,622
c
C
ports/xDMS/source/maketbl.c
phmullins/beos
ab4317f49aed404fe7091e2b24bda381628f17c3
[ "MIT" ]
null
null
null
ports/xDMS/source/maketbl.c
phmullins/beos
ab4317f49aed404fe7091e2b24bda381628f17c3
[ "MIT" ]
null
null
null
ports/xDMS/source/maketbl.c
phmullins/beos
ab4317f49aed404fe7091e2b24bda381628f17c3
[ "MIT" ]
null
null
null
/* * xDMS v1.3 - Portable DMS archive unpacker - Public Domain * Written by Andre Rodrigues de la Rocha <adlroc@usa.net> * * Makes decoding table for Heavy LZH decompression * From UNIX LHA made by Masaru Oki * */ #include "cdata.h" #include "maketbl.h" static SHORT c; static USHORT n, tblsiz, len, depth, maxdepth, avail; static USHORT codeword, bit, *tbl, TabErr; static UCHAR *blen; static USHORT mktbl(void); USHORT make_table(USHORT nchar, UCHAR bitlen[],USHORT tablebits, USHORT table[]){ n = avail = nchar; blen = bitlen; tbl = table; tblsiz = (USHORT) (1U << tablebits); bit = (USHORT) (tblsiz / 2); maxdepth = (USHORT)(tablebits + 1); depth = len = 1; c = -1; codeword = 0; TabErr = 0; mktbl(); /* left subtree */ if (TabErr) return TabErr; mktbl(); /* right subtree */ if (TabErr) return TabErr; if (codeword != tblsiz) return 5; return 0; } static USHORT mktbl(void){ USHORT i=0; if (TabErr) return 0; if (len == depth) { while (++c < n) if (blen[c] == len) { i = codeword; codeword += bit; if (codeword > tblsiz) { TabErr=1; return 0; } while (i < codeword) tbl[i++] = (USHORT)c; return (USHORT)c; } c = -1; len++; bit >>= 1; } depth++; if (depth < maxdepth) { mktbl(); mktbl(); } else if (depth > 32) { TabErr = 2; return 0; } else { if ((i = avail++) >= 2 * n - 1) { TabErr = 3; return 0; } left[i] = mktbl(); right[i] = mktbl(); if (codeword >= tblsiz) { TabErr = 4; return 0; } if (depth == maxdepth) tbl[codeword++] = i; } depth--; return i; }
17.44086
81
0.576449
c78f6e817ba5f1b35bce324f2c88b9709291bd58
998
h
C
HiClass_SDK/Classes/Mine/Controller/MyScore/View/HICIntegralTaskHeadView.h
jia-hisense/HiClasss_SDK
24e10c8fc46d66c332c132f3026d67dba56e9bd3
[ "MIT" ]
null
null
null
HiClass_SDK/Classes/Mine/Controller/MyScore/View/HICIntegralTaskHeadView.h
jia-hisense/HiClasss_SDK
24e10c8fc46d66c332c132f3026d67dba56e9bd3
[ "MIT" ]
null
null
null
HiClass_SDK/Classes/Mine/Controller/MyScore/View/HICIntegralTaskHeadView.h
jia-hisense/HiClasss_SDK
24e10c8fc46d66c332c132f3026d67dba56e9bd3
[ "MIT" ]
null
null
null
// // HICIntegralTaskHeadView.h // HiClass // // Created by 聚好看 on 2021/11/24. // Copyright © 2021 hisense. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN typedef void(^IntegralRankPushBlock)(void); typedef void(^IntegralSubsidiaryPushBlock)(void); @interface HICIntegralTaskHeadView : UIView ///排行榜按钮 - (IBAction)btnScoreRankAction:(id)sender; @property (weak, nonatomic) IBOutlet UILabel *lbScoreRank; ///积分label @property (weak, nonatomic) IBOutlet UILabel *lbAllScore; ///积分明细 - (IBAction)btnScoreDetailsAction:(id)sender; @property (weak, nonatomic) IBOutlet UILabel *lbIntegralSubsidiary; @property (copy, nonatomic) IntegralRankPushBlock integralRankPushBlock; @property (copy, nonatomic) IntegralSubsidiaryPushBlock integralSubsidiaryPushBlock; @property (weak, nonatomic) IBOutlet UIButton *btnScoreRank; @property (weak, nonatomic) IBOutlet UIView *line; @property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftDistence; @end NS_ASSUME_NONNULL_END
29.352941
84
0.792585
d5834a62318199b749373e3233a3672e01e9e867
222
h
C
tools/snex_playground/test_files/basic/auto_return_type.h
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
tools/snex_playground/test_files/basic/auto_return_type.h
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
tools/snex_playground/test_files/basic/auto_return_type.h
Matt-Dub/HISE
ae2dd1653e1c8d749a9088edcd573de6252b0b96
[ "Intel" ]
null
null
null
/* BEGIN_TEST_DATA f: main ret: int args: int input: 12 output: 12 error: "" filename: "basics/auto_return_type" END_TEST_DATA */ int main(int input) { auto x = Math.abs((double)input); return x; }
10.090909
37
0.635135
c513cd9632048545ac885cb0ca697208e2f4b315
633
h
C
Source/spaceinvaders/Public/SIPlayerController.h
iestevez/spaceinvaders
bc90609d8435e0636698914e61bf84da2bc358ae
[ "CC-BY-3.0" ]
null
null
null
Source/spaceinvaders/Public/SIPlayerController.h
iestevez/spaceinvaders
bc90609d8435e0636698914e61bf84da2bc358ae
[ "CC-BY-3.0" ]
null
null
null
Source/spaceinvaders/Public/SIPlayerController.h
iestevez/spaceinvaders
bc90609d8435e0636698914e61bf84da2bc358ae
[ "CC-BY-3.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/PlayerController.h" #include "Kismet/GameplayStatics.h" #include "Engine/World.h" #include "SIPlayerController.generated.h" // This class derives from APlayerController // to set the camera tagged as MainCamera as the view target UCLASS() class SPACEINVADERS_API ASIPlayerController : public APlayerController { GENERATED_BODY() public: ASIPlayerController(); virtual void BeginPlay() override; private: UPROPERTY() TArray<class AActor*> m_cameras; FName m_mainCameraTag; };
20.419355
78
0.781991
7b0d5962a60d6ff117d07b429a70f8ea68db1e4c
373
c
C
testdata/gcc-6.3.0/gcc/testsuite/gcc.c-torture/compile/pr34856.c
mewbak/cc-1
d673e9b70d4d716fd96e81a4d7dc9d532c6c0391
[ "BSD-3-Clause" ]
178
2016-03-03T12:31:18.000Z
2021-11-05T22:36:55.000Z
testdata/gcc-6.3.0/gcc/testsuite/gcc.c-torture/compile/pr34856.c
mewbak/cc-1
d673e9b70d4d716fd96e81a4d7dc9d532c6c0391
[ "BSD-3-Clause" ]
106
2016-03-03T13:11:42.000Z
2018-09-27T13:01:51.000Z
testdata/gcc-6.3.0/gcc/testsuite/gcc.c-torture/compile/pr34856.c
mewbak/cc-1
d673e9b70d4d716fd96e81a4d7dc9d532c6c0391
[ "BSD-3-Clause" ]
21
2016-03-03T14:21:36.000Z
2020-04-09T01:19:17.000Z
/* { dg-options "-msse" { target { i?86-*-* x86_64-*-* } } } */ #undef __vector #define __vector __attribute__((vector_size(16) )) typedef __vector signed char qword; typedef __vector unsigned int VU32; extern short g[192 +16]; void f(qword); void f1 (unsigned ctr) { VU32 pin; pin = (VU32){(__SIZE_TYPE__)&g[16]}; do { f((qword)pin); ctr--; } while(ctr); }
19.631579
63
0.635389
f21abb25216dec1cb5002785955a9d85b820908a
2,620
h
C
src/objects/light.h
hardware/ObjectViewer
718922e00a6f3e83510e6091f7630ac3c0e5066b
[ "MIT" ]
52
2015-02-26T04:00:19.000Z
2021-04-25T03:18:25.000Z
src/objects/light.h
hardware/ObjectViewer
718922e00a6f3e83510e6091f7630ac3c0e5066b
[ "MIT" ]
2
2017-03-15T02:11:06.000Z
2017-12-04T12:26:06.000Z
src/objects/light.h
hardware/ObjectViewer
718922e00a6f3e83510e6091f7630ac3c0e5066b
[ "MIT" ]
21
2015-09-09T13:59:02.000Z
2021-04-25T03:18:27.000Z
#ifndef LIGHT_H #define LIGHT_H #include <string> #include <QColor> #include <QVector3D> #include <QOpenGLShaderProgram> #include <QSharedPointer> using namespace std; typedef QSharedPointer<QOpenGLShaderProgram> QOpenGLShaderProgramPtr; class Light { public: enum LightType { PointLight, DirectionalLight, SpotLight }; Light(const string& name); ~Light(); void setType(LightType type); LightType type() const; void setIntensity(float intensity); void setUniqueColor(const QColor& color); void setUniqueColor(float r, float g, float b); void setColors(const QColor& ambientColor, const QColor& diffuseColor, const QColor& specularColor); void setAmbientColor(const QColor& color); void setAmbientColor(float r, float g, float b); void setDiffuseColor(const QColor& color); void setDiffuseColor(float r, float g, float b); void setSpecularColor(const QColor& color); void setSpecularColor(float r, float g, float b); const QColor& ambientColor() const; const QColor& diffuseColor() const; const QColor& specularColor() const; void setDirection(const QVector3D& direction); void setDirection(float x, float y, float z); const QVector3D& direction() const; void setPosition(const QVector3D& position); void setPosition(float x, float y, float z); const QVector3D& position() const; void setAttenuation(float constantFactor, float linearFactor, float quadraticFactor); void setConstantAttenuation(float constantFactor); void setLinearAttenuation(float linearFactor); void setQuadraticAttenuation(float quadraticFactor); float constantAttenuation() const; float linearAttenuation() const; float quadraticAttenuation() const; void setSpotFalloff(float falloff); void setSpotInnerAngle(float innerAngle); void setSpotOuterAngle(float outerAngle); float spotFallOff() const; float spotInnerAngle() const; float spotOuterAngle() const; void render(const QOpenGLShaderProgramPtr& shader, const QMatrix4x4& viewMatrix); private: string m_name; LightType m_type; QVector3D m_position; QVector3D m_direction; QColor m_ambientColor; QColor m_diffuseColor; QColor m_specularColor; float m_constantAttenuation; float m_linearAttenuation; float m_quadraticAttenuation; float m_spotFalloff; float m_spotInnerAngle; float m_spotOuterAngle; float m_intensity; }; #endif // LIGHT_H
24.485981
85
0.703817
00fb2b6e9d941b07a2519bc691d43e5059747a74
470
h
C
tests/unit_C/org_fudgemsg_proto_tests_ExternalEnum.h
OpenGamma/Fudge-Proto
ce6e68ad1debd9eb621a352d747c1e0c7c7440fd
[ "Apache-2.0" ]
null
null
null
tests/unit_C/org_fudgemsg_proto_tests_ExternalEnum.h
OpenGamma/Fudge-Proto
ce6e68ad1debd9eb621a352d747c1e0c7c7440fd
[ "Apache-2.0" ]
null
null
null
tests/unit_C/org_fudgemsg_proto_tests_ExternalEnum.h
OpenGamma/Fudge-Proto
ce6e68ad1debd9eb621a352d747c1e0c7c7440fd
[ "Apache-2.0" ]
3
2015-08-23T04:52:59.000Z
2019-05-08T05:50:24.000Z
#ifndef __INC_ORG_FUDGEMSG_PROTO_TESTS_EXTERNALENUM_H #define __INC_ORG_FUDGEMSG_PROTO_TESTS_EXTERNALENUM_H enum _org_fudgemsg_proto_tests_ExternalEnum { FOO, BAR }; FudgeString org_fudgemsg_proto_tests_ExternalEnum_toFudgeEncoding (enum _org_fudgemsg_proto_tests_ExternalEnum value); enum _org_fudgemsg_proto_tests_ExternalEnum org_fudgemsg_proto_tests_ExternalEnum_fromFudgeEncoding (FudgeString); #endif /* ifndef INC_ORG_FUDGEMSG_PROTO_TESTS_EXTERNALENUM_H */
39.166667
118
0.9
7a612a97bea1df081ad502d2d4c0822c9eefc43b
945
h
C
qqtw/qqheaders7.2/QQGrayTipsMsgTabModule.h
onezens/QQTweak
04b9efd1d93eba8ef8fec5cf9a20276637765777
[ "MIT" ]
5
2018-02-20T14:24:17.000Z
2020-08-06T09:31:21.000Z
qqtw/qqheaders7.2/QQGrayTipsMsgTabModule.h
onezens/QQTweak
04b9efd1d93eba8ef8fec5cf9a20276637765777
[ "MIT" ]
1
2020-06-10T07:49:16.000Z
2020-06-12T02:08:35.000Z
qqtw/qqheaders7.2/QQGrayTipsMsgTabModule.h
onezens/SmartQQ
04b9efd1d93eba8ef8fec5cf9a20276637765777
[ "MIT" ]
null
null
null
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" #import "QQGrayTipsProcessDelegate.h" @class NSString; @interface QQGrayTipsMsgTabModule : NSObject <QQGrayTipsProcessDelegate> { } - (_Bool)_isGrayTipContentEqual:(id)arg1 msg2:(id)arg2; - (_Bool)_isGrayTipExtInfoEqul:(id)arg1 msg2:(id)arg2; - (id)_queryGrayTipWithTipId:(long long)arg1 tipKey:(id)arg2 uin:(id)arg3 uinTpye:(unsigned long long)arg4; - (void)deleteGrayTipWithTipId:(long long)arg1 tipKey:(id)arg2 uin:(id)arg3 uinTpye:(unsigned long long)arg4; - (void)modifyGrayTipWithParam:(id)arg1; - (void)processWithGrayTipsParam:(id)arg1 delegate:(id)arg2; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
29.53125
109
0.757672
a39c358c4f85161b869d89042b322858ac17f217
1,516
h
C
VenEcon2/ShinobiCharts.framework/Headers/SChartBubbleSeriesStyle.h
jammastergirish/VenezuelaEcon-iOS
507a2757045b803af39c856dd85b4197c3cd01d7
[ "MIT" ]
1
2019-06-10T15:47:47.000Z
2019-06-10T15:47:47.000Z
VenEcon2/ShinobiCharts.framework/Headers/SChartBubbleSeriesStyle.h
jammastergirish/VenezuelaEcon-iOS
507a2757045b803af39c856dd85b4197c3cd01d7
[ "MIT" ]
null
null
null
VenEcon2/ShinobiCharts.framework/Headers/SChartBubbleSeriesStyle.h
jammastergirish/VenezuelaEcon-iOS
507a2757045b803af39c856dd85b4197c3cd01d7
[ "MIT" ]
null
null
null
// // SChartBubbleSeriesStyle.h // ShinobiControls_Source // // Copyright (c) 2013 Scott Logic Ltd. All rights reserved. // // #import "SChartPointSeriesStyle.h" @class SChartBubblePointStyle; @interface SChartBubbleSeriesStyle : SChartPointSeriesStyle /** Manages the appearance of unselected points/bubbles on a bubble series. The default settings of the style are inherited from the chart theme. You can tweak the appearance of the series by modifying the style. */ - (SChartBubblePointStyle*) pointStyle; /** Sets the unselected point/bubble style object for this bubble series style. @param style The new style object to use for the point style. @see style */ - (void) setPointStyle:(SChartBubblePointStyle*)pointStyle; /** Manages the appearance of selected points/bubbles on a bubble series. Style settings in this object will be applied when the point is marked as selected. The default settings of the style are inherited from the chart theme. You can tweak the appearance of the series by modifying the style. */ - (SChartBubblePointStyle*) selectedPointStyle; /** Sets the selected point/bubble style object for this bubble series style. @param style The new style object to use for the point style. @see style */ - (void) setSelectedPointStyle:(SChartBubblePointStyle*) selectedPointStyle; /** Supplements this style object by taking styles this object doesn't have, from the argument, `style` */ - (void)supplementStyleFromStyle:(SChartBubbleSeriesStyle *)style; @end
32.255319
138
0.771108
c7bccce8d5ab1f7e1f04fa07fff1ee8be5ad4801
1,034
c
C
C/2.3.1progt.c
spewspew/taocp
d340dd308ae7e27a60d5a8ccfca0295f25c397a9
[ "0BSD" ]
2
2018-11-14T13:51:08.000Z
2020-11-22T19:29:26.000Z
C/2.3.1progt.c
spewspew/taocp
d340dd308ae7e27a60d5a8ccfca0295f25c397a9
[ "0BSD" ]
null
null
null
C/2.3.1progt.c
spewspew/taocp
d340dd308ae7e27a60d5a8ccfca0295f25c397a9
[ "0BSD" ]
null
null
null
#include <u.h> #include <libc.h> enum{ MAXRECUR = 1000 }; typedef struct Node Node; struct Node { Node *left, *right; int val; }; #define push(p) \ if(sp == ep) \ exits("Stack overflow"); \ else \ *sp++ = (p) #define pop(p) (p) = *--sp /* Program T */ void inorder(Node *p, void(*visit)(Node*)) { static Node *a[MAXRECUR], **sp, **ep; sp = a; ep = sp + MAXRECUR; for(;;) { if(p == nil) { if(sp == a) return; pop(p); visit(p); p = p->right; continue; } push(p); p = p->left; } } Node* insert(Node *r, Node *n) { if(r == nil) return n; if(n->val > r->val) r->right = insert(r->right, n); else if (n->val < r->val) r->left = insert(r->left, n); return r; } void printnode(Node *r) { print("Value is %d.\n", r->val); } Node pool[100]; void main(void) { Node *a, *r; srand(time(nil)); r = nil; for(a = pool; a < pool + nelem(pool); a++) { a->val = lnrand(1000); print("Inserting %d.\n", a->val); r = insert(r, a); } print("\nSorted:\n"); inorder(r, printnode); }
13.088608
45
0.531915
841cf0b9de6c06c52af1594f906cc5bf340798b2
929
h
C
src/engine/ui/Image.h
maunovaha/cpp_tic_tac_toe
add37c4954551490235a68f359761a781b7ecfe1
[ "MIT" ]
2
2019-12-06T17:06:27.000Z
2019-12-10T12:08:52.000Z
src/engine/ui/Image.h
maunovaha/cpp_tic_tac_toe
add37c4954551490235a68f359761a781b7ecfe1
[ "MIT" ]
null
null
null
src/engine/ui/Image.h
maunovaha/cpp_tic_tac_toe
add37c4954551490235a68f359761a781b7ecfe1
[ "MIT" ]
null
null
null
#pragma once #include "../core/Surface.h" #include "../core/Texture.h" #include "../core/Component.h" #include "../core/AppContext.h" #include "../math/Rect.h" #include "../math/Point.h" #include <string> #include <memory> namespace engine::ui { class Image : public core::Component { public: Image(const core::Surface& surface) : texture_{core::AppContext::getRenderer() , surface} {} Image(const std::string& path, std::unique_ptr<math::Rect> clip = std::unique_ptr<math::Rect>{nullptr}) : texture_{core::AppContext::getRenderer(), path} , clip_{std::move(clip)} {} void onRender() const override; int getWidth() const; int getHeight() const; math::Point getSize() const; math::Point getCenter() const; math::Rect getRect() const; math::Rect getWorldRect() const; private: core::Texture texture_; std::unique_ptr<math::Rect> clip_; }; }
26.542857
82
0.643703
27bea9b19f3530bae6cc4635a845ef151ba1d56b
1,411
h
C
src/DesktopCore/Network/Agents/FileServerAgent.h
lurume84/blink-desktop
d6d01f8dc461edd22192a521fbd49669bfa8f684
[ "MIT" ]
75
2019-03-08T14:15:49.000Z
2022-01-05T17:30:43.000Z
src/DesktopCore/Network/Agents/FileServerAgent.h
lurume84/blink-desktop
d6d01f8dc461edd22192a521fbd49669bfa8f684
[ "MIT" ]
55
2019-02-17T01:34:12.000Z
2022-02-26T21:07:33.000Z
src/DesktopCore/Network/Agents/FileServerAgent.h
lurume84/blink-desktop
d6d01f8dc461edd22192a521fbd49669bfa8f684
[ "MIT" ]
20
2019-05-21T19:02:31.000Z
2022-03-28T07:29:28.000Z
#pragma once #include "../../System/Services/ApplicationDataService.h" #include "../../System/Services/IniFileService.h" #include "../../Model/IAgent.h" #include <string> #include <map> #include <mutex> namespace httplib { class Server; struct Request; struct Response; class ContentReader; } namespace web { namespace http { namespace experimental { namespace listener { class http_listener; } } } } namespace desktop { namespace core { namespace agent { class FileServerAgent : public model::IAgent { public: FileServerAgent(std::unique_ptr<service::ApplicationDataService> applicationService = std::make_unique<service::ApplicationDataService>(), std::unique_ptr<service::IniFileService> iniFileService = std::make_unique<service::IniFileService>()); ~FileServerAgent(); void handlePOST(const httplib::Request& req, httplib::Response& res, const httplib::ContentReader &content_reader); void handleGET(const httplib::Request& req, httplib::Response& res) const; void handleGETVersion(const httplib::Request& req, httplib::Response& res) const; private: std::unique_ptr<service::ApplicationDataService> m_applicationService; std::unique_ptr<service::IniFileService> m_iniFileService; std::string m_endpoint; std::string m_folder; std::mutex m_mutex; std::unique_ptr<httplib::Server> m_server; }; }}}
32.068182
140
0.722183
b461f3e63b34c33bf34fcc62bdd31fa6a06b5589
2,480
h
C
Etherlab_EtherCAT_Master/master/sdo_entry.h
ShellAlbert/3-axies-robot-arm
7963137012e838f4a7c3675d06448ed7003ad901
[ "Apache-2.0" ]
1
2021-09-13T03:05:45.000Z
2021-09-13T03:05:45.000Z
Etherlab_EtherCAT_Master/master/sdo_entry.h
ShellAlbert/3-axies-robot-arm
7963137012e838f4a7c3675d06448ed7003ad901
[ "Apache-2.0" ]
41
2020-06-18T03:28:31.000Z
2020-09-25T05:09:08.000Z
Etherlab_EtherCAT_Master/master/sdo_entry.h
ShellAlbert/3-axies-robot-arm
7963137012e838f4a7c3675d06448ed7003ad901
[ "Apache-2.0" ]
1
2021-09-13T03:05:47.000Z
2021-09-13T03:05:47.000Z
/****************************************************************************** * * $Id$ * * Copyright (C) 2006-2008 Florian Pose, Ingenieurgemeinschaft IgH * * This file is part of the IgH EtherCAT Master. * * The IgH EtherCAT Master is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version 2, as * published by the Free Software Foundation. * * The IgH EtherCAT Master 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 the IgH EtherCAT Master; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * --- * * The license mentioned above concerns the source code only. Using the * EtherCAT technology and brand is only permitted in compliance with the * industrial property and similar rights of Beckhoff Automation GmbH. * *****************************************************************************/ /** \file EtherCAT CANopen SDO entry structure. */ /*****************************************************************************/ #ifndef __EC_SDO_ENTRY_H__ #define __EC_SDO_ENTRY_H__ #include <linux/list.h> #include <linux/kobject.h> #include "globals.h" /*****************************************************************************/ struct ec_sdo; typedef struct ec_sdo ec_sdo_t; /**< \see ec_sdo. */ /*****************************************************************************/ /** CANopen SDO entry. */ typedef struct { struct list_head list; /**< List item. */ ec_sdo_t *sdo; /**< Parent SDO. */ uint8_t subindex; /**< Subindex. */ uint16_t data_type; /**< Data type. */ uint16_t bit_length; /**< Data size in bit. */ uint8_t read_access[EC_SDO_ENTRY_ACCESS_COUNT]; /**< Read access. */ uint8_t write_access[EC_SDO_ENTRY_ACCESS_COUNT]; /**< Write access. */ char *description; /**< Description. */ } ec_sdo_entry_t; /*****************************************************************************/ void ec_sdo_entry_init(ec_sdo_entry_t *, ec_sdo_t *, uint8_t); void ec_sdo_entry_clear(ec_sdo_entry_t *); /*****************************************************************************/ #endif
33.972603
79
0.549194
b40b03f4131a0b7f36559098f1193b2a0c469007
2,641
h
C
ns-allinone-2.35/xgraph-12.2/copyright.h
nitishk017/ns2project
f037b796ff10300ffe0422580be5855c37d0b140
[ "MIT" ]
1
2021-04-21T06:39:42.000Z
2021-04-21T06:39:42.000Z
ns-allinone-2.35/xgraph-12.2/copyright.h
nitishk017/ns2project
f037b796ff10300ffe0422580be5855c37d0b140
[ "MIT" ]
null
null
null
ns-allinone-2.35/xgraph-12.2/copyright.h
nitishk017/ns2project
f037b796ff10300ffe0422580be5855c37d0b140
[ "MIT" ]
null
null
null
/* * xgraph - program to graphically display numerical data * * David Harrison * University of California, Berkeley * 1989 * * Animation, Differentiation by Paul Walker * NCSA and University of Illinois at Urbana Champaign Dept. of Physics * * Copyright (c) 1988, 1989, Regents of the University of California. * All rights reserved. * * Use and copying of this software and preparation of derivative works * based upon this software are permitted. However, any distribution of * this software or derivative works must include the above copyright * notice. * * This software is made available AS IS, and neither the Electronics * Research Laboratory or the University of California make any * warranty about the software, its performance or its conformity to * any specification. * Animation and differentiation routines were added by Paul Walker, NCSA and UIUC Dept of Physics. The following copyright and disclaimer applies to these parts of the code only. UNIVERSITY OF ILLINOIS (UI), NATIONAL CENTER FOR SUPERCOMPUTING APPLICATIONS (NCSA), Software Distribution Policy for Copyrighted Software The above mentioned modifications to XGraph made with the authors consent are copyrighted, but available without fee for education, academic research and non-commercial purposes. The modifications are copyrighted in the name of the UI, and ownership of the modifications remains with the UI. Users may distribute the binary and source code to third parties provided that the copyright notice and this statement appears on all copies and that no charge is made for such copies. Any entity wishing to integrate all or part of the source code into a product for commercial use or resale, should contact the University of Illinois, c/o NCSA, to negotiate an appropriate license for such commercial use. UI MAKES NO REPRESENTATIONS ABOUT THE SUITABILITY OF THE SOFTWARE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY. THE UI SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY THE USER OF THIS SOFTWARE. The software may have been developed under agreements between the UI and the Federal Government which entitle the Government to certain rights. By copying this program, you, the user, agree to abide by the copyright conditions and understandings with respect to any software which is marked with a copyright notice. Send all comments about the modifications to Paul Walker, pwalker@ncsa.uiuc.edu * */ #ifndef _RIGHTS_ #define _RIGHTS_ static char copyright[] = "Copyright (c) 1989, Regents of the University of California. All rights reserved."; #endif /* _RIGHTS_ */
40.015152
111
0.788338
fe78fdde2d36bdedb40b084a601f482dcf98e6f4
5,434
h
C
pwiz_tools/BiblioSpec/src/RefSpectrum.h
austinkeller/pwiz
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
[ "Apache-2.0" ]
null
null
null
pwiz_tools/BiblioSpec/src/RefSpectrum.h
austinkeller/pwiz
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
[ "Apache-2.0" ]
null
null
null
pwiz_tools/BiblioSpec/src/RefSpectrum.h
austinkeller/pwiz
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
[ "Apache-2.0" ]
null
null
null
// // $Id$ // // // 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. // /* * RefSpectrum class is an extension of Spectrum. These are spectra * that are stored in a library. Associated with them are a peptide * sequence, modifications for the sequence, an ID number, an annotation * to indicate the quality of the spectrum, and the number of copies this * spectrum was chosen from if it is in a filtered library. * * Functions for sorting (comparing) by ID or by ion (charge+seq+mods) */ /******************************************************************** * Since the library is now stored in sqlite3 format, there are some * changes based on that. ********************************************************************/ #ifndef REFSPECTRUM_H #define REFSPECTRUM_H #include <vector> #include <string> #include <algorithm> #include <functional> #include <iostream> #include <stdexcept> #include <assert.h> #include "Verbosity.h" #include "Spectrum.h" #include "SmallMolMetadata.h" using namespace std; namespace BiblioSpec { class RefSpectrum : public Spectrum { protected: int charge; // a spectrum with an id must have only one charge int copies; int libID; //when multiple libraries searched, index of BiblioLibrary table int libSpecID;//id number in RefSpectra table string pepSeq; string modsPepSeq; string prevAA; string nextAA; SmallMolMetadata smallMolMetadata_; // Small molecule stuff double circShift_; // amount by which peaks have been circularly shifted // 0 if observed spectrum double score_; int scoreType_; public: RefSpectrum(); RefSpectrum(const RefSpectrum& rs); RefSpectrum(const Spectrum& s); RefSpectrum* newDecoy(double shiftDelta, bool shiftRawSpectrum) const; ~RefSpectrum(); RefSpectrum& operator=(const Spectrum& s); RefSpectrum& operator=(const RefSpectrum& s); void clear(); // setters void setCharge(int charge); void addCharge(int charge); // override Spectrum to force 1 charge state void setSeq(const char * newSeq); void setMods(const char * newMods); void setLibID(int id); void setLibSpecID( int specID); void setCopies(int dups); void setPrevAA(const char * pAA); void setNextAA(const char * nAA); void setScore(double score); void setScoreType(int scoreType); void setMoleculeName(const char * name); void setChemicalFormula(const char * formula); void setPrecursorAdduct(const char * precursorAdduct); void setInchiKey(const char * inchikey); void setotherKeys(const char * ids); //getters int getCharge() const; string getSeq() const; string getMods() const; int getLibID() const; int getLibSpecID() const; int getCopies() const; string getPrevAA() const; string getNextAA() const; double getCircShift() const; double getScore() const; int getScoreType() const; string getMoleculeName() const; string getChemicalFormula() const; string getAdduct() const; string getInchiKey() const; string getotherKeys() const; // Sets result string to a tab seperated concatenation of molecule name, formula, // inchikey, otherkeys and adduct when this is non-proteomic (has no mods). // Sets result empty otherwise. void getSmallMoleculeIonID(string &result) const; // make this private and only allow decoys as copy of refs? // create null spectrum by doing a circular shift of peaks void circularShift(double deltaMz, bool shiftRawPeaks); }; //sort by both charge and sequence struct compRefSpecIon : public binary_function<RefSpectrum, RefSpectrum, bool> { bool operator()(RefSpectrum s1, RefSpectrum s2) { if( s1.getCharge() == s2.getCharge() ) { return (s1.getSeq() < s2.getSeq()); } //else return ( s1.getCharge() < s2.getCharge() ); } }; //sort by both charge and sequence struct compRefSpecPtrIon : public binary_function<RefSpectrum*, RefSpectrum*, bool>{ bool operator()(RefSpectrum* s1, RefSpectrum* s2) { if( s1->getCharge() == s2->getCharge() ) { if (s1->getSeq() == s2->getSeq()) { return ( s1->getMods() < s2->getMods() ); } else { return (s1->getSeq() < s2->getSeq()); } } //else return ( s1->getCharge() < s2->getCharge() ); } }; struct compRefSpecPtrId : public binary_function<RefSpectrum*, RefSpectrum*, bool> { bool operator()(RefSpectrum* s1, RefSpectrum* s2) {return s1->getLibSpecID() < s2->getLibSpecID();} }; } // namespace #endif //REFSPECTRUM_H /* * Local Variables: * mode: c * c-basic-offset: 4 * End: */
30.52809
103
0.656238
706d7d02d91555bb7ede1c93343cd676b32b62d5
1,264
h
C
src/carl-logging/Sink.h
sjunges/carl
5013c31c035990d9912a6265944e7d4add4c378b
[ "MIT" ]
29
2015-05-19T12:17:16.000Z
2021-03-05T17:53:00.000Z
src/carl-logging/Sink.h
sjunges/carl
5013c31c035990d9912a6265944e7d4add4c378b
[ "MIT" ]
36
2016-10-26T12:47:11.000Z
2021-03-03T15:19:38.000Z
src/carl-logging/Sink.h
sjunges/carl
5013c31c035990d9912a6265944e7d4add4c378b
[ "MIT" ]
16
2015-05-27T07:35:19.000Z
2021-03-05T17:53:08.000Z
#pragma once #include <fstream> #include <ostream> namespace carl::logging { /** * Base class for a logging sink. It only provides an interface to access some std::ostream. */ class Sink { public: /** * Abstract logging interface. * The intended usage is to write any log output to the output stream returned by this function. * @return Output stream. */ virtual std::ostream& log() noexcept = 0; }; /** * Logging sink that wraps an arbitrary `std::ostream`. * It is meant to be used for streams like `std::cout` or `std::cerr`. */ class StreamSink final: public Sink { /// Output stream. std::ostream os; public: /** * Create a StreamSink from some output stream. * @param _os Output stream. */ explicit StreamSink(std::ostream& _os): os(_os.rdbuf()) {} std::ostream& log() noexcept override { return os; } }; /** * Logging sink for file output. */ class FileSink: public Sink { /// File output stream. std::ofstream os; public: virtual ~FileSink() = default; /** * Create a FileSink that logs to the specified file. * The file is truncated upon construction. * @param filename */ explicit FileSink(const std::string& filename): os(filename, std::ios::out) {} std::ostream& log() noexcept override { return os; } }; }
24.307692
97
0.68038
f2727ebf81bd26a04428af919ef8fbed25f5f44a
3,465
h
C
dev/kd_tree.h
22427/oflibs
9e84ad98835799584f88d117bf06116cedd68068
[ "MIT" ]
2
2018-09-03T13:40:39.000Z
2020-08-25T15:16:48.000Z
dev/kd_tree.h
22427/oflibs
9e84ad98835799584f88d117bf06116cedd68068
[ "MIT" ]
null
null
null
dev/kd_tree.h
22427/oflibs
9e84ad98835799584f88d117bf06116cedd68068
[ "MIT" ]
1
2020-08-25T15:16:52.000Z
2020-08-25T15:16:52.000Z
#pragma once #include <map> #include <vector> #include <set> #include <algorithm> #include "dll.h" namespace ofl { template<unsigned int D=3, typename T=float> class kdNode { uint m_item; uint m_stride; kdNode<D,T>* m_left; kdNode<D,T>* m_right; uint m_axis; T m_value; T calc_dist2(const T* from, const T* to) { T sqd = 0 ; for(uint i = 0 ; i < D;i++) { const auto q = from[i]-to[i]; sqd += q*q; } return sqd; } public: kdNode(std::vector<uint>& data, const T* base, uint stage, uint stride = D) :m_left(nullptr), m_right(nullptr), m_axis(stage) { m_axis = stage; m_stride = stride; // a leaf node! if(data.size() == 1) { m_item = data.back(); return; } // find median std::sort(data.begin(),data.end(), [base,stage,stride](const uint a, const uint b) { return base[a*stride+stage] < base[b*stride+stage]; }); uint median_index = static_cast<unsigned int>(data.size())/2u; T value = base[data[median_index]*m_stride+stage]; std::vector<uint> left(data.size()/2+data.size()%2); std::vector<uint> right(data.size()/2); for(const uint& i : data) { if(base[i*m_stride+stage] <= value) left.push_back(i); else right.push_back(i); } m_left = new kdNode<D,T>(left,base,(stage+1)%D); m_right = new kdNode<D,T>(right,base,(stage+1)%D); } int find_nearest(const T* to, const T* base,T& dist, int curr) { bool is_left = to[m_axis] < m_value; if(m_left||m_right) // not a leave { // go left or right if(is_left) curr = m_left->find_nearest(to,base,dist,curr); else curr = m_right->find_nearest(to,base,dist,curr); // test if we have to check the other side as well if(dist >= (to[m_axis]-m_value)*(to[m_axis]-m_value)) { if(!is_left) curr = m_left->find_nearest(to,base,dist,curr); else curr = m_right->find_nearest(to,base,dist,curr); } } else // a leave { auto md = calc_dist2(to,base+m_item*m_stride); if(md < dist) { dist = md; curr = static_cast<int>(m_item); } } return curr; } }; /** * @brief The kDTree class is a simple kDTree */ template<typename A=int,unsigned int D =3,typename T=float> class OFL_DLL_PUBLIC kDTree { protected: kdNode<D,T>* m_root; const T* m_base; const A* m_attached; public: void clear() { delete m_root; } void generate(const T*base,const A* attached, uint cnt,uint stride=D) { m_base = base; m_attached = attached; std::vector<uint> v(cnt) ; std::iota (std::begin(v), std::end(v), 0); m_root = new kdNode<D,T>(v,base,0,stride); } /** * @brief find_nearest returns the closest element in this kDTree to a given * point to * @param to The location of the point. * @param distance output for the actual distance * @return the closest Element. */ const A& find_nearest(const T* to, T* distance = nullptr) const { T d; int id = m_root->find_nearest(to,m_base,d,-1); if(distance) *distance = d; return m_attached[id]; } }; class kDTree3D : public kDTree<int,3,float> { public: void clear() { delete m_root; } void generate(const float* base, uint cnt) { m_base = base; std::vector<uint> v(cnt) ; std::iota (std::begin(v), std::end(v), 0); m_root = new kdNode<3,float>(v,base,0); } int find_nearest(const float* to, float* distance = nullptr) const { float d = -1; int id = m_root->find_nearest(to,m_base,d,-1); if(distance) *distance = d; return id; } }; }
18.934426
84
0.630303
cc90a51288b6cb545636edd1c488ff418e2e9b44
338
h
C
Trade Matching Engine/solution 1/common.h
kishoredbn/Object-Oriented-Pros
fc69eaeda90776b7e72a39c4f32229cb4fb8729d
[ "MIT" ]
null
null
null
Trade Matching Engine/solution 1/common.h
kishoredbn/Object-Oriented-Pros
fc69eaeda90776b7e72a39c4f32229cb4fb8729d
[ "MIT" ]
null
null
null
Trade Matching Engine/solution 1/common.h
kishoredbn/Object-Oriented-Pros
fc69eaeda90776b7e72a39c4f32229cb4fb8729d
[ "MIT" ]
1
2021-03-11T15:40:07.000Z
2021-03-11T15:40:07.000Z
#pragma once #include <iostream> #include <string> #include <sstream> #include <variant> #include <memory> #include <vector> #include <unordered_map> #include <tuple> #include <algorithm> #include <queue> #include "order_attribute.h" #include "order_trade.h" #include "order_factory.h" #include "trade_engine.h" #include "order_input.h"
18.777778
28
0.751479
62c4baa9dcc300ea4b39655ed5de59aa8f1fd6bf
3,314
h
C
src/cmd/cmd_set.h
AlexeyBukin/StaRT
dfe7dbe2109c1e981fc88456aedb6491f4357dc9
[ "MIT" ]
2
2020-11-09T13:23:13.000Z
2020-12-09T04:08:28.000Z
src/cmd/cmd_set.h
AlexeyBukin/StaRT
dfe7dbe2109c1e981fc88456aedb6491f4357dc9
[ "MIT" ]
null
null
null
src/cmd/cmd_set.h
AlexeyBukin/StaRT
dfe7dbe2109c1e981fc88456aedb6491f4357dc9
[ "MIT" ]
4
2020-10-31T14:15:08.000Z
2020-12-14T19:36:08.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* cmd_set.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rtacos <rtacos@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/10 02:49:57 by kcharla #+# #+# */ /* Updated: 2020/12/14 17:18:22 by rtacos ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef CMD_SET_H # define CMD_SET_H # include "srv_types.h" # include "rt_types.h" # include "cmd_types.h" /* ** cmd/set */ t_msg cmd_set(t_rt *rt, t_parser *parser); /* ** cmd/set/cmd_set_sphere */ t_msg cmd_set_sphere(t_rt *rt, t_parser *parser, t_obj *dest); int cmd_set_sphere_default(t_rt *rt, t_parser *parser); /* ** cmd/set/cmd_set_plane */ t_msg cmd_set_plane(t_rt *rt, t_parser *parser, t_obj *dest); int cmd_set_plane_default(t_rt *rt, t_parser *parser); /* ** cmd/set/cmd_set_material */ int cmd_set_material_default(t_rt *rt, t_parser *parser); /* ** cmd/set/cmd_set_cylinder */ t_msg cmd_set_cylinder(t_rt *rt, t_parser *parser, t_obj *dest); int cmd_set_cylinder_default(t_rt *rt, t_parser *parser); /* ** cmd/set/cmd_set_cone */ t_msg cmd_set_cone(t_rt *rt, t_parser *parser, t_obj *dest); int cmd_set_cone_default(t_rt *rt, t_parser *parser); /* ** cmd/set/cmd_set_group */ t_msg cmd_set_group(t_rt *rt, t_parser *parser, t_obj *dest); int cmd_set_group_default(t_rt *rt, t_parser *parser); /* ** cmd/set/cmd_set_material */ t_msg cmd_set_material(t_rt *rt, t_parser *parser); /* ** cmd/set/cmd_set_camera */ t_msg cmd_set_camera(t_rt *rt, t_parser *parser, t_obj *dest); /* ** cmd/set/cmd_set_tools */ int cmd_set_radius(t_parser *parser); /* ** cmd/set/cmd_set_transform_part */ int cmd_read_transform_part(t_parser *parser); /* ** cmd/set/cmd_set_object_attributes */ int cmd_set_obj_visibility(t_parser *parser); int cmd_set_obj_name(t_rt *rt, t_parser *parser); int cmd_set_obj_grp(t_rt *rt, t_parser *parser); int cmd_set_obj_mat(t_rt *rt, t_parser *parser); /* ** cmd/set/cmd_set_txr */ t_msg cmd_set_txr(t_rt *rt, t_parser *parser); /* ** cmd/utils/cmd_set_obj TODO move to set */ int cmd_set_prepare_obj(t_parser *parser, t_obj *src); t_msg cmd_set_type(t_rt *rt, t_parser *parser); t_msg cmd_set_error(t_parser *parser, char *message); t_msg cmd_set_object(t_rt *rt, t_parser *parser); t_msg cmd_set_mat_to_scn(t_parser *parser, t_mat *dest); t_msg cmd_set_light(t_rt *rt, t_parser *parser, t_obj *dest); t_msg cmd_set_copy(t_rt *rt, t_parser *parser, t_obj *obj); int cmd_read_txr_type(t_parser *parser); int cmd_read_txr_filename(t_parser *parser); t_msg cmd_set_txr_to_scn(t_parser *parser, t_txr *dest); #endif
27.163934
80
0.538021
00fe82dd5246b6048642578ec1a20b5eacc6a017
2,134
h
C
libsrc/msgsocket.h
JulianaYuan/socketMsgQue
c365ace168cb4324b952cee1df723993c580bd00
[ "Apache-2.0" ]
null
null
null
libsrc/msgsocket.h
JulianaYuan/socketMsgQue
c365ace168cb4324b952cee1df723993c580bd00
[ "Apache-2.0" ]
null
null
null
libsrc/msgsocket.h
JulianaYuan/socketMsgQue
c365ace168cb4324b952cee1df723993c580bd00
[ "Apache-2.0" ]
null
null
null
#ifndef _MSGSOCKET_H_ #define _MSGSOCKET_H_ #include<sys/types.h> #include<sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include<stdio.h> #include<sys/un.h> #include<unistd.h> #include<stdlib.h> #include <stddef.h> #include <pthread.h> #include <signal.h> #include <errno.h> #include <string.h> #define SERVER_NAME "@server_socket" #define MAXLINE 8192//212994//8192//2147479552//9612 #define QUE_MAX 4096 enum SKCMD { CMD_MSG_GET_CREATE, CMD_MSG_GET_NOCRTE, CMD_MSG_SEND_WAIT, CMD_MSG_SEND_NOWT, CMD_MSG_RECV_WAIT_BYTYPE, CMD_MSG_RECV_NOWT_BYTYPE, CMD_MSG_RECV_WAIT_EXTYPE, CMD_MSG_RECV_NOWT_EXTYPE, /*CMD_MSG_CTRL_REMOVE, CMD_MSG_CTRL_GETATTR, CMD_MSG_CTRL_SETATTR,*/ }; enum QUE_STS { NORMAL, //que is not full, or que is not exist FULLED, //answer que is fulled, EMPTY,//que is empty EXISTED,//que is exist NOTEXIST,//que is exist REMOVED, ERROR,//que is exist }; typedef struct socketMsg_s { long int msgType; int size; char msg[MAXLINE]; }socketMsg; typedef struct socketData_s { int key; int msqId; enum SKCMD cmd; enum QUE_STS sts; socketMsg msg; }socketData,*psocketData; int server_create(const char* svnm); int writeToSocket(int fd ,socketData *skDat); int readFromSocket(int fd ,socketData *skDat); int clientMsgGetCreate(int key,bool &exist); int clientMsgGetNoCrte(int key,bool &exist); #if 0 int clientSetMsgqueAttr(int __msqid, struct msqid_ds *__buf); int clientGetMsgqueAttr(int __msqid, struct msqid_ds *__buf); int clientMsgCtrlRemv(int msqid); #endif int clientMsgRcvNowaitBytype(int msqid,long int __msgtyp,void *msg,size_t __msgsz,bool noerror); int clientMsgRcvNowaitExtype(int msqid,long int __msgtyp,void *msg,size_t __msgsz,bool noerror); int clientMsgRcvWaitBytype(int msqid,long int __msgtyp,void *msg,size_t __msgsz,bool noerror); int clientMsgRcvWaitExtype(int msqid,long int __msgtyp,void *msg,size_t __msgsz,bool noerror); int clientMsgSendWaitExt(int msqid,const void *msg,size_t __msgsz); int clientMsgSendNoWaitExt(int msqid,const void *msg,size_t __msgsz); void debugprintf(socketMsg *msg); #endif
24.25
96
0.766167
13d4290d5a73b7a51ed6499efd7bb9114eac8eb2
48,989
c
C
Firmware/keil_standard_f103_20200910/RL/USB/Drivers/usbh_stm32f10x.c
SmartElec/OfflineSWD
b176b29bee137bf3a73aabb54d97cbd4be803121
[ "Apache-2.0" ]
142
2020-10-10T03:18:32.000Z
2022-03-31T02:14:49.000Z
Firmware/keil_standard_f103_20200910/RL/USB/Drivers/usbh_stm32f10x.c
SmartElec/OfflineSWD
b176b29bee137bf3a73aabb54d97cbd4be803121
[ "Apache-2.0" ]
2
2020-10-19T13:45:25.000Z
2020-10-28T10:19:14.000Z
Firmware/keil_standard_f103_20200910/RL/USB/Drivers/usbh_stm32f10x.c
SmartElec/OfflineSWD
b176b29bee137bf3a73aabb54d97cbd4be803121
[ "Apache-2.0" ]
61
2020-10-10T03:18:37.000Z
2022-03-31T02:14:54.000Z
/*------------------------------------------------------------------------------ * RL-ARM - USB *------------------------------------------------------------------------------ * Name: usbh_stm32f10x.c * Purpose: Full/Low-speed Host STM32F10x Driver module * Rev.: V4.70 *------------------------------------------------------------------------------ * This code is part of the RealView Run-Time Library. * Copyright (c) 2004-2013 KEIL - An ARM Company. All rights reserved. *----------------------------------------------------------------------------*/ #include <RTL.h> #include <rl_usb.h> #include "usbh_stm32f10x.h" #include <stm32f10x_cl.h> #include <string.h> /************************** Host Controller Driver Structure ******************/ USBH_HCD usbh0_hcd = { /* Host Controller Driver structure */ USBH_STM32_Get_Capabilities, /* Get Host Ctrl Driver capabilities */ USBH_STM32_Delay_ms, /* Delay in ms */ USBH_STM32_Pins_Config, /* Config/Unconfig pins */ USBH_STM32_Init, /* Init/Uninit Host Controller */ USBH_STM32_Port_Power, /* On/Off Port Power */ USBH_STM32_Port_Reset, /* Reset port */ USBH_STM32_Get_Connect, /* Get port conn/disconn status */ USBH_STM32_Get_Speed, /* Get port enumerated speed */ USBH_STM32_EP_Add, /* Add Endpoint */ USBH_STM32_EP_Config, /* (Re)Configure Endpoint */ USBH_STM32_EP_Remove, /* Remove Endpoint */ USBH_STM32_URB_Submit, /* Submit USB Block Request */ USBH_STM32_URB_Cancel /* Cancel USB Block Request */ }; /************************** Driver Settings ***********************************/ //-------- <<< Use Configuration Wizard in Context Menu >>> -------------------- // <o0> Size of memory used by the OTG_FS USB Host Controller <1-1048576> // <i> This is a size of memory (in bytes) that the USB Host Controller // <i> will use for USB communication data. #define USBH_STM32_SZ_MPOOL 0x00000234 /************************** Variable and Memory Definitons ********************/ #define MAX_TIMEOUT_COUNT 100 #define DEBOUNCE_500ms 500 #define OTG_MAX_CH 8 #define OTG OTG_FS static U32 *OTG_DFIFO[OTG_MAX_CH] = { OTG_FS_DFIFO0, OTG_FS_DFIFO1, OTG_FS_DFIFO2, OTG_FS_DFIFO3, OTG_FS_DFIFO4, OTG_FS_DFIFO5, OTG_FS_DFIFO6, OTG_FS_DFIFO7 }; /* Reserve memory for memory pool */ U32 USBH_MPOOL[(USBH_STM32_SZ_MPOOL+3)>>2]; static BOOL HW_Accessing = { __FALSE }; static USBH_URB *CHURB [OTG_MAX_CH] = { 0 }; static U8 cntInterval [OTG_MAX_CH] = { 0 }; static U8 cntIntervalMax [OTG_MAX_CH] = { 0 }; static U16 cntDebounce = { 0 }; static U32 calDelay = 0 ; static U32 Port_Discon_Evt = { 0 }; static U32 Port_Speed = { 0 }; static U32 Port_Con = { 0 }; /************************** Local Module Functions ****************************/ /***----------------------- DMA Functions ----------------------------------***/ /*------------------------- USBH_STM32_DMA_Enable ------------------------------ * * Enable the DMA so it can be used for USB * * Parameter: None * Return: None *----------------------------------------------------------------------------*/ __inline static void USBH_STM32_DMA_Enable (void) { RCC->AHBENR |= 1; /* Enable DMA1 clock, DMA1 */ /* will be used to load */ /* TX FIFO */ } /*------------------------- USBH_STM32_DMA_Disable ----------------------------- * * Disable the DMA previoucly used for USB * * Parameter: None * Return: None *----------------------------------------------------------------------------*/ #if 0 __inline static void USBH_STM32_DMA_Disable (void) { RCC->AHBENR &= ~1; /* Disable DMA1 clock */ } #endif /*------------------------- USBH_STM32_DMA_Stop -------------------------------- * * Stop the DMA transfer * * Parameter: None * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ __inline static BOOL USBH_STM32_DMA_Stop (void) { S32 tout; DMA1_CH1->CCR = 0; /* Stop the DMA transfer */ for (tout = 1010; tout >= 0; tout--) { /* Wait max 100 ms */ if (!(DMA1_CH1->CCR & 1)) /* Wait for DMA to disable */ break; if (!tout) return (__FALSE); if (tout <= 10) USBH_STM32_Delay_ms (10); } return (__TRUE); } /*------------------------- USBH_STM32_DMA_Start ------------------------------- * * Start the DMA transfer * * Parameter: ptrDest: Pointer to Destination addres of transfer * ptrSrc: Pointer to Source address of transfer * len: Number of bytes to transfer * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ __inline static BOOL USBH_STM32_DMA_Start (U32 *ptrDest, U32 *ptrSrc, U16 len) { DMA1->IFCR = 0x0F; /* Clear DMA interrupts */ DMA1_CH1->CMAR = (uint32_t)ptrSrc; /* Load source address */ DMA1_CH1->CPAR = (uint32_t)ptrDest; /* Load destination address */ DMA1_CH1->CNDTR = (len+3)/4; /* Set size of transfer */ DMA1_CH1->CCR = (1 << 14) | /* MEM2MEM enable */ (0 << 12) | /* Priority Level low (PL=0)*/ (2 << 10) | /* Memory size 32 bits */ (2 << 8) | /* Peripheral size 32 bits */ (1 << 7) | /* Memory increment enable */ (1 << 6) | /* Peripheral increment en */ (0 << 5) | /* CIRC = 0 */ (1 << 4) | /* Direction from memory */ (0 << 3) | /* TEIE = 0 */ (0 << 2) | /* HTIE = 0 */ (0 << 1) ; /* TCIE = 0 */ DMA1_CH1->CCR |= (1 << 0) ; /* Channel enable */ return (__TRUE); } /*------------------------- USBH_STM32_DMA_Wait -------------------------------- * * Wait for the DMA transfer to finish and cleanup DMA for next transfer * * Parameter: None * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ __inline static BOOL USBH_STM32_DMA_Wait (void) { S32 tout; for (tout = 1010; tout >= 0; tout--) { /* Wait max 100 ms */ if (!(DMA1_CH1->CCR&1) || !(DMA1_CH1->CNDTR)) /* If prev trans completed */ break; if (!tout) return (__FALSE); if (tout <= 10) USBH_STM32_Delay_ms (10); } if (!USBH_STM32_DMA_Stop()) /* Stop the DMA transfer */ return (__FALSE); return (__TRUE); } /***----------------------- Channel Functions ------------------------------***/ /*------------------------- USBH_STM32_CH_GetIndexFromCH ----------------------- * * Get the Index of Channel from it's Address * * Parameter: ptrCH: Pointer to the Channel * Return: Index of the Channel *----------------------------------------------------------------------------*/ static U32 USBH_STM32_CH_GetIndexFromCH (USBH_STM32_CH *ptrCH) { return (ptrCH - (USBH_STM32_CH *)(&(OTG->HCCHAR0))); } /*------------------------- USBH_STM32_CH_GetCHFromIndex ----------------------- * * Get the Channel Address from it's Index * * Parameter: idx: Index of the Channel * Return: Address of the Channel *----------------------------------------------------------------------------*/ static USBH_STM32_CH *USBH_STM32_CH_GetCHFromIndex (U32 idx) { return ((USBH_STM32_CH *)(&(OTG->HCCHAR0)) + idx); } /*------------------------- USBH_STM32_CH_FindFree ----------------------------- * * Find a free Channel * * Parameter: * Return: Pointer to the first free Channel * (0 = no free Channel is available) *----------------------------------------------------------------------------*/ static void *USBH_STM32_CH_FindFree (void) { USBH_STM32_CH *ptr_CH; U32 i; ptr_CH = (USBH_STM32_CH *)(&(OTG->HCCHAR0)); for (i = 0; i < OTG_MAX_CH; i++) { if (!ptr_CH->HCCHAR) { return (ptr_CH); } ptr_CH++; } return (0); } /*------------------------- USBH_STM32_CH_Disable ------------------------------ * * Disable the Channel * * Parameter: ptrCH: Pointer to the Channel * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ static BOOL USBH_STM32_CH_Disable (USBH_STM32_CH *ptrCH) { S32 tout; if (!ptrCH) return (__FALSE); ptrCH->HCINTMSK = 0; USBH_STM32_Delay_ms (2); if (ptrCH->HCCHAR & USBH_STM32_HCCHAR_CHENA) { if (!(ptrCH->HCCHAR & USBH_STM32_HCCHAR_EPDIR) && (ptrCH->HCTSIZ)) { if (!USBH_STM32_DMA_Stop()) return (__FALSE); } ptrCH->HCINT = ~USBH_STM32_HCINT_CHH; ptrCH->HCCHAR = (ptrCH->HCCHAR | USBH_STM32_HCCHAR_CHENA); USBH_STM32_Delay_ms (2); ptrCH->HCCHAR = (ptrCH->HCCHAR & ~USBH_STM32_HCCHAR_CHENA) | USBH_STM32_HCCHAR_CHDIS; for (tout = 1010; tout >= 0; tout--) { /* Wait max 100 ms */ if (ptrCH->HCINT & USBH_STM32_HCINT_CHH) break; if ((ptrCH->HCCHAR & (USBH_STM32_HCCHAR_CHENA | USBH_STM32_HCCHAR_CHDIS)) == (USBH_STM32_HCCHAR_CHENA | USBH_STM32_HCCHAR_CHDIS)) break; if (!tout) { return (__FALSE); } if (tout <= 10) USBH_STM32_Delay_ms (10); } } return (__TRUE); } /*------------------------- USBH_STM32_CH_TransferEnqueue ---------------------- * * Enqueue the Transfer * * Parameter: ptrCH: Pointer to the channel on which transfer will take place * tgl_typ: Toggle (bit 5..4: bit 5 - force toggle, bit 4 - value) and * Packet type (bit 3..0: USBH_PACKET_IN, USBH_PACKET_OUT or USBH_PACKET_SETUP) * buf: Start of the receive or transmit data buffer * len: Length of the data to be received or sent * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ static BOOL USBH_STM32_CH_TransferEnqueue (USBH_STM32_CH *ptrCH, U32 tgl_typ, U8 *buf, U32 len) { U32 hcchar; U32 hctsiz; U32 hcintmsk; U32 mpsiz; U32 ch_idx; BOOL load_data; if (!ptrCH) return (__FALSE); if (!Port_Con) return (__FALSE); hcchar = ptrCH->HCCHAR; /* Read channel characterist*/ hctsiz = ptrCH->HCTSIZ; /* Read channel size info */ hcintmsk = 0; /* Prepare transfer */ /* Prepare HCCHAR register */ hcchar &= USBH_STM32_HCCHAR_ODDFRM| /* Keep ODDFRM */ USBH_STM32_HCCHAR_DAD | /* Keep DAD */ USBH_STM32_HCCHAR_MCNT | /* Keep MCNT */ USBH_STM32_HCCHAR_EPTYP | /* Keep EPTYP */ USBH_STM32_HCCHAR_LSDEV | /* Keep LSDEV */ USBH_STM32_HCCHAR_EPNUM | /* Keep EPNUM */ USBH_STM32_HCCHAR_MPSIZ ; /* Keep MPSIZ */ switch (tgl_typ & 0x0F) { case USBH_PACKET_IN: hcchar |= USBH_STM32_HCCHAR_EPDIR; hcintmsk = USBH_STM32_HCINTMSK_DTERRM | USBH_STM32_HCINTMSK_BBERRM | USBH_STM32_HCINTMSK_TXERRM | USBH_STM32_HCINTMSK_ACKM | USBH_STM32_HCINTMSK_NAKM | USBH_STM32_HCINTMSK_STALLM | USBH_STM32_HCINTMSK_XFRCM ; break; case USBH_PACKET_OUT: hcchar &= ~USBH_STM32_HCCHAR_EPDIR; hcintmsk = USBH_STM32_HCINTMSK_TXERRM | USBH_STM32_HCINTMSK_NYET | USBH_STM32_HCINTMSK_NAKM | USBH_STM32_HCINTMSK_STALLM | USBH_STM32_HCINTMSK_XFRCM ; break; case USBH_PACKET_SETUP: hcchar &= ~USBH_STM32_HCCHAR_EPDIR; hcintmsk = USBH_STM32_HCINTMSK_TXERRM | USBH_STM32_HCINTMSK_NAKM | USBH_STM32_HCINTMSK_STALLM | USBH_STM32_HCINTMSK_XFRCM ; break; } hcchar &= ~USBH_STM32_HCCHAR_CHDIS; hcchar |= USBH_STM32_HCCHAR_CHENA; /* Prepare HCTSIZ register */ hctsiz &= USBH_STM32_HCTSIZ_DPID; /* Keep DPID */ if ((tgl_typ & 0x0F) == USBH_PACKET_SETUP) { /* If setup pckt DPID=MDATA */ hctsiz &= ~USBH_STM32_HCTSIZ_DPID; hctsiz |= USBH_STM32_HCTSIZ_DPID_MDATA; } else if ((tgl_typ >> 5) & 1) { /* If toggle force bit activ*/ if ((tgl_typ >> 4) & 1) { /* Toggle bit value */ hctsiz &= ~USBH_STM32_HCTSIZ_DPID; hctsiz |= USBH_STM32_HCTSIZ_DPID_DATA1; } else { hctsiz &= ~USBH_STM32_HCTSIZ_DPID; hctsiz |= USBH_STM32_HCTSIZ_DPID_DATA0; } } mpsiz = hcchar & 0x7FF; /* Maximum packet size */ if (len) { /* Normal packet */ hctsiz |= ((len+mpsiz-1) / mpsiz) << 19; /* Prepare PKTCNT field */ hctsiz |= ( len ) << 0; /* Prepare XFRSIZ field */ } else { /* Zero length packet */ hctsiz |= ( 1 ) << 19; /* Prepare PKTCNT field */ hctsiz |= ( 0 ) << 0; /* Prepare XFRSIZ field */ } ch_idx = USBH_STM32_CH_GetIndexFromCH (ptrCH); ptrCH->HCINTMSK = hcintmsk; /* Enable channel interrupts*/ ptrCH->HCTSIZ = hctsiz; /* Write ch transfer size */ /* load_data == __TRUE if there is data to be loaded to FIFO (If packet is OUT or SETUP and len > 0) */ load_data = (((tgl_typ & 0x0F) == USBH_PACKET_OUT) || ((tgl_typ & 0x0F) == USBH_PACKET_SETUP)) && len; if (load_data) USBH_STM32_DMA_Wait(); ptrCH->HCCHAR = hcchar; /* Write ch characteristics */ if (load_data) USBH_STM32_DMA_Start (OTG_DFIFO[ch_idx], (U32 *)(buf), len); return (__TRUE); } /************************** Module Functions **********************************/ /*------------------------- USBH_STM32_Get_Capabilities ------------------------ * * Get capabilities of Host Controller Driver * * Parameter: cap: Pointer to USBH_HCI_CAP structure where * capabilities are loaded * Return: *----------------------------------------------------------------------------*/ void USBH_STM32_Get_Capabilities (USBH_HCI_CAP *cap) { cap->MultiPckt = __TRUE; cap->MaxDataSz = 512; cap->CtrlNAKs = 100000; cap->BulkNAKs = 1000000; } /*------------------------- USBH_STM32_Delay_ms -------------------------------- * * Delay execution (in milliseconds) * Calibration is done if global variable calDelay is 0 * * Parameter: ms: Number of milliseconds to delay execution for * Return: *----------------------------------------------------------------------------*/ void USBH_STM32_Delay_ms (U32 ms) { U32 cnt = 0, vals = 0, vale = 0; start: if (!calDelay) { /* If not calibrated */ cnt = 1000; if (!(SysTick->CTRL & SysTick_CTRL_ENABLE_Msk)) { /* If SysTick timer not running */ vals = 0xFFFFFF; SysTick->LOAD = 0xFFFFFF; SysTick->VAL = 0xFFFFFF; SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_ENABLE_Msk; } else { vals = SysTick->VAL; /* Timer start value */ } } else { cnt = ms * calDelay; } while (cnt--); if (!calDelay) { /* If not calibrated */ vale = SysTick->VAL; /* Timer end value */ if (vale >= vals) /* If timer reloaded */ vals += SysTick->LOAD; calDelay = SystemFrequency / (vals - vale); /* Calibrated value */ if (vals == 0xFFFFFF) /* Stop timer if we started it */ SysTick->CTRL = 0; goto start; } } /*------------------------- USBH_STM32_Pins_Config ----------------------------- * * Configurate or unconfigurate pins used by the USB Host * * Parameter: on: __TRUE = configurate, __FALSE = unconfigurate * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ BOOL USBH_STM32_Pins_Config (BOOL on) { if (on) { RCC->APB2ENR |= ( 1 << 4); /* Enable GPIOC port clock */ GPIOC->BSRR = ( 1 << 9); /* PC9 drive high */ GPIOC->CRH &= ~(0x0F << 4); /* Clear PC9 configuration */ GPIOC->CRH |= ( 1 << 6)| /* PC9 general purpose open-drain */ ( 1 << 4); /* PC9 output mode (10 MHz) */ USBH_STM32_Port_Power ( __FALSE); /* Turn off port power */ } else { GPIOC->CRH &= ~(0x0F << 4); /* Clear PC9 configuration */ GPIOC->CRH |= (0x04 << 4); /* Float Input (reset state) */ } return (__TRUE); } /*------------------------- USBH_STM32_Init ------------------------------------ * * Initialize or uninitialize the USB Host Controller * * Parameter: on: __TRUE = initialize, __FALSE = uninitialize * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ BOOL USBH_STM32_Init (BOOL on) { S32 tout; if (on) { /* Initialize memory pool for data */ if (!usbh_mem_init(0, (U32 *)&USBH_MPOOL, USBH_STM32_SZ_MPOOL)) return (__FALSE); RCC->AHBENR |= ( 1 << 12); /* OTG FS clock enable */ OTG->GRSTCTL |= 1; /* USB Core Reset */ for (tout = 100; tout >= 0; tout--) { /* Wait max 1 second */ if (!(OTG->GRSTCTL & 1)) /* Wait for Core Reset end */ break; if (!tout) { return (__FALSE); } USBH_STM32_Delay_ms (10); } USBH_STM32_DMA_Enable (); USBH_STM32_Delay_ms (100); /* Wait ~100 ms */ /* Core initialization */ OTG->GAHBCFG |= USBH_STM32_GAHBCFG_GINTMSK; /* Enable interrupts */ OTG->GUSBCFG &=~(USBH_STM32_GUSBCFG_FHMOD | /* Clear register */ USBH_STM32_GUSBCFG_TRDT(15)| USBH_STM32_GUSBCFG_PHYSEL); OTG->GUSBCFG = USBH_STM32_GUSBCFG_FHMOD | /* Force host mode */ USBH_STM32_GUSBCFG_PHYSEL | /* Full-spd transceiver */ USBH_STM32_GUSBCFG_TRDT(5); /* Turnaround time */ USBH_STM32_Delay_ms (100); /* Wait ~100 ms */ OTG->GRXFSIZ = (512/4) + /* RxFIFO depth is 512 by */ 2 + /* 8 bytes for Int EP */ 4 ; /* Packet info and status */ OTG->GNPTXFSIZ = ((512/4)<<16) | ((512/4)+6); /* Non-periodic TxFIFO */ OTG->HPTXFSIZ = (16<<16) | (((512/4)*2)+6); /* Periodic TxFIFO mem */ OTG->GCCFG |= USBH_STM32_GCCFG_SOFOUTEN | /* Enable SOF output */ USBH_STM32_GCCFG_PWRDWN ; /* Disable power down */ OTG->GINTMSK |= USBH_STM32_GINTMSK_DISCINT| /* Enable disconn int */ USBH_STM32_GINTMSK_HCIM | /* Enable host ch int */ USBH_STM32_GINTMSK_PRTIM | /* Enable host prt int */ USBH_STM32_GINTMSK_RXFLVLM| /* Enable RXFIFO int */ USBH_STM32_GINTMSK_SOFM ; /* Enable SOF int */ if (!(OTG->HCFG & 3)) { OTG->HCFG = USBH_STM32_HCFG_FSLSPCS(1)| /* PHY clk at 48MHz */ USBH_STM32_HCFG_FSLS(1) ; /* FS/LS only */ } OTG->HAINTMSK = 0xFF; /* Enable all ch ints */ NVIC_SetPriority (OTG_FS_IRQn, 0); /* Set OTG interrupt highest priority */ NVIC_EnableIRQ (OTG_FS_IRQn); /* Enable OTG interrupt */ } else { NVIC_DisableIRQ (OTG_FS_IRQn); /* Disable OTG interrupt */ OTG->HAINTMSK &= ~0xFF; /* Disable channel interrupts */ RCC->AHBSTR |= ( 1 << 12); /* OTG FS reset */ RCC->AHBSTR &= ~( 1 << 12); /* OTG FS not reset */ RCC->AHBENR &= ~( 1 << 12); /* OTG FS clock disable */ OTG->HPRT = 0; /* Reset host port control*/ OTG->HCFG = 0; /* Reset host config */ OTG->GINTMSK &=~(USBH_STM32_GINTMSK_DISCINT| /* Disable interrupts */ USBH_STM32_GINTMSK_HCIM | USBH_STM32_GINTMSK_PRTIM | USBH_STM32_GINTMSK_RXFLVLM| USBH_STM32_GINTMSK_SOFM ); OTG->GUSBCFG &=~(USBH_STM32_GUSBCFG_FHMOD | /* Reset USB config fields*/ USBH_STM32_GUSBCFG_PHYSEL | USBH_STM32_GUSBCFG_TRDT(15)); OTG->GUSBCFG |= USBH_STM32_GUSBCFG_TRDT(2); /* Set init values */ calDelay = 0; /* Force delay recalibrate */ } return (__TRUE); } /*------------------------- USBH_STM32_Port_Power ------------------------------ * * Turn USB Host port power on or off * * Parameter: on: __TRUE = power on, __FALSE = power off * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ BOOL USBH_STM32_Port_Power (BOOL on) { if (on) { OTG->HPRT |= USBH_STM32_HPRT_PPWR; /* Port power on */ GPIOC->BRR = ( 1 << 9); /* PC9 drive low */ } else { GPIOC->BSRR = ( 1 << 9); /* PC9 drive high */ OTG->HPRT &= ~USBH_STM32_HPRT_PPWR; /* Port power off */ } return (__TRUE); } /*------------------------- USBH_STM32_Port_Reset ------------------------------ * * Reset Port * * Parameter: port: Root Hub port to be reset (only 0 is available) * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ BOOL USBH_STM32_Port_Reset (U8 port) { U32 hcfg, hprt; S32 tout; if (!Port_Con) return (__FALSE); hcfg = OTG->HCFG; hprt = OTG->HPRT; switch ((hprt >> 17) & 3) { case 0: /* High-speed detected */ break; case 1: /* Full-speed detected */ OTG->HFIR = 48000; if ((hcfg & 3) != 1) { hcfg = (hcfg & ~USBH_STM32_HCFG_FSLSPCS(3)) | USBH_STM32_HCFG_FSLSPCS(1); OTG->HCFG = hcfg; } break; case 2: /* Low-speed detected */ OTG->HFIR = 6000; if ((hcfg & 3) != 2) { hcfg = (hcfg & ~USBH_STM32_HCFG_FSLSPCS(3)) | USBH_STM32_HCFG_FSLSPCS(2); OTG->HCFG = hcfg; } break; case 3: break; } OTG->HPRT |= USBH_STM32_HPRT_PRST; /* Port reset */ USBH_STM32_Delay_ms (17); /* Wait ~17 ms */ OTG->HPRT &= ~USBH_STM32_HPRT_PRST; /* Clear port reset */ for (tout = 10100; tout >= 0; tout--) { /* Wait for max 1 s */ if ((OTG->HPRT & USBH_STM32_HPRT_PENA)) /* If port enabled */ break; if (!tout) return (__FALSE); if (tout <= 100) USBH_STM32_Delay_ms (10); /* Wait ~10 ms */ } USBH_STM32_Delay_ms (20); /* Wait ~20 ms */ return (__TRUE); } /*------------------------- USBH_STM32_Get_Connect ----------------------------- * * Returns connect/disconnect port events (also does debouncing) * * Parameter: None * Return: Connection/Disconnection events *----------------------------------------------------------------------------*/ U32 USBH_STM32_Get_Connect (void) { U32 ret, stat; stat = (OTG->HPRT & USBH_STM32_HPRT_PCSTS); ret = Port_Discon_Evt; ret |= ((stat ^ Port_Con) && (Port_Con)); if (ret){ /* If port disconnect occured */ Port_Discon_Evt &= ~ret; return (ret << 16); } if (cntDebounce) { cntDebounce--; if (!cntDebounce) { /* If debounce time expired */ ret = ((stat ^ Port_Con) && (!Port_Con)); /* If debounce expired on conn 0 -> 1 */ Port_Con |= ret; } else { USBH_STM32_Delay_ms (1); } } else if ((stat ^ Port_Con) && (!Port_Con)) { /* Restart debouncing if connect */ cntDebounce = DEBOUNCE_500ms; } return (ret); } /*------------------------- USBH_STM32_Get_Speed ------------------------------- * * Returns port speeds * * Parameter: None * Return: Port speeds *----------------------------------------------------------------------------*/ U32 USBH_STM32_Get_Speed (void) { return (Port_Speed); } /*------------------------- USBH_STM32_EP_Add ---------------------------------- * * Add the Endpoint and return handle (address of the Endpoint) * * Parameter: dev_adr: Device Address * ep_spd: Endpoint Speed * ptrEPD: Pointer to the USB Standard Endpoint Descriptor * Return: Handle to the Configured Endpoint (0 = FAIL) *----------------------------------------------------------------------------*/ U32 USBH_STM32_EP_Add (U8 dev_adr, U8 ep_spd, USB_ENDPOINT_DESCRIPTOR *ptrEPD) { USBH_STM32_CH *ptr_CH; ptr_CH = (USBH_STM32_CH *)(USBH_STM32_CH_FindFree ()); /* Find free Channel*/ if (!ptr_CH) { /* If no free exists */ return (0); } /* Fill in all fields from the USB Standard Endpoint Descriptor */ ptr_CH->HCCHAR = (((ptrEPD->wMaxPacketSize ) & 0x07FF) << 0) | (((ptrEPD->bEndpointAddress ) & 0x000F) << 11) | (((ptrEPD->bEndpointAddress >> 7) & 0x0001) << 15) | ((ep_spd == USBH_LS) << 17) | ((ptrEPD->bmAttributes & USB_ENDPOINT_TYPE_MASK) << 18) | ((dev_adr & 0x007F) << 22) ; switch (ptrEPD->bmAttributes & USB_ENDPOINT_TYPE_MASK) { case USB_ENDPOINT_TYPE_CONTROL: case USB_ENDPOINT_TYPE_BULK: break; case USB_ENDPOINT_TYPE_ISOCHRONOUS: case USB_ENDPOINT_TYPE_INTERRUPT: cntIntervalMax[USBH_STM32_CH_GetIndexFromCH (ptr_CH)] = ptrEPD->bInterval; ptr_CH->HCCHAR |= USBH_STM32_HCCHAR_MCNT1; break; } return ((U32)ptr_CH); } /*------------------------- USBH_STM32_EP_Config ------------------------------- * * (Re)Configure some parameters of the Endpoint * * Parameter: hndl: Handle to the Configured Endpoint * dev_adr: Device Address * ep_spd: Endpoint Speed * ptrEPD: Pointer to the USB Standard Endpoint Descriptor * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ BOOL USBH_STM32_EP_Config (U32 hndl, U8 dev_adr, U8 ep_spd, USB_ENDPOINT_DESCRIPTOR *ptrEPD) { USBH_STM32_CH *ptr_CH; if (!hndl) return (__FALSE); ptr_CH = (USBH_STM32_CH *)(hndl); if (!USBH_STM32_CH_Disable (ptr_CH)) return (__FALSE); /* Fill in all fields of Endpoint Descriptor */ ptr_CH->HCCHAR = (((ptrEPD->wMaxPacketSize ) & 0x07FF) << 0) | (((ptrEPD->bEndpointAddress ) & 0x000F) << 11) | (((ptrEPD->bEndpointAddress >> 7) & 0x0001) << 15) | ((ep_spd == USBH_LS) << 17) | ((ptrEPD->bmAttributes & USB_ENDPOINT_TYPE_MASK) << 18) | ((dev_adr & 0x007F) << 22) ; switch (ptrEPD->bmAttributes & USB_ENDPOINT_TYPE_MASK) { case USB_ENDPOINT_TYPE_CONTROL: case USB_ENDPOINT_TYPE_BULK: break; case USB_ENDPOINT_TYPE_ISOCHRONOUS: case USB_ENDPOINT_TYPE_INTERRUPT: ptr_CH->HCCHAR |= USBH_STM32_HCCHAR_MCNT1; break; } return (__TRUE); } /*------------------------- USBH_STM32_EP_Remove ------------------------------- * * Remove the Endpoint * * Parameter: hndl: Handle to the Configured Endpoint * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ BOOL USBH_STM32_EP_Remove (U32 hndl) { USBH_STM32_CH *ptr_CH; USBH_URB *ptr_URB; U32 ch_idx; if (!hndl) return (__FALSE); ptr_CH = (USBH_STM32_CH *)(hndl); ch_idx = USBH_STM32_CH_GetIndexFromCH (ptr_CH); ptr_URB = CHURB[ch_idx]; /* Pointer to channels URB */ if (ptr_URB) { /* If URB exists cancel it */ if (!USBH_STM32_URB_Cancel (hndl, ptr_URB)) return (__FALSE); } ptr_CH->HCCHAR = 0; ptr_CH->HCINT = 0; ptr_CH->HCINTMSK = 0; ptr_CH->HCTSIZ = 0; cntInterval[ch_idx] = 0; return (__TRUE); } /*------------------------- USBH_STM32_URB_Submit ------------------------------ * * Submit the URB (USB Request Block) to be processed * * Parameter: hndl: Endpoint handle (Endpoint address in memory) * ptrURB: Pointer to the URB * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ BOOL USBH_STM32_URB_Submit (U32 hndl, USBH_URB *ptrURB) { USBH_STM32_CH *ptr_CH; U32 ch_idx; U8 resp_type; if (!hndl) return (__FALSE); if (!ptrURB) return (__FALSE); if (!Port_Con) return (__FALSE); if ((ptrURB->Submitted == 1) || (ptrURB->InProgress == 1)) return (__FALSE); resp_type = ptrURB->ResponsePacketType; ptrURB->DataTransferred = 0; ptrURB->Status = 0; ptrURB->TimeoutCount = MAX_TIMEOUT_COUNT; ptr_CH = (USBH_STM32_CH *)(hndl); ch_idx = USBH_STM32_CH_GetIndexFromCH (ptr_CH); CHURB[ch_idx] = ptrURB; if (ptr_CH->EPTYP == USB_ENDPOINT_TYPE_INTERRUPT) { /* If interrupt endpoint transfer */ if (resp_type == USBH_PACKET_NAK) { cntInterval[ch_idx] = cntIntervalMax[ch_idx]; } else { cntInterval[ch_idx] = 1; /* Enable transmission on next SOF */ } ptrURB->Submitted = 1; } else if ((ptr_CH->EPTYP == USB_ENDPOINT_TYPE_CONTROL) || (ptr_CH->EPTYP == USB_ENDPOINT_TYPE_BULK)) { if ((Port_Speed & 3) != USBH_LS) { HW_Accessing = __TRUE; ptrURB->Submitted = 1; ptrURB->InProgress = 1; USBH_STM32_CH_TransferEnqueue (ptr_CH, (U8)ptrURB->Parameters, (U8 *)ptrURB->ptrDataBuffer, (U32)ptrURB->DataLength); HW_Accessing = __FALSE; } else { ptrURB->Submitted = 1; } } return (__TRUE); } /*------------------------- USBH_STM32_URB_Cancel ------------------------------ * * Cancel the URB (USB Request Block) * * Parameter: hndl: Endpoint handle (Endpoint address in memory) * ptrURB: Pointer to the URB * Return: __TRUE = Ok, __FALSE = error *----------------------------------------------------------------------------*/ BOOL USBH_STM32_URB_Cancel (U32 hndl, USBH_URB *ptrURB) { USBH_STM32_CH *ptr_CH; U32 ch_idx; if (!hndl) return (__FALSE); if (!ptrURB) return (__FALSE); if (!ptrURB->Submitted) return (__TRUE); ptrURB->Submitted = 0; ptr_CH = (USBH_STM32_CH *)(hndl); if (ptrURB->InProgress == 1) { if (!USBH_STM32_CH_Disable (ptr_CH))/* Stop Endpoint processing */ return (__FALSE); ptrURB->InProgress = 0; } ch_idx = USBH_STM32_CH_GetIndexFromCH (ptr_CH); if (!cntInterval[ch_idx]) { /* If interrupt endpoint transfer */ cntInterval[ch_idx] = 0; /* Disable transmission on next SOF */ } CHURB[ch_idx] = 0; ptrURB->Cancelled = 1; return (__TRUE); } /*------------------------- OTG_FS_IRQHandler ---------------------------------- * * STM32 USB Interrupt Handler Routine * * Parameter: * Return: *----------------------------------------------------------------------------*/ void OTG_FS_IRQHandler (void) { USBH_STM32_CH *ptr_CH; USBH_URB *ptr_URB; U8 *ptrData8; U32 *ptrData32; U32 *DFIFO; U32 gintsts, hprt, haint, hcint, pktcnt, mpsiz; U32 grxsts, bcnt, ch, dat, len, len_rest; U32 act; /* Read global interrupt register */ gintsts = OTG->GINTSTS & OTG->GINTMSK; hprt = OTG->HPRT; haint = OTG->HAINT; /* Analyze interrupt */ if (gintsts & USBH_STM32_GINTSTS_SOF) { /* If start of frame int */ for (ch = 0; ch < OTG_MAX_CH; ch++) { if (CHURB[ch]) { if (CHURB[ch]->TimeoutCount) { /* If timeout not 0 */ if (!(--CHURB[ch]->TimeoutCount)) { CHURB[ch]->Timeout = 1; /* If timeout expired */ } } } } } if (gintsts&USBH_STM32_GINTSTS_HPRTINT) { /* If host port interrupt */ if (hprt & USBH_STM32_HPRT_PCDET) { /* Port connect detected */ if (!Port_Con) { cntDebounce = DEBOUNCE_500ms; } } if (hprt & USBH_STM32_HPRT_PENCHNG) { /* If port enable changed */ if (hprt & USBH_STM32_HPRT_PENA) { /* If device connected */ Port_Speed &= ~3; switch ((hprt >> 17) & 3) { case 0: break; case 1: Port_Speed |= USBH_FS; break; case 2: Port_Speed |= USBH_LS; break; case 3: break; } } if (!(hprt & USBH_STM32_HPRT_PCSTS) && /* If device disconnected */ Port_Con) { Port_Discon_Evt = 1; Port_Con = 0; } } hprt &= ~USBH_STM32_HPRT_PENA; /* Leave PENA bit */ OTG->HPRT = hprt; /* Clear host port interrupt*/ } if ((gintsts & USBH_STM32_GINTSTS_DISCINT) && /* If device disconnected */ Port_Con) { Port_Discon_Evt = 1; Port_Con = 0; } if (Port_Discon_Evt) { /* If disconnect detected */ ptr_CH = (USBH_STM32_CH *)(&(OTG->HCCHAR0)); for (ch = 0; ch < OTG_MAX_CH; ch++) { if (CHURB[ch]) USBH_STM32_URB_Cancel ((U32)USBH_STM32_CH_GetCHFromIndex (ch), CHURB[ch]); ptr_CH++; } } /* Handle reception int */ if (gintsts & USBH_STM32_GINTSTS_RXFLVL) { /* If RXFIFO non-empty int */ OTG->GINTMSK &= ~USBH_STM32_GINTMSK_RXFLVLM; grxsts = OTG->GRXSTSR; if (((grxsts >> 17) & 0x0F) == 0x02){ /* If PKTSTS = 0x02 */ grxsts = (OTG->GRXSTSP); ch = (grxsts >> 0) & 0x00F; bcnt = (grxsts >> 4) & 0x7FF; ptr_CH = USBH_STM32_CH_GetCHFromIndex (ch); DFIFO = OTG_DFIFO[ch]; ptr_URB = CHURB[ch]; /* Pointer to channels URB */ ptrData32 = (U32 *)(ptr_URB->ptrDataBuffer + ptr_URB->DataTransferred); len = bcnt / 4; /* Received number of bytes */ len_rest = bcnt & 3; /* Number of bytes left */ while (len--) { *ptrData32++ = *DFIFO; ptr_URB->DataTransferred += 4; } if (len_rest) { dat = *DFIFO; ptrData8 = (U8 *)ptrData32; while (len_rest--) { *ptrData8++ = dat; dat >>= 8; ptr_URB->DataTransferred ++; } } } else { /* If PKTSTS != 0x02 */ grxsts = OTG->GRXSTSP; } OTG->GINTMSK |= USBH_STM32_GINTMSK_RXFLVLM; } /* Handle transmission int */ if (gintsts & USBH_STM32_GINTSTS_HCINT) { /* If host channel interrupt*/ ptr_CH = (USBH_STM32_CH *)(&(OTG->HCCHAR0)); for (ch = 0; ch < OTG_MAX_CH; ch++) { if (haint & (1 << ch)) { /* If channels interrupt act*/ hcint = ptr_CH->HCINT & ptr_CH->HCINTMSK; ptr_URB = CHURB[ch]; /* Pointer to channels URB */ ptr_URB->Error |= (hcint & USBH_STM32_HCINT_ERR) >> 7; if ((ptr_URB->PacketType == USBH_PACKET_OUT) || /* If OUT packet ----------*/ (ptr_URB->PacketType == USBH_PACKET_SETUP)) { /* or SETUP packet----------*/ if (hcint & USBH_STM32_HCINT_XFRC) { /* If data transfer finished*/ USBH_STM32_DMA_Stop(); /* Stop the DMA transfer */ ptr_CH->HCINTMSK = 0; ptr_URB->DataTransferred = ptr_URB->DataLength; ptr_URB->Status = 0; ptr_URB->ResponsePacketType = USBH_PACKET_ACK; ptr_URB->Completed = 1; CHURB[ch] = 0; } else if (hcint & USBH_STM32_HCINT_STALL) { /* If STALL event */ USBH_STM32_DMA_Stop(); /* Stop the DMA transfer */ ptr_URB->ResponsePacketType = USBH_PACKET_STALL; ptr_CH->HCINTMSK = USBH_STM32_HCINT_CHH; /* Halt the channel */ ptr_CH->HCCHAR |= USBH_STM32_HCCHAR_CHDIS; } else if ((hcint & USBH_STM32_HCINT_NAK) || /* If NAK received*/ (hcint & USBH_STM32_HCINT_TXERR)) { /* If TXERR rece */ USBH_STM32_DMA_Stop(); /* Stop the DMA transfer */ if (hcint & USBH_STM32_HCINT_NAK) { ptr_URB->ResponsePacketType = USBH_PACKET_NAK; ptr_CH->HCINTMSK = USBH_STM32_HCINT_CHH; } else { ptr_URB->Error = USBH_STM32_HCINT_TXERR >> 7; ptr_CH->HCINTMSK = USBH_STM32_HCINT_ACK | USBH_STM32_HCINT_CHH; } if (ptr_URB->DataLength) { /* Update transfer info */ pktcnt = (ptr_CH->HCTSIZ >> 19) & 0x3FF; mpsiz = (ptr_CH->HCCHAR >> 0) & 0x7FF; ptr_URB->DataTransferred = (((ptr_URB->DataLength + mpsiz - 1) / mpsiz) - pktcnt) * mpsiz; } /* Halt the channel */ ptr_CH->HCCHAR |= USBH_STM32_HCCHAR_CHENA | USBH_STM32_HCCHAR_CHDIS; } else if (hcint&USBH_STM32_HCINT_CHH) {/* If channel halted */ if ((ptr_CH->EPTYP != USB_ENDPOINT_TYPE_INTERRUPT) && (ptr_URB->ResponsePacketType == USBH_PACKET_NAK) && (CHURB[ch]->NAKRetries--)) { /* Reenable channel */ USBH_STM32_CH_TransferEnqueue (ptr_CH, (U8)CHURB[ch]->Parameters, (U8 *)CHURB[ch]->ptrDataBuffer+CHURB[ch]->DataTransferred, (U32)CHURB[ch]->DataLength-CHURB[ch]->DataTransferred); CHURB[ch]->TimeoutCount= MAX_TIMEOUT_COUNT; } else { ptr_CH->HCINTMSK = 0; ptr_URB->Submitted = 0; ptr_URB->InProgress = 0; ptr_URB->Completed = 1; CHURB[ch] = 0; } } else if (hcint&USBH_STM32_HCINT_ACK) {/* If ACK received */ ptr_URB->ResponsePacketType = USBH_PACKET_ACK; ptr_URB->Error = 0; ptr_CH->HCINTMSK &=~USBH_STM32_HCINT_ACK; } } else if (ptr_URB->PacketType == USBH_PACKET_IN) { /* If IN packet ----------*/ if (hcint & USBH_STM32_HCINT_XFRC) { ptr_URB->ResponsePacketType = USBH_PACKET_ACK; ptr_URB->Error = 0; ptr_CH->HCINTMSK = USBH_STM32_HCINT_CHH; /* Halt the channel */ ptr_CH->HCCHAR |= USBH_STM32_HCCHAR_CHENA | USBH_STM32_HCCHAR_CHDIS; } else if (hcint&USBH_STM32_HCINT_NAK) {/* If NAK received */ ptr_URB->ResponsePacketType = USBH_PACKET_NAK; if ((Port_Con) && (ptr_CH->EPTYP != USB_ENDPOINT_TYPE_INTERRUPT) && (CHURB[ch]->NAKRetries--)) { /* Reenable channel */ ptr_CH->HCINTMSK = USBH_STM32_HCINTMSK_DTERRM | USBH_STM32_HCINTMSK_BBERRM | USBH_STM32_HCINTMSK_TXERRM | USBH_STM32_HCINTMSK_ACKM | USBH_STM32_HCINTMSK_NAKM | USBH_STM32_HCINTMSK_STALLM | USBH_STM32_HCINTMSK_XFRCM ; ptr_CH->HCCHAR |= USBH_STM32_HCCHAR_CHENA; CHURB[ch]->TimeoutCount= MAX_TIMEOUT_COUNT; } else { /* Halt the channel */ ptr_CH->HCINTMSK = USBH_STM32_HCINT_CHH; ptr_CH->HCCHAR |= USBH_STM32_HCCHAR_CHENA | USBH_STM32_HCCHAR_CHDIS; } } else if ((hcint & USBH_STM32_HCINT_TXERR) || /* If TXERR event */ (hcint & USBH_STM32_HCINT_BBERR) || /* If BBERR event */ (hcint & USBH_STM32_HCINT_STALL)) { /* If STALL event */ ptr_CH->HCINTMSK = USBH_STM32_HCINT_CHH; if (hcint & USBH_STM32_HCINT_TXERR) { ptr_URB->Error = USBH_STM32_HCINT_TXERR >> 7; ptr_CH->HCINTMSK |= USBH_STM32_HCINT_ACK; } else if (hcint & USBH_STM32_HCINT_BBERR) { ptr_URB->Error = USBH_STM32_HCINT_BBERR >> 7; } else { ptr_URB->ResponsePacketType = USBH_PACKET_STALL; } /* Halt the channel */ ptr_CH->HCCHAR |= USBH_STM32_HCCHAR_CHENA | USBH_STM32_HCCHAR_CHDIS; } else if (hcint&USBH_STM32_HCINT_CHH) {/* If Channel Halted */ ptr_CH->HCINTMSK = 0; ptr_URB->Submitted = 0; ptr_URB->InProgress = 0; ptr_URB->Completed = 1; CHURB[ch] = 0; if (ptr_URB->Completed && ptr_URB->CompletedCallback) { ptr_URB->CompletedCallback(); } } else if (hcint&USBH_STM32_HCINT_ACK) {/* If ACK received */ ptr_URB->ResponsePacketType = USBH_PACKET_ACK; ptr_URB->Error = 0; if (ptr_CH->EPTYP != USB_ENDPOINT_TYPE_INTERRUPT) { ptr_CH->HCINTMSK = USBH_STM32_HCINTMSK_DTERRM | USBH_STM32_HCINTMSK_BBERRM | USBH_STM32_HCINTMSK_TXERRM | USBH_STM32_HCINTMSK_ACKM | USBH_STM32_HCINTMSK_NAKM | USBH_STM32_HCINTMSK_STALLM | USBH_STM32_HCINTMSK_XFRCM ; /* Reenable channel */ ptr_CH->HCCHAR |= USBH_STM32_HCCHAR_CHENA; CHURB[ch]->TimeoutCount= MAX_TIMEOUT_COUNT; } else { ptr_CH->HCINTMSK = USBH_STM32_HCINT_CHH; /* Halt the channel */ ptr_CH->HCCHAR |= USBH_STM32_HCCHAR_CHENA | USBH_STM32_HCCHAR_CHDIS; } } else if (hcint&USBH_STM32_HCINT_DTERR) {/* If DTERR received */ } } ptr_CH->HCINT = 0x7FF; } ptr_CH++; } OTG->HAINT = haint; } OTG->GINTSTS = gintsts; /* Clear core interrupts */ if (gintsts & USBH_STM32_GINTSTS_SOF) { /* If start of frame int */ if (HW_Accessing) { act = 1; } else { act = 0; for (ch = 0; ch < OTG_MAX_CH; ch++) { if (CHURB[ch]) { if (CHURB[ch]->InProgress == 1) { /* If any URB in progress */ act = 1; /* Set act to 1 */ break; } } } } /* At this point act == 1 if there is USB bus activity */ ptr_CH = (USBH_STM32_CH *)(&(OTG->HCCHAR0)); for (ch = 0; ch < OTG_MAX_CH; ch++) { ptr_URB = CHURB[ch]; /* Pointer to channels URB */ if (ptr_URB) { if ((ptr_URB->Submitted == 1) && /* If URB is submitted */ (ptr_URB->InProgress == 0)) { /* If URB not in progress */ if (ptr_CH->EPTYP == USB_ENDPOINT_TYPE_INTERRUPT) { if (cntInterval[ch]) { if ((act && (cntInterval[ch] > 1)) || !act) cntInterval[ch]--; } if (!act) { if (!cntInterval[ch]) { /* If period expired */ ptr_URB->InProgress = 1; USBH_STM32_CH_TransferEnqueue (ptr_CH, (U8)ptr_URB->Parameters, (U8 *)ptr_URB->ptrDataBuffer, (U32)ptr_URB->DataLength); act = 1; } } } else if (!act) { ptr_URB->InProgress = 1; USBH_STM32_CH_TransferEnqueue (ptr_CH, (U8)ptr_URB->Parameters, (U8 *)ptr_URB->ptrDataBuffer, (U32)ptr_URB->DataLength); act = 1; } } } ptr_CH++; } } }
39.860862
194
0.455082
286f9e5b2185583861cbf46c196cb6522fa38f87
181
c
C
src_code/CPrimerPlus/ch06/for_13s.c
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
src_code/CPrimerPlus/ch06/for_13s.c
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
src_code/CPrimerPlus/ch06/for_13s.c
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
/* for_13s.c */ #include <stdio.h> int main(void) { int n; /* count by 13s */ for (n = 2; n < 60; n = n + 13) printf("%d \n", n); return 0; }
16.454545
37
0.40884
4dfa30f687221d59535115dad8c0a15723978294
4,426
c
C
src/cui/Observer.c
boldowa/GIEPY
5aa326b264ef19f71d2e0ab5513b08fac7bca941
[ "MIT" ]
8
2018-03-15T22:01:35.000Z
2019-07-13T18:04:41.000Z
src/cui/Observer.c
telinc1/GIEPY
9c87ad1070e519637fc4b11b6bef01f998961678
[ "MIT" ]
21
2018-02-18T06:25:40.000Z
2018-07-13T17:54:40.000Z
src/cui/Observer.c
telinc1/GIEPY
9c87ad1070e519637fc4b11b6bef01f998961678
[ "MIT" ]
2
2018-07-25T21:04:23.000Z
2022-01-01T08:40:13.000Z
/** * @file Observer.c */ #include <stdio.h> #include <bolib.h> #include <stdarg.h> #include <ctype.h> #include "common/Observer.h" #include "dll/Mewthree.def" #include "common/GetFmtStr.h" #if isWindows # include <windows.h> #endif #include "cui/Console.h" #ifndef _tprintf #define _tprintf printf #endif extern bool vdebug; extern bool disableWarn; bool isPut = true; ProgressMode pMode = ProgressMode_Normal; static void putcommon(uint flag, FILE* tgt, char* buffer, uint id, va_list vl, bool newLine) { static const ConsoleAttribute cas[] = { CA_Default, CA_Success, CA_Error, CA_Important }; int attr = 0; if(0 != (OBSFLG_SUCCESS & flag)) attr=1; if(0 != (OBSFLG_FAILURE & flag)) attr=2; if(0 != (OBSFLG_IMPORTANT & flag)) attr=3; sprintf(buffer, "%s%s", GetFmtStr(id), newLine?"\n":"([Y]es/[N]o): "); if(attr) SetConsoleAttribute(stdout, cas[attr]); vfprintf(tgt, buffer, vl); if(attr) SetConsoleAttribute(stdout, CA_Default); isPut = true; } uint putdbg(uint flag, uint id, ...) { va_list vl; char buf[2048]; if(vdebug) { va_start(vl, id); fprintf(stdout, "["); fprintf(stdout, "%s", GetFmtStr(GSID_DEBUG)); fprintf(stdout, "] "); putcommon(flag, stdout, buf, id, vl, true); va_end(vl); } return MEW_OBS_OK; } uint putinf(uint flag, uint id, ...) { va_list vl; char buf[2048]; va_start(vl, id); fprintf(stdout, "["); fprintf(stdout, "%s", GetFmtStr(GSID_INFO)); fprintf(stdout, "] "); putcommon(flag, stdout, buf, id, vl, true); va_end(vl); return MEW_OBS_OK; } static bool getqres(char c, uint* result) { switch(c) { case 'y': (*result) = MEW_OBS_YES; return true; case 'n': (*result) = MEW_OBS_NO; return true; default: break; } return false; } uint putques(uint flag, uint id, ...) { va_list vl; char buf[2048]; char s[2]; uint result = MEW_OBS_CANCEL; va_start(vl, id); for(;;) { fprintf(stdout, "["); fprintf(stdout, "%s", GetFmtStr(GSID_INQUIRY)); fprintf(stdout, "] "); putcommon(flag, stdout, buf, id, vl, false); /* read stdin */ fgets(s, 2, stdin); if(s[0] != '\n') if(s[1] != '\n') while(getchar()!='\n'); /* flush */ /* scanf("%1s%*[^\n]", s); getchar(); */ /* get answer */ if(getqres((char)tolower(s[0]), &result)) break; } va_end(vl); return result; } uint putwar(uint flag, uint id, ...) { va_list vl; char buf[2048]; if(!disableWarn) { va_start(vl, id); fprintf(stderr, "["); SetConsoleAttribute(stderr, CA_Warning); fprintf(stderr, "%s", GetFmtStr(GSID_WARN)); SetConsoleAttribute(stderr, CA_Default); fprintf(stderr, "] "); putcommon(flag, stderr, buf, id, vl, true); va_end(vl); } return MEW_OBS_OK; } uint puterr(uint flag, uint id, ...) { va_list vl; char buf[2048]; va_start(vl, id); fprintf(stderr, "["); SetConsoleAttribute(stderr, CA_Error); fprintf(stderr, "%s", GetFmtStr(GSID_ERROR)); SetConsoleAttribute(stderr, CA_Default); fprintf(stderr, "] "); putcommon(flag, stderr, buf, id, vl, true); va_end(vl); return MEW_OBS_OK; } uint putfatal(uint flag, uint id, ...) { va_list vl; char buf[2048]; va_start(vl, id); fprintf(stderr, "["); SetConsoleAttribute(stderr, CA_Fatal); fprintf(stderr, "%s", GetFmtStr(GSID_FATAL)); SetConsoleAttribute(stderr, CA_Default); fprintf(stderr, "] "); putcommon(flag, stderr, buf, id, vl, true); va_end(vl); return MEW_OBS_OK; } void timesub(uint* time, const uint msec) { time[3] = (msec/10); time[2] = (msec/1000); time[1] = (time[2]/60); time[0] = (time[1]/60); time[3] %= 100; time[2] %= 60; time[1] %= 60; } void progress(uint cur, uint all) { uint rate; float rate_f; static const int pbwidth = 50; int i; int len; rate_f = (float)cur/(float)all; rate = (uint)(rate_f*100); len = (int)((float)pbwidth*rate_f); if(false == isPut) MoveBackLines(stdout, 2); isPut = false; switch(pMode) { case ProgressMode_Normal: printf(" %4d / %4d\n", cur, all); break; case ProgressMode_Timer: { uint ctime[4]; uint atime[4]; timesub(ctime, cur); timesub(atime, all); printf(" %02d:%02d:%02d /", ctime[0],ctime[1],ctime[2]); printf(" %02d:%02d:%02d \n", atime[0],atime[1],atime[2]); } break; } printf("["); SetConsoleAttribute(stdout, CA_ProgressBar); for(i=0;i<len;i++) { printf("="); } for(;i<pbwidth;i++) { printf(" "); } SetConsoleAttribute(stdout, CA_Default); printf("] %3d%%\n", rate); }
17.846774
92
0.632174
9e92992ec71ce6b854a5bbfea7e1098b992dc474
27,892
h
C
Bull-Engine/AK/SoundEngine/Platforms/arm_neon/AkSimd.h
Sersius/Bull-Engine
d97c7ed4725eb9bef776ffbe9e5a13bed200cfd0
[ "MIT" ]
10
2019-02-05T07:57:21.000Z
2021-10-17T13:44:31.000Z
Engine/AK/include/AK/SoundEngine/Platforms/arm_neon/AkSimd.h
TempName0/TempMotor3D_P3
cc386713dd786e2a52cc9b219a0d701a9398f202
[ "MIT" ]
178
2019-02-26T17:29:08.000Z
2019-06-05T10:55:42.000Z
Engine/AK/include/AK/SoundEngine/Platforms/arm_neon/AkSimd.h
TempName0/TempMotor3D_P3
cc386713dd786e2a52cc9b219a0d701a9398f202
[ "MIT" ]
2
2020-02-27T18:57:27.000Z
2020-05-28T01:19:59.000Z
/******************************************************************************* The content of this file includes portions of the AUDIOKINETIC Wwise Technology released in source code form as part of the SDK installer package. Commercial License Usage Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology may use this file in accordance with the end user license agreement provided with the software or, alternatively, in accordance with the terms contained in a written agreement between you and Audiokinetic Inc. Apache License Usage Alternatively, this file may be used under the Apache License, Version 2.0 (the "Apache License"); you may not use this file except in compliance with the Apache License. You may obtain a copy of the Apache License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the Apache License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Apache License for the specific language governing permissions and limitations under the License. Version: v2017.2.3 Build: 6575 Copyright (c) 2006-2018 Audiokinetic Inc. *******************************************************************************/ // AkSimd.h /// \file /// AKSIMD - arm_neon implementation #ifndef _AKSIMD_ARM_NEON_H_ #define _AKSIMD_ARM_NEON_H_ #include <arm_neon.h> #include <AK/SoundEngine/Common/AkTypes.h> // Platform specific defines for prefetching /* // ?????? #define AKSIMD_ARCHCACHELINESIZE (64) ///< Assumed cache line width for architectures on this platform // ?????? #define AKSIMD_ARCHMAXPREFETCHSIZE (512) ///< Use this to control how much prefetching maximum is desirable (assuming 8-way cache) /// Cross-platform memory prefetch of effective address assuming non-temporal data // ?????? #define AKSIMD_PREFETCHMEMORY( __offset__, __add__ ) _mm_prefetch(((char *)(__add__))+(__offset__), _MM_HINT_NTA ) */ //////////////////////////////////////////////////////////////////////// /// @name Platform specific memory size alignment for allocation purposes //@{ #define AKSIMD_ALIGNSIZE( __Size__ ) (((__Size__) + 15) & ~15) //@} //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// @name AKSIMD types //@{ typedef int32x4_t AKSIMD_V4I32; ///< Vector of 4 32-bit signed integers typedef int16x8_t AKSIMD_V8I16; ///< Vector of 8 16-bit signed integers typedef int16x4_t AKSIMD_V4I16; ///< Vector of 4 16-bit signed integers typedef uint32x4_t AKSIMD_V4UI32; ///< Vector of 4 32-bit unsigned signed integers typedef uint32x2_t AKSIMD_V2UI32; ///< Vector of 2 32-bit unsigned signed integers typedef int32x2_t AKSIMD_V2I32; ///< Vector of 2 32-bit signed integers typedef float32_t AKSIMD_F32; ///< 32-bit float typedef float32x2_t AKSIMD_V2F32; ///< Vector of 2 32-bit floats typedef float32x4_t AKSIMD_V4F32; ///< Vector of 4 32-bit floats typedef uint32x4_t AKSIMD_V4COND; ///< Vector of 4 comparison results typedef uint32x4_t AKSIMD_V4ICOND; ///< Vector of 4 comparison results typedef uint32x4_t AKSIMD_V4FCOND; ///< Vector of 4 comparison results #if defined(AK_CPU_ARM_NEON) typedef float32x2x2_t AKSIMD_V2F32X2; typedef float32x4x2_t AKSIMD_V4F32X2; typedef float32x4x4_t AKSIMD_V4F32X4; #endif //@} //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// @name AKSIMD loading / setting //@{ /// Loads four single-precision, floating-point values (see _mm_load_ps) #define AKSIMD_LOAD_V4F32( __addr__ ) vld1q_f32( (float32_t*)(__addr__) ) /// Loads four single-precision floating-point values from unaligned /// memory (see _mm_loadu_ps) #define AKSIMD_LOADU_V4F32( __addr__ ) vld1q_f32( (float32_t*)(__addr__) ) /// Loads a single single-precision, floating-point value, copying it into /// all four words (see _mm_load1_ps, _mm_load_ps1) #define AKSIMD_LOAD1_V4F32( __scalar__ ) vld1q_dup_f32( (float32_t*)(&(__scalar__)) ) /// Sets the four single-precision, floating-point values to __scalar__ (see /// _mm_set1_ps, _mm_set_ps1) #define AKSIMD_SET_V4F32( __scalar__ ) vdupq_n_f32( __scalar__ ) /// Sets the four integer values to __scalar__ #define AKSIMD_SET_V4I32( __scalar__ ) vdupq_n_s32( __scalar__ ) /// Sets the four single-precision, floating-point values to zero (see /// _mm_setzero_ps) #define AKSIMD_SETZERO_V4F32() AKSIMD_SET_V4F32( 0 ) /// Loads a single-precision, floating-point value into the low word /// and clears the upper three words. /// r0 := *p; r1 := 0.0 ; r2 := 0.0 ; r3 := 0.0 (see _mm_load_ss) #define AKSIMD_LOAD_SS_V4F32( __addr__ ) vld1q_lane_f32( (float32_t*)(__addr__), AKSIMD_SETZERO_V4F32(), 0 ); /// Loads four 32-bit signed integer values (aligned) #define AKSIMD_LOAD_V4I32( __addr__ ) vld1q_s32( (const int32_t*)(__addr__) ) /// Loads 8 16-bit signed integer values (aligned) #define AKSIMD_LOAD_V8I16( __addr__ ) vld1q_s16( (const int16_t*)(__addr__) ) /// Loads 4 16-bit signed integer values (aligned) #define AKSIMD_LOAD_V4I16( __addr__ ) vld1_s16( (const int16_t*)(__addr__) ) /// Loads unaligned 128-bit value (see _mm_loadu_si128) #define AKSIMD_LOADU_V4I32( __addr__ ) vld1q_s32( (const int32_t*)(__addr__)) /// Sets the four 32-bit integer values to zero (see _mm_setzero_si128) #define AKSIMD_SETZERO_V4I32() vdupq_n_s32( 0 ) /// Loads two single-precision, floating-point values #define AKSIMD_LOAD_V2F32( __addr__ ) vld1_f32( (float32_t*)(__addr__) ) #define AKSIMD_LOAD_V2F32_LANE( __addr__, __vec__, __lane__ ) vld1_lane_f32( (float32_t*)(__addr__), (__vec__), (__lane__) ); /// Sets the two single-precision, floating-point values to __scalar__ #define AKSIMD_SET_V2F32( __scalar__ ) vdup_n_f32( __scalar__ ) /// Sets the two single-precision, floating-point values to zero #define AKSIMD_SETZERO_V2F32() AKSIMD_SET_V2F32( 0 ) /// Loads data from memory and de-interleaves #define AKSIMD_LOAD_V4F32X2( __addr__ ) vld2q_f32( (float32_t*)(__addr__) ) #define AKSIMD_LOAD_V2F32X2( __addr__ ) vld2_f32( (float32_t*)(__addr__) ) /// Loads data from memory and de-interleaves; only selected lane #define AKSIMD_LOAD_V2F32X2_LANE( __addr__, __vec__, __lane__ ) vld2_lane_f32( (float32_t*)(__addr__), (__vec__), (__lane__) ); #define AKSIMD_LOAD_V4F32X4_LANE( __addr__, __vec__, __lane__ ) vld4q_lane_f32( (float32_t*)(__addr__), (__vec__), (__lane__) ); //@} //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// @name AKSIMD storing //@{ /// Stores four single-precision, floating-point values. The address must be 16-byte aligned #define AKSIMD_STORE_V4F32( __addr__, __vName__ ) vst1q_f32( (float32_t*)(__addr__), (__vName__) ) /// Stores four single-precision, floating-point values. The address does not need to be 16-byte aligned. #define AKSIMD_STOREU_V4F32( __addr__, __vec__ ) vst1q_f32( (float32_t*)(__addr__), (__vec__) ) /// Stores the lower single-precision, floating-point value. /// *p := a0 (see _mm_store_ss) #define AKSIMD_STORE1_V4F32( __addr__, __vec__ ) vst1q_lane_f32( (float32_t*)(__addr__), (__vec__), 0 ) /// Stores four 32-bit integer values. The address must be 16-byte aligned. #define AKSIMD_STORE_V4I32( __addr__, __vec__ ) vst1q_s32( (int32_t*)(__addr__), (__vec__) ) /// Stores four 32-bit integer values. The address does not need to be 16-byte aligned. #define AKSIMD_STOREU_V4I32( __addr__, __vec__ ) vst1q_s32( (int32_t*)(__addr__), (__vec__) ) /// Stores four 32-bit unsigned integer values. The address does not need to be 16-byte aligned. #define AKSIMD_STOREU_V4UI32( __addr__, __vec__ ) vst1q_u32( (uint32_t*)(__addr__), (__vec__) ) /// Stores two single-precision, floating-point values. The address must be 16-byte aligned. #define AKSIMD_STORE_V2F32( __addr__, __vName__ ) vst1_f32( (AkReal32*)(__addr__), (__vName__) ) /// Stores data by interleaving into memory #define AKSIMD_STORE_V4F32X2( __addr__, __vName__ ) vst2q_f32( (float32_t*)(__addr__), (__vName__) ) #define AKSIMD_STORE_V2F32X2( __addr__, __vName__ ) vst2_f32( (float32_t*)(__addr__), (__vName__) ) //@} //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// @name AKSIMD conversion //@{ /// Converts the four signed 32-bit integer values of a to single-precision, /// floating-point values (see _mm_cvtepi32_ps) #define AKSIMD_CONVERT_V4I32_TO_V4F32( __vec__ ) vcvtq_f32_s32( __vec__ ) /// Converts the four single-precision, floating-point values of a to signed /// 32-bit integer values (see _mm_cvtps_epi32) #define AKSIMD_CONVERT_V4F32_TO_V4I32( __vec__ ) vcvtq_s32_f32( __vec__ ) /// Converts the four single-precision, floating-point values of a to signed /// 32-bit integer values by truncating (see _mm_cvttps_epi32) #define AKSIMD_TRUNCATE_V4F32_TO_V4I32( __vec__ ) vcvtq_s32_f32( (__vec__) ) /// Converts the two single-precision, floating-point values of a to signed /// 32-bit integer values #define AKSIMD_CONVERT_V2F32_TO_V2I32( __vec__ ) vcvt_s32_f32( __vec__ ) //@} //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// @name AKSIMD logical operations //@{ /// Computes the bitwise AND of the 128-bit value in a and the /// 128-bit value in b (see _mm_and_si128) #define AKSIMD_AND_V4I32( __a__, __b__ ) vandq_s32( (__a__), (__b__) ) /// Compares the 8 signed 16-bit integers in a and the 8 signed /// 16-bit integers in b for greater than (see _mm_cmpgt_epi16) #define AKSIMD_CMPGT_V8I16( __a__, __b__ ) \ vreinterpretq_s32_u16( vcgtq_s16( vreinterpretq_s16_s32(__a__), vreinterpretq_s16_s32(__b__) ) ) /// Compares for less than or equal (see _mm_cmple_ps) #define AKSIMD_CMPLE_V4F32( __a__, __b__ ) vcleq_f32( (__a__), (__b__) ) #define AKSIMD_CMPLT_V4I32( __a__, __b__) vreinterpretq_s32_u32(vcltq_s32(__a__, __b__)) #define AKSIMD_CMPGT_V4I32( __a__, __b__) vreinterpretq_s32_u32(vcgtq_s32(__a__,__b__)) #define AKSIMD_XOR_V4I32(__a__, __b__) veorq_s32(__a__, __b__) static AkForceInline AKSIMD_V4F32 AKSIMD_XOR_V4F32( const AKSIMD_V4F32& in_vec0, const AKSIMD_V4F32& in_vec1 ) { uint32x4_t t0 = vreinterpretq_u32_f32(in_vec0); uint32x4_t t1 = vreinterpretq_u32_f32(in_vec1); uint32x4_t res = veorq_u32(t0, t1); return vreinterpretq_f32_u32(res); } #define AKSIMD_SUB_V4I32(__a__, __b__) vsubq_s32(__a__, __b__) //@} //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// @name AKSIMD shifting //@{ /// Shifts the 4 signed or unsigned 32-bit integers in a left by /// in_shiftBy bits while shifting in zeros (see _mm_slli_epi32) #define AKSIMD_SHIFTLEFT_V4I32( __vec__, __shiftBy__ ) \ vshlq_n_s32( (__vec__), (__shiftBy__) ) /// Shifts the 4 signed 32-bit integers in a right by in_shiftBy /// bits while shifting in the sign bit (see _mm_srai_epi32) #define AKSIMD_SHIFTRIGHTARITH_V4I32( __vec__, __shiftBy__ ) \ vrshrq_n_s32( (__vec__), (__shiftBy__) ) //@} //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// @name AKSIMD shuffling //@{ // Macro for combining two vector of 2 elements into one vector of // 4 elements. #define AKSIMD_COMBINE_V2F32( a, b ) vcombine_f32( a, b ) // Macro for shuffle parameter for AKSIMD_SHUFFLE_V4F32() (see _MM_SHUFFLE) #define AKSIMD_SHUFFLE( fp3, fp2, fp1, fp0 ) \ (((fp3) << 6) | ((fp2) << 4) | ((fp1) << 2) | ((fp0))) /// Selects four specific single-precision, floating-point values from /// a and b, based on the mask i (see _mm_shuffle_ps) // Usage: AKSIMD_SHUFFLE_V4F32( vec1, vec2, AKSIMD_SHUFFLE( z, y, x, w ) ) // If you get a link error, it's probably because the required // _AKSIMD_LOCAL::SHUFFLE_V4F32< zyxw > is not implemented in // <AK/SoundEngine/Platforms/arm_neon/AkSimdShuffle.h>. #define AKSIMD_SHUFFLE_V4F32( a, b, zyxw ) \ _AKSIMD_LOCAL::SHUFFLE_V4F32< zyxw >( a, b ) /// Barrel-shift all floats by one. #define AKSIMD_SHUFFLE_BCDA( __a__ ) AKSIMD_SHUFFLE_V4F32( (__a__), (__a__), AKSIMD_SHUFFLE(0,3,2,1)) // Various combinations of zyxw for _AKSIMD_LOCAL::SHUFFLE_V4F32< zyxw > are // implemented in a separate header file to keep this one cleaner: #include <AK/SoundEngine/Platforms/arm_neon/AkSimdShuffle.h> /// Moves the upper two single-precision, floating-point values of b to /// the lower two single-precision, floating-point values of the result. /// The upper two single-precision, floating-point values of a are passed /// through to the result. /// r3 := a3; r2 := a2; r1 := b3; r0 := b2 (see _mm_movehl_ps) inline AKSIMD_V4F32 AKSIMD_MOVEHL_V4F32( const AKSIMD_V4F32 abcd, const AKSIMD_V4F32 xyzw ) { //return akshuffle_zwcd( xyzw, abcd ); AKSIMD_V2F32 zw = vget_high_f32( xyzw ); AKSIMD_V2F32 cd = vget_high_f32( abcd ); AKSIMD_V4F32 zwcd = vcombine_f32( zw , cd ); return zwcd; } /// Moves the lower two single-precision, floating-point values of b to /// the upper two single-precision, floating-point values of the result. /// The lower two single-precision, floating-point values of a are passed /// through to the result. /// r3 := b1 ; r2 := b0 ; r1 := a1 ; r0 := a0 (see _mm_movelh_ps) inline AKSIMD_V4F32 AKSIMD_MOVELH_V4F32( const AKSIMD_V4F32& xyzw, const AKSIMD_V4F32& abcd ) { return vcombine_f32( vget_low_f32( xyzw ) , vget_low_f32( abcd ) ); } /// Swap the 2 lower floats together and the 2 higher floats together. //#define AKSIMD_SHUFFLE_BADC( __a__ ) AKSIMD_SHUFFLE_V4F32( (__a__), (__a__), AKSIMD_SHUFFLE(2,3,0,1)) #define AKSIMD_SHUFFLE_BADC( __a__ ) vrev64q_f32( __a__ ) /// Swap the 2 lower floats with the 2 higher floats. //#define AKSIMD_SHUFFLE_CDAB( __a__ ) AKSIMD_SHUFFLE_V4F32( (__a__), (__a__), AKSIMD_SHUFFLE(1,0,3,2)) #define AKSIMD_SHUFFLE_CDAB( __a__ ) vcombine_f32( vget_high_f32(__a__), vget_low_f32(__a__) ) /// Duplicates the odd items into the even items (d c b a -> d d b b ) #define AKSIMD_DUP_ODD(__vv) AKSIMD_SHUFFLE_V4F32(__vv, __vv, AKSIMD_SHUFFLE(3,3,1,1)) /// Duplicates the even items into the odd items (d c b a -> c c a a ) #define AKSIMD_DUP_EVEN(__vv) AKSIMD_SHUFFLE_V4F32(__vv, __vv, AKSIMD_SHUFFLE(2,2,0,0)) //@} //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// @name AKSIMD arithmetic //@{ /// Subtracts the four single-precision, floating-point values of /// a and b (a - b) (see _mm_sub_ps) #define AKSIMD_SUB_V4F32( __a__, __b__ ) vsubq_f32( (__a__), (__b__) ) /// Subtracts the two single-precision, floating-point values of /// a and b #define AKSIMD_SUB_V2F32( __a__, __b__ ) vsub_f32( (__a__), (__b__) ) /// Subtracts the lower single-precision, floating-point values of a and b. /// The upper three single-precision, floating-point values are passed through from a. /// r0 := a0 - b0 ; r1 := a1 ; r2 := a2 ; r3 := a3 (see _mm_sub_ss) #define AKSIMD_SUB_SS_V4F32( __a__, __b__ ) \ vsubq_f32( (__a__), vsetq_lane_f32( AKSIMD_GETELEMENT_V4F32( (__b__), 0 ), AKSIMD_SETZERO_V4F32(), 0 ) ); /// Adds the four single-precision, floating-point values of /// a and b (see _mm_add_ps) #define AKSIMD_ADD_V4F32( __a__, __b__ ) vaddq_f32( (__a__), (__b__) ) /// Adds the two single-precision, floating-point values of /// a and b #define AKSIMD_ADD_V2F32( __a__, __b__ ) vadd_f32( (__a__), (__b__) ) /// Adds the four integers of a and b #define AKSIMD_ADD_V4I32( __a__, __b__ ) vaddq_s32( (__a__), (__b__) ) /// Multiplies the 4 low-parts of both operand into the 4 32-bit integers (no overflow) #define AKSIMD_MULLO16_V4I32( __a__, __b__ ) vmulq_s32(__a__, __b__) /// Compare the content of four single-precision, floating-point values of /// a and b #define AKSIMD_COMP_V4F32( __a__, __b__ ) vceqq_f32( (__a__), (__b__) ) /// Compare the content of two single-precision, floating-point values of /// a and b #define AKSIMD_COMP_V2F32( __a__, __b__ ) vceq_f32( (__a__), (__b__) ) /// Adds the lower single-precision, floating-point values of a and b; the /// upper three single-precision, floating-point values are passed through from a. /// r0 := a0 + b0; r1 := a1; r2 := a2; r3 := a3 (see _mm_add_ss) #define AKSIMD_ADD_SS_V4F32( __a__, __b__ ) \ vaddq_f32( (__a__), vsetq_lane_f32( AKSIMD_GETELEMENT_V4F32( (__b__), 0 ), AKSIMD_SETZERO_V4F32(), 0 ) ) /// Multiplies the four single-precision, floating-point values /// of a and b (see _mm_mul_ps) #define AKSIMD_MUL_V4F32( __a__, __b__ ) vmulq_f32( (__a__), (__b__) ) /// Multiplies the four single-precision, floating-point values of a /// by the single-precision, floating-point scalar b #define AKSIMD_MUL_V4F32_SCALAR( __a__, __b__ ) vmulq_n_f32( (__a__), (__b__) ) /// Rough estimation of division AkForceInline AKSIMD_V4F32 AKSIMD_DIV_V4F32( AKSIMD_V4F32 a, AKSIMD_V4F32 b ) { AKSIMD_V4F32 inv = vrecpeq_f32(b); AKSIMD_V4F32 restep = vrecpsq_f32(b, inv); inv = vmulq_f32(restep, inv); return vmulq_f32(a, inv); } /// Multiplies the two single-precision, floating-point values /// of a and b #define AKSIMD_MUL_V2F32( __a__, __b__ ) vmul_f32( (__a__), (__b__) ) /// Multiplies the two single-precision, floating-point values of a /// by the single-precision, floating-point scalar b #define AKSIMD_MUL_V2F32_SCALAR( __a__, __b__ ) vmul_n_f32( (__a__), (__b__) ) /// Multiplies the lower single-precision, floating-point values of /// a and b; the upper three single-precision, floating-point values /// are passed through from a. /// r0 := a0 * b0; r1 := a1; r2 := a2; r3 := a3 (see _mm_add_ss) #define AKSIMD_MUL_SS_V4F32( __a__, __b__ ) \ vmulq_f32( (__a__), vsetq_lane_f32( AKSIMD_GETELEMENT_V4F32( (__b__), 0 ), AKSIMD_SETZERO_V4F32(), 0 ) ) /// Vector multiply-add operation. #define AKSIMD_MADD_V4F32( __a__, __b__, __c__ ) \ AKSIMD_ADD_V4F32( AKSIMD_MUL_V4F32( (__a__), (__b__) ), (__c__) ) #define AKSIMD_MSUB_V4F32( __a__, __b__, __c__ ) \ AKSIMD_SUB_V4F32( AKSIMD_MUL_V4F32( (__a__), (__b__) ), (__c__) ) #define AKSIMD_MADD_V2F32( __a__, __b__, __c__ ) \ AKSIMD_ADD_V2F32( AKSIMD_MUL_V2F32( (__a__), (__b__) ), (__c__) ) #define AKSIMD_MSUB_V2F32( __a__, __b__, __c__ ) \ AKSIMD_SUB_V2F32( AKSIMD_MUL_V2F32( (__a__), (__b__) ), (__c__) ) #define AKSIMD_MADD_V4F32_INST( __a__, __b__, __c__ ) vmlaq_f32( (__c__), (__a__), (__b__) ) #define AKSIMD_MADD_V2F32_INST( __a__, __b__, __c__ ) vmla_f32( (__c__), (__a__), (__b__) ) //#define AKSIMD_MSUB_V4F32( __a__, __b__, __c__ ) vmlsq_f32( (__c__), (__a__), (__b__) ) //#define AKSIMD_MSUB_V2F32( __a__, __b__, __c__ ) vmls_f32( (__c__), (__a__), (__b__) ) #define AKSIMD_MADD_V4F32_SCALAR( __a__, __b__, __c__ ) vmlaq_n_f32( (__c__), (__a__), (__b__) ) #define AKSIMD_MADD_V2F32_SCALAR( __a__, __b__, __c__ ) vmla_n_f32( (__c__), (__a__), (__b__) ) /// Vector multiply-add operation. AkForceInline AKSIMD_V4F32 AKSIMD_MADD_SS_V4F32( const AKSIMD_V4F32& __a__, const AKSIMD_V4F32& __b__, const AKSIMD_V4F32& __c__ ) { return AKSIMD_ADD_SS_V4F32( AKSIMD_MUL_SS_V4F32( __a__, __b__ ), __c__ ); } /// Computes the minima of the four single-precision, floating-point /// values of a and b (see _mm_min_ps) #define AKSIMD_MIN_V4F32( __a__, __b__ ) vminq_f32( (__a__), (__b__) ) /// Computes the minima of the two single-precision, floating-point /// values of a and b #define AKSIMD_MIN_V2F32( __a__, __b__ ) vmin_f32( (__a__), (__b__) ) /// Computes the maximums of the four single-precision, floating-point /// values of a and b (see _mm_max_ps) #define AKSIMD_MAX_V4F32( __a__, __b__ ) vmaxq_f32( (__a__), (__b__) ) /// Computes the maximums of the two single-precision, floating-point /// values of a and b #define AKSIMD_MAX_V2F32( __a__, __b__ ) vmax_f32( (__a__), (__b__) ) /// Returns absolute value #define AKSIMD_ABS_V4F32( __a__ ) vabsq_f32((__a__)) /// Changes the sign #define AKSIMD_NEG_V2F32( __a__ ) vneg_f32( (__a__) ) #define AKSIMD_NEG_V4F32( __a__ ) vnegq_f32( (__a__) ) /// Square root (4 floats) #define AKSIMD_SQRT_V4F32( __vec__ ) vrecpeq_f32( vrsqrteq_f32( __vec__ ) ) /// Square root (2 floats) #define AKSIMD_SQRT_V2F32( __vec__ ) vrecpe_f32( vrsqrte_f32( __vec__ ) ) /// Faked in-place vector horizontal add. /// \akwarning /// Don't expect this to be very efficient. /// /endakwarning static AkForceInline void AKSIMD_HORIZONTALADD( AKSIMD_V4F32 & vVec ) { AKSIMD_V4F32 vHighLow = AKSIMD_MOVEHL_V4F32(vVec, vVec); vVec = AKSIMD_ADD_V4F32(vVec, vHighLow); vHighLow = AKSIMD_SHUFFLE_V4F32(vVec, vVec, 0x55); vVec = AKSIMD_ADD_V4F32(vVec, vHighLow); } /// Cross-platform SIMD multiplication of 2 complex data elements with interleaved real and imaginary parts #if defined(AK_IOS) // V2 implementation (faster 'cause ARM processors actually have an x2 pipeline) static AkForceInline AKSIMD_V4F32 AKSIMD_COMPLEXMUL( AKSIMD_V4F32 vCIn1, AKSIMD_V4F32 vCIn2 ) { static const AKSIMD_V2F32 vSign = { -1.f, 1.f }; AKSIMD_V2F32 vCIn1a = vget_low_f32( vCIn1 ); AKSIMD_V2F32 vCIn2a = vget_low_f32( vCIn2 ); AKSIMD_V2F32 vTmpa0 = vmul_n_f32( vCIn2a, vCIn1a[0] ); AKSIMD_V2F32 vTmpa1 = vmul_n_f32( vCIn2a, vCIn1a[1] ); vTmpa1 = vrev64_f32( vTmpa1 ); vTmpa1 = vmul_f32( vTmpa1, vSign ); vTmpa0 = vadd_f32( vTmpa0, vTmpa1 ); AKSIMD_V2F32 vCIn1b = vget_high_f32( vCIn1 ); AKSIMD_V2F32 vCIn2b = vget_high_f32( vCIn2 ); AKSIMD_V2F32 vTmpb0 = vmul_n_f32( vCIn2b, vCIn1b[0] ); AKSIMD_V2F32 vTmpb1 = vmul_n_f32( vCIn2b, vCIn1b[1] ); vTmpb1 = vrev64_f32( vTmpb1 ); vTmpb1 = vmul_f32( vTmpb1, vSign ); vTmpb0 = vadd_f32( vTmpb0, vTmpb1 ); return vcombine_f32( vTmpa0, vTmpb0 ); } #else // V4 implementation (kept in case future ARM processors actually have an x4 pipeline) static AkForceInline AKSIMD_V4F32 AKSIMD_COMPLEXMUL( AKSIMD_V4F32 vCIn1, AKSIMD_V4F32 vCIn2 ) { #ifdef AKSIMD_DECLARE_V4F32 static const AKSIMD_DECLARE_V4F32( vSign, 1.f, -1.f, 1.f, -1.f ); #else static const AKSIMD_V4F32 vSign = { 1.f, -1.f, 1.f, -1.f }; #endif AKSIMD_V4F32 vTmp1 = AKSIMD_SHUFFLE_V4F32( vCIn1, vCIn1, AKSIMD_SHUFFLE(2,2,0,0)); vTmp1 = AKSIMD_MUL_V4F32( vTmp1, vCIn2 ); AKSIMD_V4F32 vTmp2 = AKSIMD_SHUFFLE_V4F32( vCIn1, vCIn1, AKSIMD_SHUFFLE(3,3,1,1)); vTmp2 = AKSIMD_MUL_V4F32( vTmp2, vSign ); vTmp2 = AKSIMD_MUL_V4F32( vTmp2, vCIn2 ); vTmp2 = AKSIMD_SHUFFLE_BADC( vTmp2 ); vTmp2 = AKSIMD_ADD_V4F32( vTmp2, vTmp1 ); return vTmp2; } #endif //@} //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// @name AKSIMD packing / unpacking //@{ /// Interleaves the lower 4 signed or unsigned 16-bit integers in a with /// the lower 4 signed or unsigned 16-bit integers in b (see _mm_unpacklo_epi16) #define AKSIMD_UNPACKLO_VECTOR8I16( __a__, __b__ ) vreinterpretq_s32_s16( vzipq_s16( vreinterpretq_s16_s32(__a__), vreinterpretq_s16_s32(__b__) ).val[0] ) /// Interleaves the upper 4 signed or unsigned 16-bit integers in a with /// the upper 4 signed or unsigned 16-bit integers in b (see _mm_unpackhi_epi16) #define AKSIMD_UNPACKHI_VECTOR8I16( __a__, __b__ ) vreinterpretq_s32_s16( vzipq_s16( vreinterpretq_s16_s32(__a__), vreinterpretq_s16_s32(__b__) ).val[1] ) /// Selects and interleaves the lower two single-precision, floating-point /// values from a and b (see _mm_unpacklo_ps) AkForceInline AKSIMD_V4F32 AKSIMD_UNPACKLO_V4F32( const AKSIMD_V4F32& in_vec1, const AKSIMD_V4F32& in_vec2 ) { // sce_vectormath_xayb(in_vec1, in_vec2) float32x2_t xy = vget_low_f32( in_vec1 /*xyzw*/ ); float32x2_t ab = vget_low_f32( in_vec2 /*abcd*/ ); float32x2x2_t xa_yb = vtrn_f32( xy, ab ); AKSIMD_V4F32 xayb = vcombine_f32( xa_yb.val[0], xa_yb.val[1] ); return xayb; } /// Selects and interleaves the upper two single-precision, floating-point /// values from a and b (see _mm_unpackhi_ps) AkForceInline AKSIMD_V4F32 AKSIMD_UNPACKHI_V4F32( const AKSIMD_V4F32& in_vec1, const AKSIMD_V4F32& in_vec2 ) { //return sce_vectormath_zcwd( in_vec1, in_vec2 ); float32x2_t zw = vget_high_f32( in_vec1 /*xyzw*/ ); float32x2_t cd = vget_high_f32( in_vec2 /*abcd*/ ); float32x2x2_t zc_wd = vtrn_f32( zw, cd ); AKSIMD_V4F32 zcwd = vcombine_f32( zc_wd.val[0], zc_wd.val[1] ); return zcwd; } /// Packs the 8 signed 32-bit integers from a and b into signed 16-bit /// integers and saturates (see _mm_packs_epi32) AkForceInline AKSIMD_V4I32 AKSIMD_PACKS_V4I32( const AKSIMD_V4I32& in_vec1, const AKSIMD_V4I32& in_vec2 ) { int16x4_t vec1_16 = vqmovn_s32( in_vec1 ); int16x4_t vec2_16 = vqmovn_s32( in_vec2 ); int16x8_t result = vcombine_s16( vec1_16, vec2_16 ); return vreinterpretq_s32_s16( result ); } /// V1 = {a,b} => VR = {b,c} /// V2 = {c,d} => #define AKSIMD_HILO_V2F32( in_vec1, in_vec2 ) vreinterpret_f32_u32( vext_u32( vreinterpret_u32_f32( in_vec1 ), vreinterpret_u32_f32( in_vec2 ), 1 ) ) /// V1 = {a,b} => V1 = {a,c} /// V2 = {c,d} => V2 = {b,d} #define AKSIMD_TRANSPOSE_V2F32( in_vec1, in_vec2 ) vtrn_f32( in_vec1, in_vec2 ) #define AKSIMD_TRANSPOSE_V4F32( in_vec1, in_vec2 ) vtrnq_f32( in_vec1, in_vec2 ) /// V1 = {a,b} => VR = {b,a} #define AKSIMD_SWAP_V2F32( in_vec ) vrev64_f32( in_vec ) //@} //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// @name AKSIMD vector comparison /// Apart from AKSIMD_SEL_GTEQ_V4F32, these implementations are limited to a few platforms. //@{ #define AKSIMD_CMP_CTRLMASK uint32x4_t /// Compare each float element and return control mask. #define AKSIMD_GTEQ_V4F32( __a__, __b__ ) vcgeq_f32( (__a__), (__b__)) /// Compare each integer element and return control mask. #define AKSIMD_GTEQ_V4I32( __a__, __b__ ) vcgeq_s32( (__a__), (__b__)) /// Compare each float element and return control mask. #define AKSIMD_EQ_V4F32( __a__, __b__ ) vceqq_f32( (__a__), (__b__)) /// Compare each integer element and return control mask. #define AKSIMD_EQ_V4I32( __a__, __b__ ) vceqq_s32( (__a__), (__b__)) /// Return a when control mask is 0, return b when control mask is non zero, control mask is in c and usually provided by above comparison operations #define AKSIMD_VSEL_V4F32( __a__, __b__, __c__ ) vbslq_f32( (__c__), (__b__), (__a__) ) // (cond1 >= cond2) ? b : a. #define AKSIMD_SEL_GTEQ_V4F32( __a__, __b__, __cond1__, __cond2__ ) AKSIMD_VSEL_V4F32( __a__, __b__, vcgeq_f32( __cond1__, __cond2__ ) ) // a >= 0 ? b : c ... Written, like, you know, the normal C++ operator syntax. #define AKSIMD_SEL_GTEZ_V4F32( __a__, __b__, __c__ ) AKSIMD_VSEL_V4F32( (__c__), (__b__), vcgeq_f32( __a__, AKSIMD_SETZERO_V4F32() ) ) #define AKSIMD_SPLAT_V4F32(var, idx) vmovq_n_f32(vgetq_lane_f32(var, idx)) static AkForceInline int AKSIMD_MASK_V4F32( const AKSIMD_V4UI32& in_vec1 ) { #ifdef AKSIMD_DECLARE_V4F32 static const AKSIMD_DECLARE_V4I32(movemask, 1, 2, 4, 8); static const AKSIMD_DECLARE_V4I32(highbit, 0x80000000, 0x80000000, 0x80000000, 0x80000000); #else static const uint32x4_t movemask = { 1, 2, 4, 8 }; static const uint32x4_t highbit = { 0x80000000, 0x80000000, 0x80000000, 0x80000000 }; #endif uint32x4_t t0 = in_vec1; uint32x4_t t1 = vtstq_u32(t0, highbit); uint32x4_t t2 = vandq_u32(t1, movemask); uint32x2_t t3 = vorr_u32(vget_low_u32(t2), vget_high_u32(t2)); return vget_lane_u32(t3, 0) | vget_lane_u32(t3, 1); } #ifndef AK_WIN static AkForceInline int AKSIMD_MASK_V4F32( const AKSIMD_V4F32& in_vec1 ) { return AKSIMD_MASK_V4F32( vreinterpretq_u32_f32(in_vec1) ); } #endif //@} //////////////////////////////////////////////////////////////////////// #endif //_AKSIMD_ARM_NEON_H_
42.389058
154
0.696257
b11155f4724373ba8007ad3fed1f3a3cfcac4e4e
2,416
c
C
lantz/lantz/drivers/linux-gpib-4.2.0/linux-gpib-user-4.2.0/lib/ibLines.c
zhong-lab/optics
9de1942d9a128183ecb3d360b160b27126e7b8f0
[ "BSD-2-Clause" ]
1
2022-03-27T07:47:19.000Z
2022-03-27T07:47:19.000Z
lantz/lantz/drivers/linux-gpib-4.2.0/linux-gpib-user-4.2.0/lib/ibLines.c
zhong-lab/optics
9de1942d9a128183ecb3d360b160b27126e7b8f0
[ "BSD-2-Clause" ]
null
null
null
lantz/lantz/drivers/linux-gpib-4.2.0/linux-gpib-user-4.2.0/lib/ibLines.c
zhong-lab/optics
9de1942d9a128183ecb3d360b160b27126e7b8f0
[ "BSD-2-Clause" ]
4
2019-11-08T22:39:04.000Z
2021-11-05T02:39:37.000Z
/*************************************************************************** lib/ibLines.c ------------------- copyright : (C) 2001,2002,2003 by Frank Mori Hess email : fmhess@users.sourceforge.net ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "ib_internal.h" int internal_iblines( ibConf_t *conf, short *line_status ) { int retval; ibBoard_t *board; if( conf->is_interface == 0 ) { setIberr( EARG ); return -1; } board = interfaceBoard( conf ); retval = ioctl( board->fileno, IBLINES, line_status ); if( retval < 0 ) { switch( errno ) { default: setIbcnt( errno ); setIberr( EDVR ); break; } return -1; } return 0; } int iblines( int ud, short *line_status ) { ibConf_t *conf; int retval; conf = general_enter_library( ud, 1, 1 ); if( conf == NULL ) return general_exit_library( ud, 1, 0, 0, 0, 0, 1 ); retval = internal_iblines( conf, line_status ); if( retval < 0 ) { return general_exit_library( ud, 1, 0, 0, 0, 0, 1 ); } return general_exit_library( ud, 0, 0, 0, 0, 0, 1 ); } void TestSRQ( int boardID, short *result ) { short line_status; ibConf_t *conf; int retval; conf = general_enter_library( boardID, 1, 0 ); if( conf == NULL ) { general_exit_library( boardID, 1, 0, 0, 0, 0, 1 ); return; } retval = internal_iblines( conf, &line_status ); if( retval < 0 ) { general_exit_library( boardID, 1, 0, 0, 0, 0, 1 ); return; } if( ( line_status & ValidSRQ ) == 0 ) { setIberr( ECAP ); general_exit_library( boardID, 1, 0, 0, 0, 0, 1 ); return; } if( line_status & BusSRQ ) { *result = 1; }else *result = 0; general_exit_library( boardID, 0, 0, 0, 0, 0, 1 ); }
23.686275
77
0.475993
9ab35fa6558ad8eef2df83ebf77460a2563573f1
7,828
c
C
src2/gfx.c
petersieg/oscilloscope-asteroids
5a40cd9b493762b448b8f36ec848965114e3433e
[ "WTFPL" ]
11
2015-07-12T01:18:41.000Z
2021-07-24T20:10:10.000Z
src2/gfx.c
petersieg/oscilloscope-asteroids
5a40cd9b493762b448b8f36ec848965114e3433e
[ "WTFPL" ]
null
null
null
src2/gfx.c
petersieg/oscilloscope-asteroids
5a40cd9b493762b448b8f36ec848965114e3433e
[ "WTFPL" ]
2
2018-12-18T13:41:31.000Z
2021-01-18T14:04:58.000Z
/* implementaion of this vector graphics library for oscilloscope * * Frames are drawn using moveTo/lineTo, which assemble lists of points (struct vlist). When * flip is called, sendFrame renders the vlist to an audio clip, which cb_fill_audio plays * back in a loop until a newer frame is sent. * * I'm releasing this code under the WTFPL. You can do whatever you like with * it, though I'd appreciate credit and thanks if you find it useful or fun. * See LICENSE.txt for details. * -Joe McKenzie / Chupi */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> #include "gfx.h" #define PI 3.14159265358979323846 //VList: x/y point list - sets of 3 Uint16's: // 1st is X coord, 0 is left, 64k is right // 2nd is Y coord, 0 is top, 64k is bottom // 3rd is weight in steps, 0 is dimmest; note that 44100 steps = 1 second to draw this line!!! //first point's weight is ignored as it's the start position //all remaining points' weights are the weight going TO that point struct vlist { Uint16 *pts; int n; //number of triplets in pts }; //right channel is horizontal, left channel is vertical struct frame { Sint16 *samples; int n; //number of left/right *pairs* of samples }; //working vlist for moveTo/lineTo struct vlist work; Uint16 work_pts[(MAX_POINTS)*3]; //currFrame is drawn repeatedly until nextFrame is non-null //then nextFrame becomes currFrame (and currFrame is freed) when currFrame finishes drawing struct frame currFrame, nextFrame; //"screen" dimensions double xmin=0, xmax=1000, ymin=0, ymax=1000, targetWeight=100; //orientation int flipX=0, flipY=0, swapXY=0; int g_freq; double g_refresh; void cb_fill_audio(void *udata, Uint8 *stream, int len); void sendFrame(struct vlist *vl); void gfxInit(int freq, int buffer) { SDL_AudioSpec aspec; Sint16 *initSamps; if(freq <= 0 ) freq=44100; g_freq = freq; if(buffer <= 0) buffer=1024; aspec.freq = freq; aspec.format = AUDIO_S16SYS; //accept "Sint16" samples aspec.channels = 2; aspec.samples = buffer; aspec.callback = cb_fill_audio; aspec.userdata = NULL; if(SDL_OpenAudio(&aspec, NULL) < 0) { fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError()); exit(1); } //initialize frames memset(&currFrame, 0, sizeof(struct frame)); memset(&nextFrame, 0, sizeof(struct frame)); initSamps = malloc(aspec.samples/4*aspec.channels*sizeof(initSamps[0])); memset(initSamps, 0, aspec.samples/4*aspec.channels*sizeof(initSamps[0])); currFrame.samples = initSamps; currFrame.n = aspec.samples/4*aspec.channels; //setup working vlist for moveTo/lineTo work.pts = work_pts; work.n = 0; SDL_PauseAudio(0); } //fill the buffer with loops of currFrame, switching to nextFrame if it's available void cb_fill_audio(void *udata, Uint8 *stream, int len) { //len is BYTES static int pos = 0; //position in currFrame (in bytes) int left = len; //bytes we still need to do int done = 0; int frameLeft; //bytes left in currFrame int toCopy; //bytes for this memcpy while(left > 0) { frameLeft = currFrame.n*4 - pos; // *4 because frame n values are in sample-pairs if(frameLeft < left) toCopy = frameLeft; else toCopy = left; if(toCopy > 0) memcpy(stream+done, ((Uint8*)currFrame.samples)+pos, toCopy); left -= toCopy; done += toCopy; pos += toCopy; frameLeft -= toCopy; if(frameLeft <= 0) { if(frameLeft<0) fprintf(stderr, "frameLeft is %d !?!?!?\n", frameLeft); //reached the end of this frame pos = 0; if(nextFrame.samples != NULL) { //new frame available! //replace currFrame with nextFrame free(currFrame.samples); memcpy(&currFrame, &nextFrame, sizeof(struct frame)); memset(&nextFrame, 0, sizeof(struct frame)); } } } } //submits vl is the next frame to draw, by rendering it to a frame of samples //if a nextFrame is already waiting, it is overwritten and freed //**does NOT free vl or its point list** void sendFrame(struct vlist *vl) { int i, pt, steps, pos=0; double X, Y, t, nextX, nextY, dX, dY; Sint16 iX, iY; Sint16 *buf; int bufsiz=0; //buffer size in L/R pairs of samples //find buffer size for(pt = 1; pt < vl->n; pt++) bufsiz += vl->pts[3*pt+2]+1; //allocate buffer buf = malloc(bufsiz * 4); // *4 for 2 16-bit samples for(pt = 1; pt < vl->n; pt++) { X = vl->pts[3*(pt-1)+0]; //start at previous point Y = vl->pts[3*(pt-1)+1]; nextX = vl->pts[3*pt+0]; //head toward current point nextY = vl->pts[3*pt+1]; steps = vl->pts[3*pt+2]+1; //fprintf(stderr, "\t%lf, %lf, %d\n", X, Y, steps); //DEBUG: output points dX = (nextX-X)/(double)steps; dY = (nextY-Y)/(double)steps; for(i=0; i<steps; i++) { if(flipX) { iX = (Sint16)(((int)X)-32768); } else { iX = (Sint16)(((int)(0x0ffff-(Uint16)X))-32768); } if(flipY) { iY = (Sint16)(((int)(0x0ffff-(Uint16)Y))-32768); } else { iY = (Sint16)(((int)Y)-32768); } if(swapXY) { buf[pos++] = iX; buf[pos++] = iY; } else { buf[pos++] = iY; buf[pos++] = iX; } X += dX; Y += dY; } } //DEBUG: sanity check if(pos != bufsiz*2) fprintf(stderr, "sendFrame: calculated %d samples needed, but used %d\n", bufsiz*2, pos); //fprintf(stderr, "Frame is %d samples, %lf Hz refresh\n", bufsiz, ((double)g_freq)/bufsiz); //DEBUG: frame size and refresh rate g_refresh = ((double)g_freq)/bufsiz; //DEBUG: write frame to raw audio file //FILE *f = fopen("frame.raw", "wb"); //fwrite(buf, bufsiz*4, 1, f); //fclose(f); //save this to nextFrame if(nextFrame.samples != NULL) { //DEBUG: warn of dropped frame //fprintf(stderr, "sendFrame: dropped frame of size %d because one of size %d didn't finish drawing in time; replacing with one of size %d\n", nextFrame.n, currFrame.n, bufsiz); free(nextFrame.samples); } nextFrame.n = bufsiz; nextFrame.samples = buf; } //set screen size for moveTo/lineTo //xleft/xright are the X coordinate of the left/right edge of the screen //ytop/ybottom similarly void setScale(double xleft, double xright, double ytop, double ybottom, double weight) { xmin = xleft; xmax = xright; ymin = ytop; ymax = ybottom; targetWeight = weight; } //move the cursor to a point on the screen void moveTo(double x, double y) { lineTo(x, y, 0); } //draw a line to a point on the screen //color ranges from 0 (invisible) to 1 (bright) or more //if x or y are outside the screen, they simply get clamped to screen edges void lineTo(double x, double y, double color) { //quit if vector list is full for this frame if(work.n >= MAX_POINTS) return; //scale to 0..65535 if(xmin == xmax) x=32768; //X axis flattened ==> go to middle else x = ((x-xmin)/(xmax-xmin))*65535; if(ymin == ymax) y=32768; //Y axis flattened ==> go to middle else y = ((y-ymin)/(ymax-ymin))*65535; //clamp to screen edges if(x < 0) x=0; else if(x > 65535) x=65535; if(y < 0) y=0; else if(y > 65535) y=65535; if(work.n > 0) { double xDist, yDist, lineLen, newColor; //there's a previous point we're drawing a line from //calculate steps from color and line length xDist = work.pts[(work.n-1)*3+0] - x; yDist = work.pts[(work.n-1)*3+1] - y; lineLen = sqrt(xDist*xDist + yDist*yDist)/65535; if(lineLen < 0.00002) lineLen = 5.0/100.0; //allow "dwelling" on a point to draw a bright dot //65 is a good number of steps for a bright line all the way across the screen color = color*lineLen*targetWeight; if(color < 1.0) color=1.0; } else color=0; //first point must be a moveTo //append to list work.pts[work.n*3+0] = (Uint16)x; work.pts[work.n*3+1] = (Uint16)y; work.pts[work.n*3+2] = (Uint16)color; work.n++; } void flip(int clear) { sendFrame(&work); if(clear) work.n = 0; } void setMode(int mode) { flipX = mode&1; flipY = mode&2; swapXY = mode&4; } double getRefreshRate(void) { return g_refresh; }
28.992593
179
0.670797
d64b85de6d0989992e22f619b5790f1baf221496
758
h
C
include/entities/projectiles.h
projectivemotion/sdlgame1
9e126b6ef096605008dfc5db8e9264b68582b38a
[ "MIT" ]
null
null
null
include/entities/projectiles.h
projectivemotion/sdlgame1
9e126b6ef096605008dfc5db8e9264b68582b38a
[ "MIT" ]
null
null
null
include/entities/projectiles.h
projectivemotion/sdlgame1
9e126b6ef096605008dfc5db8e9264b68582b38a
[ "MIT" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: projectiles.h * Author: eye * * Created on September 17, 2019, 11:56 PM */ #ifndef PROJECTILES_H #define PROJECTILES_H #include "app/AppClass.h" #include "entities/entity.h" #include <list> typedef struct { entity<SDL_Texture>* ball; SDL_Rect speed; } projectile; class projectiles { public: projectiles(); projectiles(const projectiles& orig); void draw(AppClass& app); void fire(entity<SDL_Texture>* e, SDL_Rect speed); virtual ~projectiles(); private: std::list<projectile> flying; }; #endif /* PROJECTILES_H */
19.435897
79
0.695251
326f4eb6c4bfa9e16c8bdb28c9c2bfc2e01ff6f6
2,573
h
C
System/Library/PrivateFrameworks/SilexVideo.framework/SVVideoPlaybackAttemptTrackerManager.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/PrivateFrameworks/SilexVideo.framework/SVVideoPlaybackAttemptTrackerManager.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/SilexVideo.framework/SVVideoPlaybackAttemptTrackerManager.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:16:41 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/SilexVideo.framework/SilexVideo * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <libobjc.A.dylib/SVVideoTransitionObserver.h> @protocol SVVideoPlaybackAttemptTrackerFactory, SVVideoEventTrackerProviding, SVVideoPlaybackAttemptTracking, SVVideoEventTracker; @class NSString; @interface SVVideoPlaybackAttemptTrackerManager : NSObject <SVVideoTransitionObserver> { id<SVVideoPlaybackAttemptTrackerFactory> _playbackAttemptTrackerFactory; id<SVVideoEventTrackerProviding> _eventTrackerProvider; id<SVVideoPlaybackAttemptTracking> _playbackAttemptTracker; id<SVVideoEventTracker> _eventTracker; } @property (nonatomic,readonly) id<SVVideoPlaybackAttemptTrackerFactory> playbackAttemptTrackerFactory; //@synthesize playbackAttemptTrackerFactory=_playbackAttemptTrackerFactory - In the implementation block @property (nonatomic,readonly) id<SVVideoEventTrackerProviding> eventTrackerProvider; //@synthesize eventTrackerProvider=_eventTrackerProvider - In the implementation block @property (nonatomic,retain) id<SVVideoPlaybackAttemptTracking> playbackAttemptTracker; //@synthesize playbackAttemptTracker=_playbackAttemptTracker - In the implementation block @property (nonatomic,retain) id<SVVideoEventTracker> eventTracker; //@synthesize eventTracker=_eventTracker - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; -(id<SVVideoEventTracker>)eventTracker; -(void)willTransitionToVideo:(id)arg1 withTransitionCoordinator:(id)arg2 ; -(void)setEventTracker:(id<SVVideoEventTracker>)arg1 ; -(id<SVVideoEventTrackerProviding>)eventTrackerProvider; -(id)initWithPlaybackAttemptTrackerFactory:(id)arg1 eventTrackerProvider:(id)arg2 ; -(id<SVVideoPlaybackAttemptTrackerFactory>)playbackAttemptTrackerFactory; -(void)setPlaybackAttemptTracker:(id<SVVideoPlaybackAttemptTracking>)arg1 ; -(id<SVVideoPlaybackAttemptTracking>)playbackAttemptTracker; @end
62.756098
220
0.758647
65382b93cc6c088ed17e7c7193a232990f17232d
1,243
h
C
apps/legato_quickstart/firmware/src/config/lcdc_rgba8888_mxt_a5d2_wvga_iar/gfx/legato/generated/screen/le_gen_screen_Screen0.h
Microchip-MPLAB-Harmony/gfx_apps_sam_a5d2
649f1fe7aad45f7cdabfc1c726c3850a6adf68d9
[ "0BSD" ]
null
null
null
apps/legato_quickstart/firmware/src/config/lcdc_rgba8888_mxt_a5d2_wvga_iar/gfx/legato/generated/screen/le_gen_screen_Screen0.h
Microchip-MPLAB-Harmony/gfx_apps_sam_a5d2
649f1fe7aad45f7cdabfc1c726c3850a6adf68d9
[ "0BSD" ]
null
null
null
apps/legato_quickstart/firmware/src/config/lcdc_rgba8888_mxt_a5d2_wvga_iar/gfx/legato/generated/screen/le_gen_screen_Screen0.h
Microchip-MPLAB-Harmony/gfx_apps_sam_a5d2
649f1fe7aad45f7cdabfc1c726c3850a6adf68d9
[ "0BSD" ]
null
null
null
#ifndef LE_GEN_SCREEN_SCREEN0_H #define LE_GEN_SCREEN_SCREEN0_H #include "gfx/legato/legato.h" #include "gfx/legato/generated/le_gen_scheme.h" #include "gfx/legato/generated/le_gen_assets.h" // DOM-IGNORE-BEGIN #ifdef __cplusplus // Provide C++ Compatibility extern "C" { #endif // DOM-IGNORE-END // screen member widget declarations extern leWidget* Screen0_default_Layer0_FillPanel; extern leImageWidget* Screen0_ImageWidget0; extern leLabelWidget* Screen0_LabelWidget2; extern leLabelWidget* Screen0_LabelWidget1; extern leLabelWidget* Screen0_LabelWidget0; extern leButtonWidget* Screen0_ButtonWidget1; extern leImageWidget* Screen0_ImageWidget1; // screen lifecycle functions // DO NOT CALL THESE DIRECTLY leResult screenInit_Screen0(void); // called when Legato is initialized leResult screenShow_Screen0(void); // called when screen is shown void screenHide_Screen0(void); // called when screen is hidden void screenDestroy_Screen0(void); // called when Legato is destroyed void screenUpdate_Screen0(void); // called when Legato is updating leWidget* screenGetRoot_Screen0(uint32_t lyrIdx); // gets a root widget for this screen //DOM-IGNORE-BEGIN #ifdef __cplusplus } #endif //DOM-IGNORE-END #endif // LE_GEN_SCREEN_SCREEN0_H
30.317073
87
0.81255
a998e1ad31c6fdc0bde9678c5654638b74fc51ea
1,922
h
C
src/canvas.h
meisterT/katarakt
a4e4b4840e49845fd6df82ce047f7be9b9ac199a
[ "BSD-2-Clause" ]
3
2017-07-29T12:25:01.000Z
2018-03-23T15:16:34.000Z
src/canvas.h
meisterT/katarakt
a4e4b4840e49845fd6df82ce047f7be9b9ac199a
[ "BSD-2-Clause" ]
1
2016-11-18T13:14:34.000Z
2016-11-18T13:14:34.000Z
src/canvas.h
meisterT/katarakt
a4e4b4840e49845fd6df82ce047f7be9b9ac199a
[ "BSD-2-Clause" ]
null
null
null
#ifndef CANVAS_H #define CANVAS_H #include <QWidget> #include <QPaintEvent> #include <QMouseEvent> #include <QWheelEvent> #include <QResizeEvent> #include <QList> #include <QTimer> #include <sys/socket.h> class Viewer; class Layout; class SingleLayout; class GridLayout; class PresenterLayout; class GotoLine; class QLabel; class Canvas : public QWidget { Q_OBJECT public: Canvas(Viewer *v, QWidget *parent = 0); ~Canvas(); bool is_valid() const; void reload(bool clamp); void set_search_visible(bool visible); Layout *get_layout() const; void update_page_overlay(); protected: // QT event handling void paintEvent(QPaintEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void wheelEvent(QWheelEvent *event); void mouseDoubleClickEvent(QMouseEvent * event); void resizeEvent(QResizeEvent *event); signals: /** * Emitted when the user requests to see the source code of a * particular point on a particular page. */ void synchronize_editor(int page, int x, int y); private slots: void page_rendered(int page); void goto_page(); // primitive actions void set_single_layout(); void set_grid_layout(); void set_presenter_layout(); void toggle_overlay(); void focus_goto(); void disable_triple_click(); void swap_selection_and_panning_buttons(); private: void setup_keys(QWidget *base); Viewer *viewer; Layout *cur_layout; SingleLayout *single_layout; GridLayout *grid_layout; PresenterLayout *presenter_layout; GotoLine *goto_line; QLabel *page_overlay; int mx, my; int mx_down, my_down; bool triple_click_possible; QTimer scroll_timer; bool valid; // config options QColor background; QColor background_fullscreen; int mouse_wheel_factor; Qt::MouseButton click_link_button; Qt::MouseButton drag_view_button; Qt::MouseButton select_text_button; }; #endif
18.660194
62
0.763788
803620d8b93f2b91d9c3b2d5e1176890a2e04532
9,082
h
C
IOKit/kext/KextManager.h
Lakr233/IOKit-Headers
92a73c77359f80dc17ab747a9805134cc87765b4
[ "MIT" ]
4
2021-02-03T23:48:28.000Z
2022-01-05T22:58:45.000Z
IOKit/kext/KextManager.h
Lakr233/IOKit-Headers
92a73c77359f80dc17ab747a9805134cc87765b4
[ "MIT" ]
null
null
null
IOKit/kext/KextManager.h
Lakr233/IOKit-Headers
92a73c77359f80dc17ab747a9805134cc87765b4
[ "MIT" ]
1
2021-02-02T09:54:09.000Z
2021-02-02T09:54:09.000Z
/* * Copyright (c) 2000-2008, 2012 Apple Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ #ifndef __KEXTMANAGER_H__ #define __KEXTMANAGER_H__ #include <CoreFoundation/CoreFoundation.h> #include <libkern/OSReturn.h> #include <sys/cdefs.h> __BEGIN_DECLS /*! * @header KextManager.h * * @abstract * The KextManager API provides a simple interface for applications * to load kernel extensions (kexts) via RPC to kextd, and to look up the * URLs for kexts by bundle identifier. */ /*! * @function KextManagerCreateURLForBundleIdentifier * @abstract Create a URL locating a kext with a given bundle identifier. * * @param allocator * The allocator to use to allocate memory for the new object. * Pass <code>NULL</code> or <code>kCFAllocatorDefault</code> * to use the current default allocator. * @param kextIdentifier * The bundle identifier to look up. * * @result * A CFURLRef locating a kext with the requested bundle identifier. * Returns <code>NULL</code> if the kext cannot be found, or on error. * * @discussion * Kexts are looked up first by whether they are loaded, second by version. * Specifically, if <code>kextIdentifier</code> identifies a kext * that is currently loaded, * the returned URL will locate that kext if it's still present on disk. * If the requested kext is not loaded, * or if its bundle is not at the location it was originally loaded from, * the returned URL will locate the latest version of the desired kext, * if one can be found within the system extensions folder. * If no version of the kext can be found, <code>NULL</code> is returned. */ CFURLRef KextManagerCreateURLForBundleIdentifier( CFAllocatorRef allocator, CFStringRef kextIdentifier) AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER; /*! * @function KextManagerLoadKextWithIdentifier * @abstract * Request the kext loading system to load a kext with a given bundle identifier. * * @param kextIdentifier * The bundle identifier of the kext to look up and load. * @param dependencyKextAndFolderURLs * An array of additional URLs, of individual kexts and * of folders that may contain kexts. * * @result * <code>kOSReturnSuccess</code> if the kext is successfully loaded * (or is already loaded), otherwise returns on error. * * @discussion * <code>kextIdentifier</code> is looked up in the system extensions * folder and among any kexts from <code>dependencyKextAndFolderURLs</code>. * Any non-kext URLs in <code>dependencyKextAndFolderURLs</code> * are scanned at the top level for kexts and plugins of kexts. * * Either the calling process must have an effective user id of 0 (superuser), * or the kext being loaded and all its dependencies must reside in * /System and have an OSBundleAllowUserLoad property of <code>true</code>. */ OSReturn KextManagerLoadKextWithIdentifier( CFStringRef kextIdentifier, CFArrayRef dependencyKextAndFolderURLs) AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER; /*! * @function KextManagerLoadKextWithURL * @abstract * Request the kext loading system to load a kext with a given URL. * * @param kextURL * The URL of the kext to load. * @param dependencyKextAndFolderURLs * An array of additional URLs, of individual kexts and * of folders that may contain kexts. * * @result * <code>kOSReturnSuccess</code> if the kext is successfully loaded * (or is already loaded), otherwise returns on error. * * @discussion * Any non-kext URLs in <code>dependencyKextAndFolderURLs</code> * are scanned at the top level for kexts and plugins of kexts. * * Either the calling process must have an effective user id of 0 (superuser), * or the kext being loaded and all its dependencies must reside in * /System and have an OSBundleAllowUserLoad property of <code>true</code>. */ OSReturn KextManagerLoadKextWithURL( CFURLRef kextURL, CFArrayRef dependencyKextAndFolderURLs) AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER; /*! * @function KextManagerUnloadKextWithIdentifier * @abstract * Request the kernel to unload a kext with a given bundle identifier. * * @param kextIdentifier * The bundle identifier of the kext to unload. * * @result * <code>kOSReturnSuccess</code> if the kext is * found and successfully unloaded, * otherwise returns on error. * See <code>/usr/include/libkern/OSKextLib.h</code> * for error codes. * * @discussion * The calling process must have an effective user id of 0 (superuser). */ OSReturn KextManagerUnloadKextWithIdentifier( CFStringRef kextIdentifier) AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER; /*! * @function KextManagerCopyLoadedKextInfo * @abstract Returns information about loaded kexts in a dictionary. * * @param kextIdentifiers An array of kext identifiers to read from the kernel. * Pass <code>NULL</code> to read info for all loaded kexts. * @param infoKeys An array of info keys to read from the kernel. * Pass <code>NULL</code> to read all information. * @result * A dictionary, keyed by bundle identifier, * of dictionaries containing information about loaded kexts. * * @discussion * The information keys returned by this function are listed below. * Some are taken directly from the kext's information property list, * and some are generated at run time. * Never assume a given key will be present for a kext. * * <ul> * <li><code>CFBundleIdentifier</code> - CFString</li> * <li><code>CFBundleVersion</code> - CFString (note: version strings may be canonicalized * but their numeric values will be the same; "1.2.0" may become "1.2", for example)</li> * <li><code>OSBundleCompatibleVersion</code> - CFString</li> * <li><code>OSBundleIsInterface</code> - CFBoolean</li> * <li><code>OSKernelResource</code> - CFBoolean</li> * <li><code>OSBundleCPUType</code> - CFNumber</li> * <li><code>OSBundleCPUSubtype</code> - CFNumber</li> * <li><code>OSBundlePath</code> - CFString (this is merely a hint stored in the kernel; * the kext is not guaranteed to be at this path)</li> * <li><code>OSBundleExecutablePath</code> - CFString * (the absolute path to the executable within the kext bundle; a hint as above)</li> * <li><code>OSBundleUUID</code> - CFData (the UUID of the kext executable, if it has one)</li> * <li><code>OSBundleStarted</code> - CFBoolean (true if the kext is running)</li> * <li><code>OSBundlePrelinked</code> - CFBoolean (true if the kext is loaded from a prelinked kernel)</li> * <li><code>OSBundleLoadTag</code> - CFNumber (the "Index" given by kextstat)</li> * <li><code>OSBundleLoadAddress</code> - CFNumber</li> * <li><code>OSBundleLoadSize</code> - CFNumber</li> * <li><code>OSBundleWiredSize</code> - CFNumber</li> * <li><code>OSBundleDependencies</code> - CFArray of load tags identifying immediate link dependencies</li> * <li><code>OSBundleRetainCount</code> - CFNumber (the OSObject retain count of the kext itself)</li> * <li><code>OSBundleClasses</code> - CFArray of CFDictionary containing info on C++ classes * defined by the kext:</li> * <ul> * <li><code>OSMetaClassName</code> - CFString</li> * <li><code>OSMetaClassSuperclassName</code> - CFString, absent for root classes</li> * <li><code>OSMetaClassTrackingCount</code> - CFNumber giving the instance count * of the class itself, <i>plus</i> 1 for each direct subclass with any instances</li> * </ul> * </ul> */ CFDictionaryRef KextManagerCopyLoadedKextInfo( CFArrayRef kextIdentifiers, CFArrayRef infoKeys) AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER; __END_DECLS #endif /* __KEXTMANAGER_H__ */
42.839623
110
0.722638
4e50a3267f5dfa4860aa09364e6c3787ca31a3ae
1,870
h
C
kernel/include/socket.h
nelsoncole/sirius-x86-64
741370f204a1da1fab2547e395f737cd383aee19
[ "BSD-3-Clause" ]
10
2021-08-18T22:37:50.000Z
2022-02-07T11:12:32.000Z
kernel/include/socket.h
nelsoncole/sirius-x86-64
741370f204a1da1fab2547e395f737cd383aee19
[ "BSD-3-Clause" ]
null
null
null
kernel/include/socket.h
nelsoncole/sirius-x86-64
741370f204a1da1fab2547e395f737cd383aee19
[ "BSD-3-Clause" ]
null
null
null
#ifndef __SOCKET_H__ #define __SOCKET_H__ #define AF_UNSPEC 0 #define AF_LOCAL 1 // Machine-local comms #define AF_INET 2 // IPv4 #define PF_INET6 3 // IPv6 #define PF_PACKET 4 // Low level packet interface #define SOCK_STREAM 1 #define SOCK_DGRAM 2 #define SOCK_SEQPACKET 3 struct socket { int id; int domain; int type; int protocol; unsigned short src_port; unsigned int src_ip; unsigned short dest_port; unsigned int dest_ip; // For TCP unsigned int seq; unsigned int ack; unsigned char protocol_flags; unsigned short src_win; unsigned short dst_win; // cache unsigned int seq_x; unsigned int ack_x; unsigned char flags; unsigned int length1; unsigned int length2; unsigned long buf1; unsigned long buf2; unsigned char num_client; struct socket *client; struct socket *next; }__attribute__((packed)); struct socket_receive_row{ unsigned char status; unsigned char protocol; unsigned short src_port; unsigned int src_ip; unsigned short dest_port; unsigned int dest_ip; // For TCP unsigned int seq; unsigned int ack; unsigned char flags; unsigned short win; unsigned char *buffer; unsigned length; }__attribute__ ((packed)); extern struct socket *current_saddr, *saddr_ready_queue; void socket_server_transmit(); int socket_server_receive(int origem, int protocol, unsigned int src_ip, unsigned int dest_ip, unsigned short src_port, unsigned short dest_port, const void *buffer, unsigned length, unsigned int seq, unsigned int ack, unsigned char flags); void socket_execute_row(); int init_socket(int domain, int type, int protocol); int socket(int domain, int type, int protocol); #endif
22.261905
145
0.67754
087475eec80a8af2470d71f9a41788c559b2639a
1,268
c
C
c/libcurl/libcurltest.c
jdmichaud/snippets
1af85cf25156231165838b309860586f62bf43e2
[ "Apache-2.0" ]
null
null
null
c/libcurl/libcurltest.c
jdmichaud/snippets
1af85cf25156231165838b309860586f62bf43e2
[ "Apache-2.0" ]
null
null
null
c/libcurl/libcurltest.c
jdmichaud/snippets
1af85cf25156231165838b309860586f62bf43e2
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <string.h> #include <curl/curl.h> int isProtocolPresent(const char * const * protocols, char *protocol) { for (int i = 0; protocols[i]; ++i) if (strncmp("https", protocols[i], strlen(protocol)) == 0) return 1; return 0; } int main(int argc, char **argv) { CURL *curl; CURLcode res; // Initial libcurl curl_global_init(CURL_GLOBAL_SSL); curl_version_info_data *curl_info = curl_version_info(CURLVERSION_NOW); fprintf(stdout, "curl version: %s (SSL: %s, HTTPS: %s)\n", curl_info->version, curl_info->features & CURL_VERSION_SSL ? "OK" : "NOK!", isProtocolPresent(curl_info->protocols, "https") ? "OK" : "NOK!"); curl = curl_easy_init(); if (curl) { // Do not verify certificate curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); // Perform a POST curl_easy_setopt(curl, CURLOPT_POST, 1L); // Provide the URL curl_easy_setopt(curl, CURLOPT_URL, "https://localhost:8000/sensor/1/1"); // Perform a PUT res = curl_easy_perform(curl); if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } curl_easy_cleanup(curl); // Power down libcurl curl_global_cleanup(); return 0; }
30.190476
77
0.654574
0c08c250f04811944d9408502e02c7342ff63a99
2,360
h
C
panda/src/tinydisplay/tinyOffscreenGraphicsPipe.h
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
panda/src/tinydisplay/tinyOffscreenGraphicsPipe.h
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
panda/src/tinydisplay/tinyOffscreenGraphicsPipe.h
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: tinyOffscreenGraphicsPipe.h // Created by: drose (09Feb09) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #ifndef TINYOFFSCREENGRAPHICSPIPE_H #define TINYOFFSCREENGRAPHICSPIPE_H #include "pandabase.h" #include "graphicsWindow.h" #include "graphicsPipe.h" #include "tinyGraphicsStateGuardian.h" class FrameBufferProperties; //////////////////////////////////////////////////////////////////// // Class : TinyOffscreenGraphicsPipe // Description : This graphics pipe creates offscreen buffers only, // but is completely platform-independent. //////////////////////////////////////////////////////////////////// class EXPCL_TINYDISPLAY TinyOffscreenGraphicsPipe : public GraphicsPipe { public: TinyOffscreenGraphicsPipe(); virtual ~TinyOffscreenGraphicsPipe(); virtual string get_interface_name() const; static PT(GraphicsPipe) pipe_constructor(); protected: virtual PT(GraphicsOutput) make_output(const string &name, const FrameBufferProperties &fb_prop, const WindowProperties &win_prop, int flags, GraphicsEngine *engine, GraphicsStateGuardian *gsg, GraphicsOutput *host, int retry, bool &precertify); public: static TypeHandle get_class_type() { return _type_handle; } static void init_type() { GraphicsPipe::init_type(); register_type(_type_handle, "TinyOffscreenGraphicsPipe", GraphicsPipe::get_class_type()); } virtual TypeHandle get_type() const { return get_class_type(); } virtual TypeHandle force_init_type() {init_type(); return get_class_type();} private: static TypeHandle _type_handle; }; #include "tinyOffscreenGraphicsPipe.I" #endif
33.714286
78
0.563983
263772f5396e7d3fe6e940b4cea6156bd704efac
7,544
c
C
src/cmd/join.c
newluhux/plan9port
f403539d479c1ecb60988e6d87f9031b1435f794
[ "MIT" ]
1,391
2015-01-02T22:15:05.000Z
2022-03-31T04:53:12.000Z
src/cmd/join.c
Acidburn0zzz/plan9port
da8a485fc143aa323845fafcf0f0f836c76a116b
[ "LPL-1.02" ]
441
2015-01-03T07:11:09.000Z
2022-03-31T13:12:22.000Z
src/cmd/join.c
Acidburn0zzz/plan9port
da8a485fc143aa323845fafcf0f0f836c76a116b
[ "LPL-1.02" ]
404
2015-01-03T13:00:57.000Z
2022-03-18T09:43:37.000Z
/* join F1 F2 on stuff */ #include <u.h> #include <libc.h> #include <stdio.h> #include <ctype.h> #define F1 0 #define F2 1 #define F0 3 #define NFLD 100 /* max field per line */ #define comp() runecmp(ppi[F1][j1],ppi[F2][j2]) FILE *f[2]; Rune buf[2][BUFSIZ]; /*input lines */ Rune *ppi[4][NFLD+1]; /* pointers to fields in lines */ Rune *s1,*s2; #define j1 joinj1 #define j2 joinj2 int j1 = 1; /* join of this field of file 1 */ int j2 = 1; /* join of this field of file 2 */ int olist[2*NFLD]; /* output these fields */ int olistf[2*NFLD]; /* from these files */ int no; /* number of entries in olist */ Rune sep1 = ' '; /* default field separator */ Rune sep2 = '\t'; char *sepstr=" "; int discard; /* count of truncated lines */ Rune null[BUFSIZ]/* = L""*/; int a1; int a2; char *getoptarg(int*, char***); void output(int, int); int input(int); void oparse(char*); void error(char*, char*); void seek1(void), seek2(void); Rune *strtorune(Rune *, char *); void main(int argc, char **argv) { int i; while (argc > 1 && argv[1][0] == '-') { if (argv[1][1] == '\0') break; switch (argv[1][1]) { case '-': argc--; argv++; goto proceed; case 'a': switch(*getoptarg(&argc, &argv)) { case '1': a1++; break; case '2': a2++; break; default: error("incomplete option -a",""); } break; case 'e': strtorune(null, getoptarg(&argc, &argv)); break; case 't': sepstr=getoptarg(&argc, &argv); chartorune(&sep1, sepstr); sep2 = sep1; break; case 'o': if(argv[1][2]!=0 || argc>2 && strchr(argv[2],',')!=0) oparse(getoptarg(&argc, &argv)); else for (no = 0; no<2*NFLD && argc>2; no++){ if (argv[2][0] == '1' && argv[2][1] == '.') { olistf[no] = F1; olist[no] = atoi(&argv[2][2]); } else if (argv[2][0] == '2' && argv[2][1] == '.') { olist[no] = atoi(&argv[2][2]); olistf[no] = F2; } else if (argv[2][0] == '0') olistf[no] = F0; else break; argc--; argv++; } break; case 'j': if(argc <= 2) break; if (argv[1][2] == '1') j1 = atoi(argv[2]); else if (argv[1][2] == '2') j2 = atoi(argv[2]); else j1 = j2 = atoi(argv[2]); argc--; argv++; break; case '1': j1 = atoi(getoptarg(&argc, &argv)); break; case '2': j2 = atoi(getoptarg(&argc, &argv)); break; } argc--; argv++; } proceed: for (i = 0; i < no; i++) if (olist[i]-- > NFLD) /* 0 origin */ error("field number too big in -o",""); if (argc != 3) error("usage: join [-1 x -2 y] [-o list] file1 file2",""); j1--; j2--; /* everyone else believes in 0 origin */ s1 = ppi[F1][j1]; s2 = ppi[F2][j2]; if (strcmp(argv[1], "-") == 0) f[F1] = stdin; else if ((f[F1] = fopen(argv[1], "r")) == 0) error("can't open %s", argv[1]); if(strcmp(argv[2], "-") == 0) { f[F2] = stdin; } else if ((f[F2] = fopen(argv[2], "r")) == 0) error("can't open %s", argv[2]); if(ftell(f[F2]) >= 0) seek2(); else if(ftell(f[F1]) >= 0) seek1(); else error("neither file is randomly accessible",""); if (discard) error("some input line was truncated", ""); exits(""); } int runecmp(Rune *a, Rune *b){ while(*a==*b){ if(*a=='\0') return 0; a++; b++; } if(*a<*b) return -1; return 1; } char *runetostr(char *buf, Rune *r){ char *s; for(s=buf;*r;r++) s+=runetochar(s, r); *s='\0'; return buf; } Rune *strtorune(Rune *buf, char *s){ Rune *r; for(r=buf;*s;r++) s+=chartorune(r, s); *r='\0'; return buf; } /* lazy. there ought to be a clean way to combine seek1 & seek2 */ #define get1() n1=input(F1) #define get2() n2=input(F2) void seek2(void) { int n1, n2; int top2=0; int bot2 = ftell(f[F2]); get1(); get2(); while(n1>0 && n2>0 || (a1||a2) && n1+n2>0) { if(n1>0 && n2>0 && comp()>0 || n1==0) { if(a2) output(0, n2); bot2 = ftell(f[F2]); get2(); } else if(n1>0 && n2>0 && comp()<0 || n2==0) { if(a1) output(n1, 0); get1(); } else /*(n1>0 && n2>0 && comp()==0)*/ { while(n2>0 && comp()==0) { output(n1, n2); top2 = ftell(f[F2]); get2(); } fseek(f[F2], bot2, 0); get2(); get1(); for(;;) { if(n1>0 && n2>0 && comp()==0) { output(n1, n2); get2(); } else if(n1>0 && n2>0 && comp()<0 || n2==0) { fseek(f[F2], bot2, 0); get2(); get1(); } else /*(n1>0 && n2>0 && comp()>0 || n1==0)*/{ fseek(f[F2], top2, 0); bot2 = top2; get2(); break; } } } } } void seek1(void) { int n1, n2; int top1=0; int bot1 = ftell(f[F1]); get1(); get2(); while(n1>0 && n2>0 || (a1||a2) && n1+n2>0) { if(n1>0 && n2>0 && comp()>0 || n1==0) { if(a2) output(0, n2); get2(); } else if(n1>0 && n2>0 && comp()<0 || n2==0) { if(a1) output(n1, 0); bot1 = ftell(f[F1]); get1(); } else /*(n1>0 && n2>0 && comp()==0)*/ { while(n2>0 && comp()==0) { output(n1, n2); top1 = ftell(f[F1]); get1(); } fseek(f[F1], bot1, 0); get2(); get1(); for(;;) { if(n1>0 && n2>0 && comp()==0) { output(n1, n2); get1(); } else if(n1>0 && n2>0 && comp()>0 || n1==0) { fseek(f[F1], bot1, 0); get2(); get1(); } else /*(n1>0 && n2>0 && comp()<0 || n2==0)*/{ fseek(f[F1], top1, 0); bot1 = top1; get1(); break; } } } } } int input(int n) /* get input line and split into fields */ { register int i, c; Rune *bp; Rune **pp; char line[BUFSIZ]; bp = buf[n]; pp = ppi[n]; if (fgets(line, BUFSIZ, f[n]) == 0) return(0); strtorune(bp, line); i = 0; do { i++; if (sep1 == ' ') /* strip multiples */ while ((c = *bp) == sep1 || c == sep2) bp++; /* skip blanks */ *pp++ = bp; /* record beginning */ while ((c = *bp) != sep1 && c != '\n' && c != sep2 && c != '\0') bp++; *bp++ = '\0'; /* mark end by overwriting blank */ } while (c != '\n' && c != '\0' && i < NFLD-1); if (c != '\n') discard++; *pp = 0; return(i); } void output(int on1, int on2) /* print items from olist */ { int i; Rune *temp; char buf[BUFSIZ]; if (no <= 0) { /* default case */ printf("%s", runetostr(buf, on1? ppi[F1][j1]: ppi[F2][j2])); for (i = 0; i < on1; i++) if (i != j1) printf("%s%s", sepstr, runetostr(buf, ppi[F1][i])); for (i = 0; i < on2; i++) if (i != j2) printf("%s%s", sepstr, runetostr(buf, ppi[F2][i])); printf("\n"); } else { for (i = 0; i < no; i++) { if (olistf[i]==F0 && on1>j1) temp = ppi[F1][j1]; else if (olistf[i]==F0 && on2>j2) temp = ppi[F2][j2]; else { temp = ppi[olistf[i]][olist[i]]; if(olistf[i]==F1 && on1<=olist[i] || olistf[i]==F2 && on2<=olist[i] || *temp==0) temp = null; } printf("%s", runetostr(buf, temp)); if (i == no - 1) printf("\n"); else printf("%s", sepstr); } } } void error(char *s1, char *s2) { fprintf(stderr, "join: "); fprintf(stderr, s1, s2); fprintf(stderr, "\n"); exits(s1); } char * getoptarg(int *argcp, char ***argvp) { int argc = *argcp; char **argv = *argvp; if(argv[1][2] != 0) return &argv[1][2]; if(argc<=2 || argv[2][0]=='-') error("incomplete option %s", argv[1]); *argcp = argc-1; *argvp = ++argv; return argv[1]; } void oparse(char *s) { for (no = 0; no<2*NFLD && *s; no++, s++) { switch(*s) { case 0: return; case '0': olistf[no] = F0; break; case '1': case '2': if(s[1] == '.' && isdigit((uchar)s[2])) { olistf[no] = *s=='1'? F1: F2; olist[no] = atoi(s += 2); break; } /* fall thru */ default: error("invalid -o list", ""); } if(s[1] == ',') s++; } }
20.389189
67
0.494433
d3f15feb837a6cfabeea5086269488378a05ea8b
111,656
c
C
FreeBSD/sys/dev/ti/if_ti.c
TigerBSD/FreeBSD-Custom-ThinkPad
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
4
2016-08-22T22:02:55.000Z
2017-03-04T22:56:44.000Z
FreeBSD/sys/dev/ti/if_ti.c
TigerBSD/FreeBSD-Custom-ThinkPad
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
21
2016-08-11T09:43:43.000Z
2017-01-29T12:52:56.000Z
FreeBSD/sys/dev/ti/if_ti.c
TigerBSD/TigerBSD
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
null
null
null
/*- * Copyright (c) 1997, 1998, 1999 * Bill Paul <wpaul@ctr.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. */ /* * Alteon Networks Tigon PCI gigabit ethernet driver for FreeBSD. * Manuals, sample driver and firmware source kits are available * from http://www.alteon.com/support/openkits. * * Written by Bill Paul <wpaul@ctr.columbia.edu> * Electrical Engineering Department * Columbia University, New York City */ /* * The Alteon Networks Tigon chip contains an embedded R4000 CPU, * gigabit MAC, dual DMA channels and a PCI interface unit. NICs * using the Tigon may have anywhere from 512K to 2MB of SRAM. The * Tigon supports hardware IP, TCP and UCP checksumming, multicast * filtering and jumbo (9014 byte) frames. The hardware is largely * controlled by firmware, which must be loaded into the NIC during * initialization. * * The Tigon 2 contains 2 R4000 CPUs and requires a newer firmware * revision, which supports new features such as extended commands, * extended jumbo receive ring desciptors and a mini receive ring. * * Alteon Networks is to be commended for releasing such a vast amount * of development material for the Tigon NIC without requiring an NDA * (although they really should have done it a long time ago). With * any luck, the other vendors will finally wise up and follow Alteon's * stellar example. * * The firmware for the Tigon 1 and 2 NICs is compiled directly into * this driver by #including it as a C header file. This bloats the * driver somewhat, but it's the easiest method considering that the * driver code and firmware code need to be kept in sync. The source * for the firmware is not provided with the FreeBSD distribution since * compiling it requires a GNU toolchain targeted for mips-sgi-irix5.3. * * The following people deserve special thanks: * - Terry Murphy of 3Com, for providing a 3c985 Tigon 1 board * for testing * - Raymond Lee of Netgear, for providing a pair of Netgear * GA620 Tigon 2 boards for testing * - Ulf Zimmermann, for bringing the GA260 to my attention and * convincing me to write this driver. * - Andrew Gallatin for providing FreeBSD/Alpha support. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include "opt_ti.h" #include <sys/param.h> #include <sys/systm.h> #include <sys/sockio.h> #include <sys/mbuf.h> #include <sys/malloc.h> #include <sys/kernel.h> #include <sys/module.h> #include <sys/socket.h> #include <sys/queue.h> #include <sys/conf.h> #include <sys/sf_buf.h> #include <net/if.h> #include <net/if_var.h> #include <net/if_arp.h> #include <net/ethernet.h> #include <net/if_dl.h> #include <net/if_media.h> #include <net/if_types.h> #include <net/if_vlan_var.h> #include <net/bpf.h> #include <netinet/in_systm.h> #include <netinet/in.h> #include <netinet/ip.h> #include <machine/bus.h> #include <machine/resource.h> #include <sys/bus.h> #include <sys/rman.h> #ifdef TI_SF_BUF_JUMBO #include <vm/vm.h> #include <vm/vm_page.h> #endif #include <dev/pci/pcireg.h> #include <dev/pci/pcivar.h> #include <sys/tiio.h> #include <dev/ti/if_tireg.h> #include <dev/ti/ti_fw.h> #include <dev/ti/ti_fw2.h> #include <sys/sysctl.h> #define TI_CSUM_FEATURES (CSUM_IP | CSUM_TCP | CSUM_UDP) /* * We can only turn on header splitting if we're using extended receive * BDs. */ #if defined(TI_JUMBO_HDRSPLIT) && !defined(TI_SF_BUF_JUMBO) #error "options TI_JUMBO_HDRSPLIT requires TI_SF_BUF_JUMBO" #endif /* TI_JUMBO_HDRSPLIT && !TI_SF_BUF_JUMBO */ typedef enum { TI_SWAP_HTON, TI_SWAP_NTOH } ti_swap_type; /* * Various supported device vendors/types and their names. */ static const struct ti_type ti_devs[] = { { ALT_VENDORID, ALT_DEVICEID_ACENIC, "Alteon AceNIC 1000baseSX Gigabit Ethernet" }, { ALT_VENDORID, ALT_DEVICEID_ACENIC_COPPER, "Alteon AceNIC 1000baseT Gigabit Ethernet" }, { TC_VENDORID, TC_DEVICEID_3C985, "3Com 3c985-SX Gigabit Ethernet" }, { NG_VENDORID, NG_DEVICEID_GA620, "Netgear GA620 1000baseSX Gigabit Ethernet" }, { NG_VENDORID, NG_DEVICEID_GA620T, "Netgear GA620 1000baseT Gigabit Ethernet" }, { SGI_VENDORID, SGI_DEVICEID_TIGON, "Silicon Graphics Gigabit Ethernet" }, { DEC_VENDORID, DEC_DEVICEID_FARALLON_PN9000SX, "Farallon PN9000SX Gigabit Ethernet" }, { 0, 0, NULL } }; static d_open_t ti_open; static d_close_t ti_close; static d_ioctl_t ti_ioctl2; static struct cdevsw ti_cdevsw = { .d_version = D_VERSION, .d_flags = 0, .d_open = ti_open, .d_close = ti_close, .d_ioctl = ti_ioctl2, .d_name = "ti", }; static int ti_probe(device_t); static int ti_attach(device_t); static int ti_detach(device_t); static void ti_txeof(struct ti_softc *); static void ti_rxeof(struct ti_softc *); static int ti_encap(struct ti_softc *, struct mbuf **); static void ti_intr(void *); static void ti_start(struct ifnet *); static void ti_start_locked(struct ifnet *); static int ti_ioctl(struct ifnet *, u_long, caddr_t); static uint64_t ti_get_counter(struct ifnet *, ift_counter); static void ti_init(void *); static void ti_init_locked(void *); static void ti_init2(struct ti_softc *); static void ti_stop(struct ti_softc *); static void ti_watchdog(void *); static int ti_shutdown(device_t); static int ti_ifmedia_upd(struct ifnet *); static int ti_ifmedia_upd_locked(struct ti_softc *); static void ti_ifmedia_sts(struct ifnet *, struct ifmediareq *); static uint32_t ti_eeprom_putbyte(struct ti_softc *, int); static uint8_t ti_eeprom_getbyte(struct ti_softc *, int, uint8_t *); static int ti_read_eeprom(struct ti_softc *, caddr_t, int, int); static void ti_add_mcast(struct ti_softc *, struct ether_addr *); static void ti_del_mcast(struct ti_softc *, struct ether_addr *); static void ti_setmulti(struct ti_softc *); static void ti_mem_read(struct ti_softc *, uint32_t, uint32_t, void *); static void ti_mem_write(struct ti_softc *, uint32_t, uint32_t, void *); static void ti_mem_zero(struct ti_softc *, uint32_t, uint32_t); static int ti_copy_mem(struct ti_softc *, uint32_t, uint32_t, caddr_t, int, int); static int ti_copy_scratch(struct ti_softc *, uint32_t, uint32_t, caddr_t, int, int, int); static int ti_bcopy_swap(const void *, void *, size_t, ti_swap_type); static void ti_loadfw(struct ti_softc *); static void ti_cmd(struct ti_softc *, struct ti_cmd_desc *); static void ti_cmd_ext(struct ti_softc *, struct ti_cmd_desc *, caddr_t, int); static void ti_handle_events(struct ti_softc *); static void ti_dma_map_addr(void *, bus_dma_segment_t *, int, int); static int ti_dma_alloc(struct ti_softc *); static void ti_dma_free(struct ti_softc *); static int ti_dma_ring_alloc(struct ti_softc *, bus_size_t, bus_size_t, bus_dma_tag_t *, uint8_t **, bus_dmamap_t *, bus_addr_t *, const char *); static void ti_dma_ring_free(struct ti_softc *, bus_dma_tag_t *, uint8_t **, bus_dmamap_t, bus_addr_t *); static int ti_newbuf_std(struct ti_softc *, int); static int ti_newbuf_mini(struct ti_softc *, int); static int ti_newbuf_jumbo(struct ti_softc *, int, struct mbuf *); static int ti_init_rx_ring_std(struct ti_softc *); static void ti_free_rx_ring_std(struct ti_softc *); static int ti_init_rx_ring_jumbo(struct ti_softc *); static void ti_free_rx_ring_jumbo(struct ti_softc *); static int ti_init_rx_ring_mini(struct ti_softc *); static void ti_free_rx_ring_mini(struct ti_softc *); static void ti_free_tx_ring(struct ti_softc *); static int ti_init_tx_ring(struct ti_softc *); static void ti_discard_std(struct ti_softc *, int); #ifndef TI_SF_BUF_JUMBO static void ti_discard_jumbo(struct ti_softc *, int); #endif static void ti_discard_mini(struct ti_softc *, int); static int ti_64bitslot_war(struct ti_softc *); static int ti_chipinit(struct ti_softc *); static int ti_gibinit(struct ti_softc *); #ifdef TI_JUMBO_HDRSPLIT static __inline void ti_hdr_split(struct mbuf *top, int hdr_len, int pkt_len, int idx); #endif /* TI_JUMBO_HDRSPLIT */ static void ti_sysctl_node(struct ti_softc *); static device_method_t ti_methods[] = { /* Device interface */ DEVMETHOD(device_probe, ti_probe), DEVMETHOD(device_attach, ti_attach), DEVMETHOD(device_detach, ti_detach), DEVMETHOD(device_shutdown, ti_shutdown), { 0, 0 } }; static driver_t ti_driver = { "ti", ti_methods, sizeof(struct ti_softc) }; static devclass_t ti_devclass; DRIVER_MODULE(ti, pci, ti_driver, ti_devclass, 0, 0); MODULE_DEPEND(ti, pci, 1, 1, 1); MODULE_DEPEND(ti, ether, 1, 1, 1); /* * Send an instruction or address to the EEPROM, check for ACK. */ static uint32_t ti_eeprom_putbyte(struct ti_softc *sc, int byte) { int i, ack = 0; /* * Make sure we're in TX mode. */ TI_SETBIT(sc, TI_MISC_LOCAL_CTL, TI_MLC_EE_TXEN); /* * Feed in each bit and stobe the clock. */ for (i = 0x80; i; i >>= 1) { if (byte & i) { TI_SETBIT(sc, TI_MISC_LOCAL_CTL, TI_MLC_EE_DOUT); } else { TI_CLRBIT(sc, TI_MISC_LOCAL_CTL, TI_MLC_EE_DOUT); } DELAY(1); TI_SETBIT(sc, TI_MISC_LOCAL_CTL, TI_MLC_EE_CLK); DELAY(1); TI_CLRBIT(sc, TI_MISC_LOCAL_CTL, TI_MLC_EE_CLK); } /* * Turn off TX mode. */ TI_CLRBIT(sc, TI_MISC_LOCAL_CTL, TI_MLC_EE_TXEN); /* * Check for ack. */ TI_SETBIT(sc, TI_MISC_LOCAL_CTL, TI_MLC_EE_CLK); ack = CSR_READ_4(sc, TI_MISC_LOCAL_CTL) & TI_MLC_EE_DIN; TI_CLRBIT(sc, TI_MISC_LOCAL_CTL, TI_MLC_EE_CLK); return (ack); } /* * Read a byte of data stored in the EEPROM at address 'addr.' * We have to send two address bytes since the EEPROM can hold * more than 256 bytes of data. */ static uint8_t ti_eeprom_getbyte(struct ti_softc *sc, int addr, uint8_t *dest) { int i; uint8_t byte = 0; EEPROM_START; /* * Send write control code to EEPROM. */ if (ti_eeprom_putbyte(sc, EEPROM_CTL_WRITE)) { device_printf(sc->ti_dev, "failed to send write command, status: %x\n", CSR_READ_4(sc, TI_MISC_LOCAL_CTL)); return (1); } /* * Send first byte of address of byte we want to read. */ if (ti_eeprom_putbyte(sc, (addr >> 8) & 0xFF)) { device_printf(sc->ti_dev, "failed to send address, status: %x\n", CSR_READ_4(sc, TI_MISC_LOCAL_CTL)); return (1); } /* * Send second byte address of byte we want to read. */ if (ti_eeprom_putbyte(sc, addr & 0xFF)) { device_printf(sc->ti_dev, "failed to send address, status: %x\n", CSR_READ_4(sc, TI_MISC_LOCAL_CTL)); return (1); } EEPROM_STOP; EEPROM_START; /* * Send read control code to EEPROM. */ if (ti_eeprom_putbyte(sc, EEPROM_CTL_READ)) { device_printf(sc->ti_dev, "failed to send read command, status: %x\n", CSR_READ_4(sc, TI_MISC_LOCAL_CTL)); return (1); } /* * Start reading bits from EEPROM. */ TI_CLRBIT(sc, TI_MISC_LOCAL_CTL, TI_MLC_EE_TXEN); for (i = 0x80; i; i >>= 1) { TI_SETBIT(sc, TI_MISC_LOCAL_CTL, TI_MLC_EE_CLK); DELAY(1); if (CSR_READ_4(sc, TI_MISC_LOCAL_CTL) & TI_MLC_EE_DIN) byte |= i; TI_CLRBIT(sc, TI_MISC_LOCAL_CTL, TI_MLC_EE_CLK); DELAY(1); } EEPROM_STOP; /* * No ACK generated for read, so just return byte. */ *dest = byte; return (0); } /* * Read a sequence of bytes from the EEPROM. */ static int ti_read_eeprom(struct ti_softc *sc, caddr_t dest, int off, int cnt) { int err = 0, i; uint8_t byte = 0; for (i = 0; i < cnt; i++) { err = ti_eeprom_getbyte(sc, off + i, &byte); if (err) break; *(dest + i) = byte; } return (err ? 1 : 0); } /* * NIC memory read function. * Can be used to copy data from NIC local memory. */ static void ti_mem_read(struct ti_softc *sc, uint32_t addr, uint32_t len, void *buf) { int segptr, segsize, cnt; char *ptr; segptr = addr; cnt = len; ptr = buf; while (cnt) { if (cnt < TI_WINLEN) segsize = cnt; else segsize = TI_WINLEN - (segptr % TI_WINLEN); CSR_WRITE_4(sc, TI_WINBASE, rounddown2(segptr, TI_WINLEN)); bus_space_read_region_4(sc->ti_btag, sc->ti_bhandle, TI_WINDOW + (segptr & (TI_WINLEN - 1)), (uint32_t *)ptr, segsize / 4); ptr += segsize; segptr += segsize; cnt -= segsize; } } /* * NIC memory write function. * Can be used to copy data into NIC local memory. */ static void ti_mem_write(struct ti_softc *sc, uint32_t addr, uint32_t len, void *buf) { int segptr, segsize, cnt; char *ptr; segptr = addr; cnt = len; ptr = buf; while (cnt) { if (cnt < TI_WINLEN) segsize = cnt; else segsize = TI_WINLEN - (segptr % TI_WINLEN); CSR_WRITE_4(sc, TI_WINBASE, rounddown2(segptr, TI_WINLEN)); bus_space_write_region_4(sc->ti_btag, sc->ti_bhandle, TI_WINDOW + (segptr & (TI_WINLEN - 1)), (uint32_t *)ptr, segsize / 4); ptr += segsize; segptr += segsize; cnt -= segsize; } } /* * NIC memory read function. * Can be used to clear a section of NIC local memory. */ static void ti_mem_zero(struct ti_softc *sc, uint32_t addr, uint32_t len) { int segptr, segsize, cnt; segptr = addr; cnt = len; while (cnt) { if (cnt < TI_WINLEN) segsize = cnt; else segsize = TI_WINLEN - (segptr % TI_WINLEN); CSR_WRITE_4(sc, TI_WINBASE, rounddown2(segptr, TI_WINLEN)); bus_space_set_region_4(sc->ti_btag, sc->ti_bhandle, TI_WINDOW + (segptr & (TI_WINLEN - 1)), 0, segsize / 4); segptr += segsize; cnt -= segsize; } } static int ti_copy_mem(struct ti_softc *sc, uint32_t tigon_addr, uint32_t len, caddr_t buf, int useraddr, int readdata) { int segptr, segsize, cnt; caddr_t ptr; uint32_t origwin; int resid, segresid; int first_pass; TI_LOCK_ASSERT(sc); /* * At the moment, we don't handle non-aligned cases, we just bail. * If this proves to be a problem, it will be fixed. */ if (readdata == 0 && (tigon_addr & 0x3) != 0) { device_printf(sc->ti_dev, "%s: tigon address %#x isn't " "word-aligned\n", __func__, tigon_addr); device_printf(sc->ti_dev, "%s: unaligned writes aren't " "yet supported\n", __func__); return (EINVAL); } segptr = tigon_addr & ~0x3; segresid = tigon_addr - segptr; /* * This is the non-aligned amount left over that we'll need to * copy. */ resid = len & 0x3; /* Add in the left over amount at the front of the buffer */ resid += segresid; cnt = len & ~0x3; /* * If resid + segresid is >= 4, add multiples of 4 to the count and * decrease the residual by that much. */ cnt += resid & ~0x3; resid -= resid & ~0x3; ptr = buf; first_pass = 1; /* * Save the old window base value. */ origwin = CSR_READ_4(sc, TI_WINBASE); while (cnt) { bus_size_t ti_offset; if (cnt < TI_WINLEN) segsize = cnt; else segsize = TI_WINLEN - (segptr % TI_WINLEN); CSR_WRITE_4(sc, TI_WINBASE, rounddown2(segptr, TI_WINLEN)); ti_offset = TI_WINDOW + (segptr & (TI_WINLEN -1)); if (readdata) { bus_space_read_region_4(sc->ti_btag, sc->ti_bhandle, ti_offset, (uint32_t *)sc->ti_membuf, segsize >> 2); if (useraddr) { /* * Yeah, this is a little on the kludgy * side, but at least this code is only * used for debugging. */ ti_bcopy_swap(sc->ti_membuf, sc->ti_membuf2, segsize, TI_SWAP_NTOH); TI_UNLOCK(sc); if (first_pass) { copyout(&sc->ti_membuf2[segresid], ptr, segsize - segresid); first_pass = 0; } else copyout(sc->ti_membuf2, ptr, segsize); TI_LOCK(sc); } else { if (first_pass) { ti_bcopy_swap(sc->ti_membuf, sc->ti_membuf2, segsize, TI_SWAP_NTOH); TI_UNLOCK(sc); bcopy(&sc->ti_membuf2[segresid], ptr, segsize - segresid); TI_LOCK(sc); first_pass = 0; } else ti_bcopy_swap(sc->ti_membuf, ptr, segsize, TI_SWAP_NTOH); } } else { if (useraddr) { TI_UNLOCK(sc); copyin(ptr, sc->ti_membuf2, segsize); TI_LOCK(sc); ti_bcopy_swap(sc->ti_membuf2, sc->ti_membuf, segsize, TI_SWAP_HTON); } else ti_bcopy_swap(ptr, sc->ti_membuf, segsize, TI_SWAP_HTON); bus_space_write_region_4(sc->ti_btag, sc->ti_bhandle, ti_offset, (uint32_t *)sc->ti_membuf, segsize >> 2); } segptr += segsize; ptr += segsize; cnt -= segsize; } /* * Handle leftover, non-word-aligned bytes. */ if (resid != 0) { uint32_t tmpval, tmpval2; bus_size_t ti_offset; /* * Set the segment pointer. */ CSR_WRITE_4(sc, TI_WINBASE, rounddown2(segptr, TI_WINLEN)); ti_offset = TI_WINDOW + (segptr & (TI_WINLEN - 1)); /* * First, grab whatever is in our source/destination. * We'll obviously need this for reads, but also for * writes, since we'll be doing read/modify/write. */ bus_space_read_region_4(sc->ti_btag, sc->ti_bhandle, ti_offset, &tmpval, 1); /* * Next, translate this from little-endian to big-endian * (at least on i386 boxes). */ tmpval2 = ntohl(tmpval); if (readdata) { /* * If we're reading, just copy the leftover number * of bytes from the host byte order buffer to * the user's buffer. */ if (useraddr) { TI_UNLOCK(sc); copyout(&tmpval2, ptr, resid); TI_LOCK(sc); } else bcopy(&tmpval2, ptr, resid); } else { /* * If we're writing, first copy the bytes to be * written into the network byte order buffer, * leaving the rest of the buffer with whatever was * originally in there. Then, swap the bytes * around into host order and write them out. * * XXX KDM the read side of this has been verified * to work, but the write side of it has not been * verified. So user beware. */ if (useraddr) { TI_UNLOCK(sc); copyin(ptr, &tmpval2, resid); TI_LOCK(sc); } else bcopy(ptr, &tmpval2, resid); tmpval = htonl(tmpval2); bus_space_write_region_4(sc->ti_btag, sc->ti_bhandle, ti_offset, &tmpval, 1); } } CSR_WRITE_4(sc, TI_WINBASE, origwin); return (0); } static int ti_copy_scratch(struct ti_softc *sc, uint32_t tigon_addr, uint32_t len, caddr_t buf, int useraddr, int readdata, int cpu) { uint32_t segptr; int cnt; uint32_t tmpval, tmpval2; caddr_t ptr; TI_LOCK_ASSERT(sc); /* * At the moment, we don't handle non-aligned cases, we just bail. * If this proves to be a problem, it will be fixed. */ if (tigon_addr & 0x3) { device_printf(sc->ti_dev, "%s: tigon address %#x " "isn't word-aligned\n", __func__, tigon_addr); return (EINVAL); } if (len & 0x3) { device_printf(sc->ti_dev, "%s: transfer length %d " "isn't word-aligned\n", __func__, len); return (EINVAL); } segptr = tigon_addr; cnt = len; ptr = buf; while (cnt) { CSR_WRITE_4(sc, CPU_REG(TI_SRAM_ADDR, cpu), segptr); if (readdata) { tmpval2 = CSR_READ_4(sc, CPU_REG(TI_SRAM_DATA, cpu)); tmpval = ntohl(tmpval2); /* * Note: I've used this debugging interface * extensively with Alteon's 12.3.15 firmware, * compiled with GCC 2.7.2.1 and binutils 2.9.1. * * When you compile the firmware without * optimization, which is necessary sometimes in * order to properly step through it, you sometimes * read out a bogus value of 0xc0017c instead of * whatever was supposed to be in that scratchpad * location. That value is on the stack somewhere, * but I've never been able to figure out what was * causing the problem. * * The address seems to pop up in random places, * often not in the same place on two subsequent * reads. * * In any case, the underlying data doesn't seem * to be affected, just the value read out. * * KDM, 3/7/2000 */ if (tmpval2 == 0xc0017c) device_printf(sc->ti_dev, "found 0xc0017c at " "%#x (tmpval2)\n", segptr); if (tmpval == 0xc0017c) device_printf(sc->ti_dev, "found 0xc0017c at " "%#x (tmpval)\n", segptr); if (useraddr) copyout(&tmpval, ptr, 4); else bcopy(&tmpval, ptr, 4); } else { if (useraddr) copyin(ptr, &tmpval2, 4); else bcopy(ptr, &tmpval2, 4); tmpval = htonl(tmpval2); CSR_WRITE_4(sc, CPU_REG(TI_SRAM_DATA, cpu), tmpval); } cnt -= 4; segptr += 4; ptr += 4; } return (0); } static int ti_bcopy_swap(const void *src, void *dst, size_t len, ti_swap_type swap_type) { const uint8_t *tmpsrc; uint8_t *tmpdst; size_t tmplen; if (len & 0x3) { printf("ti_bcopy_swap: length %zd isn't 32-bit aligned\n", len); return (-1); } tmpsrc = src; tmpdst = dst; tmplen = len; while (tmplen) { if (swap_type == TI_SWAP_NTOH) *(uint32_t *)tmpdst = ntohl(*(const uint32_t *)tmpsrc); else *(uint32_t *)tmpdst = htonl(*(const uint32_t *)tmpsrc); tmpsrc += 4; tmpdst += 4; tmplen -= 4; } return (0); } /* * Load firmware image into the NIC. Check that the firmware revision * is acceptable and see if we want the firmware for the Tigon 1 or * Tigon 2. */ static void ti_loadfw(struct ti_softc *sc) { TI_LOCK_ASSERT(sc); switch (sc->ti_hwrev) { case TI_HWREV_TIGON: if (tigonFwReleaseMajor != TI_FIRMWARE_MAJOR || tigonFwReleaseMinor != TI_FIRMWARE_MINOR || tigonFwReleaseFix != TI_FIRMWARE_FIX) { device_printf(sc->ti_dev, "firmware revision mismatch; " "want %d.%d.%d, got %d.%d.%d\n", TI_FIRMWARE_MAJOR, TI_FIRMWARE_MINOR, TI_FIRMWARE_FIX, tigonFwReleaseMajor, tigonFwReleaseMinor, tigonFwReleaseFix); return; } ti_mem_write(sc, tigonFwTextAddr, tigonFwTextLen, tigonFwText); ti_mem_write(sc, tigonFwDataAddr, tigonFwDataLen, tigonFwData); ti_mem_write(sc, tigonFwRodataAddr, tigonFwRodataLen, tigonFwRodata); ti_mem_zero(sc, tigonFwBssAddr, tigonFwBssLen); ti_mem_zero(sc, tigonFwSbssAddr, tigonFwSbssLen); CSR_WRITE_4(sc, TI_CPU_PROGRAM_COUNTER, tigonFwStartAddr); break; case TI_HWREV_TIGON_II: if (tigon2FwReleaseMajor != TI_FIRMWARE_MAJOR || tigon2FwReleaseMinor != TI_FIRMWARE_MINOR || tigon2FwReleaseFix != TI_FIRMWARE_FIX) { device_printf(sc->ti_dev, "firmware revision mismatch; " "want %d.%d.%d, got %d.%d.%d\n", TI_FIRMWARE_MAJOR, TI_FIRMWARE_MINOR, TI_FIRMWARE_FIX, tigon2FwReleaseMajor, tigon2FwReleaseMinor, tigon2FwReleaseFix); return; } ti_mem_write(sc, tigon2FwTextAddr, tigon2FwTextLen, tigon2FwText); ti_mem_write(sc, tigon2FwDataAddr, tigon2FwDataLen, tigon2FwData); ti_mem_write(sc, tigon2FwRodataAddr, tigon2FwRodataLen, tigon2FwRodata); ti_mem_zero(sc, tigon2FwBssAddr, tigon2FwBssLen); ti_mem_zero(sc, tigon2FwSbssAddr, tigon2FwSbssLen); CSR_WRITE_4(sc, TI_CPU_PROGRAM_COUNTER, tigon2FwStartAddr); break; default: device_printf(sc->ti_dev, "can't load firmware: unknown hardware rev\n"); break; } } /* * Send the NIC a command via the command ring. */ static void ti_cmd(struct ti_softc *sc, struct ti_cmd_desc *cmd) { int index; index = sc->ti_cmd_saved_prodidx; CSR_WRITE_4(sc, TI_GCR_CMDRING + (index * 4), *(uint32_t *)(cmd)); TI_INC(index, TI_CMD_RING_CNT); CSR_WRITE_4(sc, TI_MB_CMDPROD_IDX, index); sc->ti_cmd_saved_prodidx = index; } /* * Send the NIC an extended command. The 'len' parameter specifies the * number of command slots to include after the initial command. */ static void ti_cmd_ext(struct ti_softc *sc, struct ti_cmd_desc *cmd, caddr_t arg, int len) { int index; int i; index = sc->ti_cmd_saved_prodidx; CSR_WRITE_4(sc, TI_GCR_CMDRING + (index * 4), *(uint32_t *)(cmd)); TI_INC(index, TI_CMD_RING_CNT); for (i = 0; i < len; i++) { CSR_WRITE_4(sc, TI_GCR_CMDRING + (index * 4), *(uint32_t *)(&arg[i * 4])); TI_INC(index, TI_CMD_RING_CNT); } CSR_WRITE_4(sc, TI_MB_CMDPROD_IDX, index); sc->ti_cmd_saved_prodidx = index; } /* * Handle events that have triggered interrupts. */ static void ti_handle_events(struct ti_softc *sc) { struct ti_event_desc *e; if (sc->ti_rdata.ti_event_ring == NULL) return; bus_dmamap_sync(sc->ti_cdata.ti_event_ring_tag, sc->ti_cdata.ti_event_ring_map, BUS_DMASYNC_POSTREAD); while (sc->ti_ev_saved_considx != sc->ti_ev_prodidx.ti_idx) { e = &sc->ti_rdata.ti_event_ring[sc->ti_ev_saved_considx]; switch (TI_EVENT_EVENT(e)) { case TI_EV_LINKSTAT_CHANGED: sc->ti_linkstat = TI_EVENT_CODE(e); if (sc->ti_linkstat == TI_EV_CODE_LINK_UP) { if_link_state_change(sc->ti_ifp, LINK_STATE_UP); sc->ti_ifp->if_baudrate = IF_Mbps(100); if (bootverbose) device_printf(sc->ti_dev, "10/100 link up\n"); } else if (sc->ti_linkstat == TI_EV_CODE_GIG_LINK_UP) { if_link_state_change(sc->ti_ifp, LINK_STATE_UP); sc->ti_ifp->if_baudrate = IF_Gbps(1UL); if (bootverbose) device_printf(sc->ti_dev, "gigabit link up\n"); } else if (sc->ti_linkstat == TI_EV_CODE_LINK_DOWN) { if_link_state_change(sc->ti_ifp, LINK_STATE_DOWN); sc->ti_ifp->if_baudrate = 0; if (bootverbose) device_printf(sc->ti_dev, "link down\n"); } break; case TI_EV_ERROR: if (TI_EVENT_CODE(e) == TI_EV_CODE_ERR_INVAL_CMD) device_printf(sc->ti_dev, "invalid command\n"); else if (TI_EVENT_CODE(e) == TI_EV_CODE_ERR_UNIMP_CMD) device_printf(sc->ti_dev, "unknown command\n"); else if (TI_EVENT_CODE(e) == TI_EV_CODE_ERR_BADCFG) device_printf(sc->ti_dev, "bad config data\n"); break; case TI_EV_FIRMWARE_UP: ti_init2(sc); break; case TI_EV_STATS_UPDATED: case TI_EV_RESET_JUMBO_RING: case TI_EV_MCAST_UPDATED: /* Who cares. */ break; default: device_printf(sc->ti_dev, "unknown event: %d\n", TI_EVENT_EVENT(e)); break; } /* Advance the consumer index. */ TI_INC(sc->ti_ev_saved_considx, TI_EVENT_RING_CNT); CSR_WRITE_4(sc, TI_GCR_EVENTCONS_IDX, sc->ti_ev_saved_considx); } bus_dmamap_sync(sc->ti_cdata.ti_event_ring_tag, sc->ti_cdata.ti_event_ring_map, BUS_DMASYNC_PREREAD); } struct ti_dmamap_arg { bus_addr_t ti_busaddr; }; static void ti_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error) { struct ti_dmamap_arg *ctx; if (error) return; KASSERT(nseg == 1, ("%s: %d segments returned!", __func__, nseg)); ctx = arg; ctx->ti_busaddr = segs->ds_addr; } static int ti_dma_ring_alloc(struct ti_softc *sc, bus_size_t alignment, bus_size_t maxsize, bus_dma_tag_t *tag, uint8_t **ring, bus_dmamap_t *map, bus_addr_t *paddr, const char *msg) { struct ti_dmamap_arg ctx; int error; error = bus_dma_tag_create(sc->ti_cdata.ti_parent_tag, alignment, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, maxsize, 1, maxsize, 0, NULL, NULL, tag); if (error != 0) { device_printf(sc->ti_dev, "could not create %s dma tag\n", msg); return (error); } /* Allocate DMA'able memory for ring. */ error = bus_dmamem_alloc(*tag, (void **)ring, BUS_DMA_NOWAIT | BUS_DMA_ZERO | BUS_DMA_COHERENT, map); if (error != 0) { device_printf(sc->ti_dev, "could not allocate DMA'able memory for %s\n", msg); return (error); } /* Load the address of the ring. */ ctx.ti_busaddr = 0; error = bus_dmamap_load(*tag, *map, *ring, maxsize, ti_dma_map_addr, &ctx, BUS_DMA_NOWAIT); if (error != 0) { device_printf(sc->ti_dev, "could not load DMA'able memory for %s\n", msg); return (error); } *paddr = ctx.ti_busaddr; return (0); } static void ti_dma_ring_free(struct ti_softc *sc, bus_dma_tag_t *tag, uint8_t **ring, bus_dmamap_t map, bus_addr_t *paddr) { if (*paddr != 0) { bus_dmamap_unload(*tag, map); *paddr = 0; } if (*ring != NULL) { bus_dmamem_free(*tag, *ring, map); *ring = NULL; } if (*tag) { bus_dma_tag_destroy(*tag); *tag = NULL; } } static int ti_dma_alloc(struct ti_softc *sc) { bus_addr_t lowaddr; int i, error; lowaddr = BUS_SPACE_MAXADDR; if (sc->ti_dac == 0) lowaddr = BUS_SPACE_MAXADDR_32BIT; error = bus_dma_tag_create(bus_get_dma_tag(sc->ti_dev), 1, 0, lowaddr, BUS_SPACE_MAXADDR, NULL, NULL, BUS_SPACE_MAXSIZE_32BIT, 0, BUS_SPACE_MAXSIZE_32BIT, 0, NULL, NULL, &sc->ti_cdata.ti_parent_tag); if (error != 0) { device_printf(sc->ti_dev, "could not allocate parent dma tag\n"); return (ENOMEM); } error = ti_dma_ring_alloc(sc, TI_RING_ALIGN, sizeof(struct ti_gib), &sc->ti_cdata.ti_gib_tag, (uint8_t **)&sc->ti_rdata.ti_info, &sc->ti_cdata.ti_gib_map, &sc->ti_rdata.ti_info_paddr, "GIB"); if (error) return (error); /* Producer/consumer status */ error = ti_dma_ring_alloc(sc, TI_RING_ALIGN, sizeof(struct ti_status), &sc->ti_cdata.ti_status_tag, (uint8_t **)&sc->ti_rdata.ti_status, &sc->ti_cdata.ti_status_map, &sc->ti_rdata.ti_status_paddr, "event ring"); if (error) return (error); /* Event ring */ error = ti_dma_ring_alloc(sc, TI_RING_ALIGN, TI_EVENT_RING_SZ, &sc->ti_cdata.ti_event_ring_tag, (uint8_t **)&sc->ti_rdata.ti_event_ring, &sc->ti_cdata.ti_event_ring_map, &sc->ti_rdata.ti_event_ring_paddr, "event ring"); if (error) return (error); /* Command ring lives in shared memory so no need to create DMA area. */ /* Standard RX ring */ error = ti_dma_ring_alloc(sc, TI_RING_ALIGN, TI_STD_RX_RING_SZ, &sc->ti_cdata.ti_rx_std_ring_tag, (uint8_t **)&sc->ti_rdata.ti_rx_std_ring, &sc->ti_cdata.ti_rx_std_ring_map, &sc->ti_rdata.ti_rx_std_ring_paddr, "RX ring"); if (error) return (error); /* Jumbo RX ring */ error = ti_dma_ring_alloc(sc, TI_JUMBO_RING_ALIGN, TI_JUMBO_RX_RING_SZ, &sc->ti_cdata.ti_rx_jumbo_ring_tag, (uint8_t **)&sc->ti_rdata.ti_rx_jumbo_ring, &sc->ti_cdata.ti_rx_jumbo_ring_map, &sc->ti_rdata.ti_rx_jumbo_ring_paddr, "jumbo RX ring"); if (error) return (error); /* RX return ring */ error = ti_dma_ring_alloc(sc, TI_RING_ALIGN, TI_RX_RETURN_RING_SZ, &sc->ti_cdata.ti_rx_return_ring_tag, (uint8_t **)&sc->ti_rdata.ti_rx_return_ring, &sc->ti_cdata.ti_rx_return_ring_map, &sc->ti_rdata.ti_rx_return_ring_paddr, "RX return ring"); if (error) return (error); /* Create DMA tag for standard RX mbufs. */ error = bus_dma_tag_create(sc->ti_cdata.ti_parent_tag, 1, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1, MCLBYTES, 0, NULL, NULL, &sc->ti_cdata.ti_rx_std_tag); if (error) { device_printf(sc->ti_dev, "could not allocate RX dma tag\n"); return (error); } /* Create DMA tag for jumbo RX mbufs. */ #ifdef TI_SF_BUF_JUMBO /* * The VM system will take care of providing aligned pages. Alignment * is set to 1 here so that busdma resources won't be wasted. */ error = bus_dma_tag_create(sc->ti_cdata.ti_parent_tag, 1, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, PAGE_SIZE * 4, 4, PAGE_SIZE, 0, NULL, NULL, &sc->ti_cdata.ti_rx_jumbo_tag); #else error = bus_dma_tag_create(sc->ti_cdata.ti_parent_tag, 1, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, MJUM9BYTES, 1, MJUM9BYTES, 0, NULL, NULL, &sc->ti_cdata.ti_rx_jumbo_tag); #endif if (error) { device_printf(sc->ti_dev, "could not allocate jumbo RX dma tag\n"); return (error); } /* Create DMA tag for TX mbufs. */ error = bus_dma_tag_create(sc->ti_cdata.ti_parent_tag, 1, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES * TI_MAXTXSEGS, TI_MAXTXSEGS, MCLBYTES, 0, NULL, NULL, &sc->ti_cdata.ti_tx_tag); if (error) { device_printf(sc->ti_dev, "could not allocate TX dma tag\n"); return (ENOMEM); } /* Create DMA maps for RX buffers. */ for (i = 0; i < TI_STD_RX_RING_CNT; i++) { error = bus_dmamap_create(sc->ti_cdata.ti_rx_std_tag, 0, &sc->ti_cdata.ti_rx_std_maps[i]); if (error) { device_printf(sc->ti_dev, "could not create DMA map for RX\n"); return (error); } } error = bus_dmamap_create(sc->ti_cdata.ti_rx_std_tag, 0, &sc->ti_cdata.ti_rx_std_sparemap); if (error) { device_printf(sc->ti_dev, "could not create spare DMA map for RX\n"); return (error); } /* Create DMA maps for jumbo RX buffers. */ for (i = 0; i < TI_JUMBO_RX_RING_CNT; i++) { error = bus_dmamap_create(sc->ti_cdata.ti_rx_jumbo_tag, 0, &sc->ti_cdata.ti_rx_jumbo_maps[i]); if (error) { device_printf(sc->ti_dev, "could not create DMA map for jumbo RX\n"); return (error); } } error = bus_dmamap_create(sc->ti_cdata.ti_rx_jumbo_tag, 0, &sc->ti_cdata.ti_rx_jumbo_sparemap); if (error) { device_printf(sc->ti_dev, "could not create spare DMA map for jumbo RX\n"); return (error); } /* Create DMA maps for TX buffers. */ for (i = 0; i < TI_TX_RING_CNT; i++) { error = bus_dmamap_create(sc->ti_cdata.ti_tx_tag, 0, &sc->ti_cdata.ti_txdesc[i].tx_dmamap); if (error) { device_printf(sc->ti_dev, "could not create DMA map for TX\n"); return (ENOMEM); } } /* Mini ring and TX ring is not available on Tigon 1. */ if (sc->ti_hwrev == TI_HWREV_TIGON) return (0); /* TX ring */ error = ti_dma_ring_alloc(sc, TI_RING_ALIGN, TI_TX_RING_SZ, &sc->ti_cdata.ti_tx_ring_tag, (uint8_t **)&sc->ti_rdata.ti_tx_ring, &sc->ti_cdata.ti_tx_ring_map, &sc->ti_rdata.ti_tx_ring_paddr, "TX ring"); if (error) return (error); /* Mini RX ring */ error = ti_dma_ring_alloc(sc, TI_RING_ALIGN, TI_MINI_RX_RING_SZ, &sc->ti_cdata.ti_rx_mini_ring_tag, (uint8_t **)&sc->ti_rdata.ti_rx_mini_ring, &sc->ti_cdata.ti_rx_mini_ring_map, &sc->ti_rdata.ti_rx_mini_ring_paddr, "mini RX ring"); if (error) return (error); /* Create DMA tag for mini RX mbufs. */ error = bus_dma_tag_create(sc->ti_cdata.ti_parent_tag, 1, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, MHLEN, 1, MHLEN, 0, NULL, NULL, &sc->ti_cdata.ti_rx_mini_tag); if (error) { device_printf(sc->ti_dev, "could not allocate mini RX dma tag\n"); return (error); } /* Create DMA maps for mini RX buffers. */ for (i = 0; i < TI_MINI_RX_RING_CNT; i++) { error = bus_dmamap_create(sc->ti_cdata.ti_rx_mini_tag, 0, &sc->ti_cdata.ti_rx_mini_maps[i]); if (error) { device_printf(sc->ti_dev, "could not create DMA map for mini RX\n"); return (error); } } error = bus_dmamap_create(sc->ti_cdata.ti_rx_mini_tag, 0, &sc->ti_cdata.ti_rx_mini_sparemap); if (error) { device_printf(sc->ti_dev, "could not create spare DMA map for mini RX\n"); return (error); } return (0); } static void ti_dma_free(struct ti_softc *sc) { int i; /* Destroy DMA maps for RX buffers. */ for (i = 0; i < TI_STD_RX_RING_CNT; i++) { if (sc->ti_cdata.ti_rx_std_maps[i]) { bus_dmamap_destroy(sc->ti_cdata.ti_rx_std_tag, sc->ti_cdata.ti_rx_std_maps[i]); sc->ti_cdata.ti_rx_std_maps[i] = NULL; } } if (sc->ti_cdata.ti_rx_std_sparemap) { bus_dmamap_destroy(sc->ti_cdata.ti_rx_std_tag, sc->ti_cdata.ti_rx_std_sparemap); sc->ti_cdata.ti_rx_std_sparemap = NULL; } if (sc->ti_cdata.ti_rx_std_tag) { bus_dma_tag_destroy(sc->ti_cdata.ti_rx_std_tag); sc->ti_cdata.ti_rx_std_tag = NULL; } /* Destroy DMA maps for jumbo RX buffers. */ for (i = 0; i < TI_JUMBO_RX_RING_CNT; i++) { if (sc->ti_cdata.ti_rx_jumbo_maps[i]) { bus_dmamap_destroy(sc->ti_cdata.ti_rx_jumbo_tag, sc->ti_cdata.ti_rx_jumbo_maps[i]); sc->ti_cdata.ti_rx_jumbo_maps[i] = NULL; } } if (sc->ti_cdata.ti_rx_jumbo_sparemap) { bus_dmamap_destroy(sc->ti_cdata.ti_rx_jumbo_tag, sc->ti_cdata.ti_rx_jumbo_sparemap); sc->ti_cdata.ti_rx_jumbo_sparemap = NULL; } if (sc->ti_cdata.ti_rx_jumbo_tag) { bus_dma_tag_destroy(sc->ti_cdata.ti_rx_jumbo_tag); sc->ti_cdata.ti_rx_jumbo_tag = NULL; } /* Destroy DMA maps for mini RX buffers. */ for (i = 0; i < TI_MINI_RX_RING_CNT; i++) { if (sc->ti_cdata.ti_rx_mini_maps[i]) { bus_dmamap_destroy(sc->ti_cdata.ti_rx_mini_tag, sc->ti_cdata.ti_rx_mini_maps[i]); sc->ti_cdata.ti_rx_mini_maps[i] = NULL; } } if (sc->ti_cdata.ti_rx_mini_sparemap) { bus_dmamap_destroy(sc->ti_cdata.ti_rx_mini_tag, sc->ti_cdata.ti_rx_mini_sparemap); sc->ti_cdata.ti_rx_mini_sparemap = NULL; } if (sc->ti_cdata.ti_rx_mini_tag) { bus_dma_tag_destroy(sc->ti_cdata.ti_rx_mini_tag); sc->ti_cdata.ti_rx_mini_tag = NULL; } /* Destroy DMA maps for TX buffers. */ for (i = 0; i < TI_TX_RING_CNT; i++) { if (sc->ti_cdata.ti_txdesc[i].tx_dmamap) { bus_dmamap_destroy(sc->ti_cdata.ti_tx_tag, sc->ti_cdata.ti_txdesc[i].tx_dmamap); sc->ti_cdata.ti_txdesc[i].tx_dmamap = NULL; } } if (sc->ti_cdata.ti_tx_tag) { bus_dma_tag_destroy(sc->ti_cdata.ti_tx_tag); sc->ti_cdata.ti_tx_tag = NULL; } /* Destroy standard RX ring. */ ti_dma_ring_free(sc, &sc->ti_cdata.ti_rx_std_ring_tag, (void *)&sc->ti_rdata.ti_rx_std_ring, sc->ti_cdata.ti_rx_std_ring_map, &sc->ti_rdata.ti_rx_std_ring_paddr); /* Destroy jumbo RX ring. */ ti_dma_ring_free(sc, &sc->ti_cdata.ti_rx_jumbo_ring_tag, (void *)&sc->ti_rdata.ti_rx_jumbo_ring, sc->ti_cdata.ti_rx_jumbo_ring_map, &sc->ti_rdata.ti_rx_jumbo_ring_paddr); /* Destroy mini RX ring. */ ti_dma_ring_free(sc, &sc->ti_cdata.ti_rx_mini_ring_tag, (void *)&sc->ti_rdata.ti_rx_mini_ring, sc->ti_cdata.ti_rx_mini_ring_map, &sc->ti_rdata.ti_rx_mini_ring_paddr); /* Destroy RX return ring. */ ti_dma_ring_free(sc, &sc->ti_cdata.ti_rx_return_ring_tag, (void *)&sc->ti_rdata.ti_rx_return_ring, sc->ti_cdata.ti_rx_return_ring_map, &sc->ti_rdata.ti_rx_return_ring_paddr); /* Destroy TX ring. */ ti_dma_ring_free(sc, &sc->ti_cdata.ti_tx_ring_tag, (void *)&sc->ti_rdata.ti_tx_ring, sc->ti_cdata.ti_tx_ring_map, &sc->ti_rdata.ti_tx_ring_paddr); /* Destroy status block. */ ti_dma_ring_free(sc, &sc->ti_cdata.ti_status_tag, (void *)&sc->ti_rdata.ti_status, sc->ti_cdata.ti_status_map, &sc->ti_rdata.ti_status_paddr); /* Destroy event ring. */ ti_dma_ring_free(sc, &sc->ti_cdata.ti_event_ring_tag, (void *)&sc->ti_rdata.ti_event_ring, sc->ti_cdata.ti_event_ring_map, &sc->ti_rdata.ti_event_ring_paddr); /* Destroy GIB */ ti_dma_ring_free(sc, &sc->ti_cdata.ti_gib_tag, (void *)&sc->ti_rdata.ti_info, sc->ti_cdata.ti_gib_map, &sc->ti_rdata.ti_info_paddr); /* Destroy the parent tag. */ if (sc->ti_cdata.ti_parent_tag) { bus_dma_tag_destroy(sc->ti_cdata.ti_parent_tag); sc->ti_cdata.ti_parent_tag = NULL; } } /* * Intialize a standard receive ring descriptor. */ static int ti_newbuf_std(struct ti_softc *sc, int i) { bus_dmamap_t map; bus_dma_segment_t segs[1]; struct mbuf *m; struct ti_rx_desc *r; int error, nsegs; m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR); if (m == NULL) return (ENOBUFS); m->m_len = m->m_pkthdr.len = MCLBYTES; m_adj(m, ETHER_ALIGN); error = bus_dmamap_load_mbuf_sg(sc->ti_cdata.ti_rx_std_tag, sc->ti_cdata.ti_rx_std_sparemap, m, segs, &nsegs, 0); if (error != 0) { m_freem(m); return (error); } KASSERT(nsegs == 1, ("%s: %d segments returned!", __func__, nsegs)); if (sc->ti_cdata.ti_rx_std_chain[i] != NULL) { bus_dmamap_sync(sc->ti_cdata.ti_rx_std_tag, sc->ti_cdata.ti_rx_std_maps[i], BUS_DMASYNC_POSTREAD); bus_dmamap_unload(sc->ti_cdata.ti_rx_std_tag, sc->ti_cdata.ti_rx_std_maps[i]); } map = sc->ti_cdata.ti_rx_std_maps[i]; sc->ti_cdata.ti_rx_std_maps[i] = sc->ti_cdata.ti_rx_std_sparemap; sc->ti_cdata.ti_rx_std_sparemap = map; sc->ti_cdata.ti_rx_std_chain[i] = m; r = &sc->ti_rdata.ti_rx_std_ring[i]; ti_hostaddr64(&r->ti_addr, segs[0].ds_addr); r->ti_len = segs[0].ds_len; r->ti_type = TI_BDTYPE_RECV_BD; r->ti_flags = 0; r->ti_vlan_tag = 0; r->ti_tcp_udp_cksum = 0; if (sc->ti_ifp->if_capenable & IFCAP_RXCSUM) r->ti_flags |= TI_BDFLAG_TCP_UDP_CKSUM | TI_BDFLAG_IP_CKSUM; r->ti_idx = i; bus_dmamap_sync(sc->ti_cdata.ti_rx_std_tag, sc->ti_cdata.ti_rx_std_maps[i], BUS_DMASYNC_PREREAD); return (0); } /* * Intialize a mini receive ring descriptor. This only applies to * the Tigon 2. */ static int ti_newbuf_mini(struct ti_softc *sc, int i) { bus_dmamap_t map; bus_dma_segment_t segs[1]; struct mbuf *m; struct ti_rx_desc *r; int error, nsegs; MGETHDR(m, M_NOWAIT, MT_DATA); if (m == NULL) return (ENOBUFS); m->m_len = m->m_pkthdr.len = MHLEN; m_adj(m, ETHER_ALIGN); error = bus_dmamap_load_mbuf_sg(sc->ti_cdata.ti_rx_mini_tag, sc->ti_cdata.ti_rx_mini_sparemap, m, segs, &nsegs, 0); if (error != 0) { m_freem(m); return (error); } KASSERT(nsegs == 1, ("%s: %d segments returned!", __func__, nsegs)); if (sc->ti_cdata.ti_rx_mini_chain[i] != NULL) { bus_dmamap_sync(sc->ti_cdata.ti_rx_mini_tag, sc->ti_cdata.ti_rx_mini_maps[i], BUS_DMASYNC_POSTREAD); bus_dmamap_unload(sc->ti_cdata.ti_rx_mini_tag, sc->ti_cdata.ti_rx_mini_maps[i]); } map = sc->ti_cdata.ti_rx_mini_maps[i]; sc->ti_cdata.ti_rx_mini_maps[i] = sc->ti_cdata.ti_rx_mini_sparemap; sc->ti_cdata.ti_rx_mini_sparemap = map; sc->ti_cdata.ti_rx_mini_chain[i] = m; r = &sc->ti_rdata.ti_rx_mini_ring[i]; ti_hostaddr64(&r->ti_addr, segs[0].ds_addr); r->ti_len = segs[0].ds_len; r->ti_type = TI_BDTYPE_RECV_BD; r->ti_flags = TI_BDFLAG_MINI_RING; r->ti_vlan_tag = 0; r->ti_tcp_udp_cksum = 0; if (sc->ti_ifp->if_capenable & IFCAP_RXCSUM) r->ti_flags |= TI_BDFLAG_TCP_UDP_CKSUM | TI_BDFLAG_IP_CKSUM; r->ti_idx = i; bus_dmamap_sync(sc->ti_cdata.ti_rx_mini_tag, sc->ti_cdata.ti_rx_mini_maps[i], BUS_DMASYNC_PREREAD); return (0); } #ifndef TI_SF_BUF_JUMBO /* * Initialize a jumbo receive ring descriptor. This allocates * a jumbo buffer from the pool managed internally by the driver. */ static int ti_newbuf_jumbo(struct ti_softc *sc, int i, struct mbuf *dummy) { bus_dmamap_t map; bus_dma_segment_t segs[1]; struct mbuf *m; struct ti_rx_desc *r; int error, nsegs; (void)dummy; m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUM9BYTES); if (m == NULL) return (ENOBUFS); m->m_len = m->m_pkthdr.len = MJUM9BYTES; m_adj(m, ETHER_ALIGN); error = bus_dmamap_load_mbuf_sg(sc->ti_cdata.ti_rx_jumbo_tag, sc->ti_cdata.ti_rx_jumbo_sparemap, m, segs, &nsegs, 0); if (error != 0) { m_freem(m); return (error); } KASSERT(nsegs == 1, ("%s: %d segments returned!", __func__, nsegs)); if (sc->ti_cdata.ti_rx_jumbo_chain[i] != NULL) { bus_dmamap_sync(sc->ti_cdata.ti_rx_jumbo_tag, sc->ti_cdata.ti_rx_jumbo_maps[i], BUS_DMASYNC_POSTREAD); bus_dmamap_unload(sc->ti_cdata.ti_rx_jumbo_tag, sc->ti_cdata.ti_rx_jumbo_maps[i]); } map = sc->ti_cdata.ti_rx_jumbo_maps[i]; sc->ti_cdata.ti_rx_jumbo_maps[i] = sc->ti_cdata.ti_rx_jumbo_sparemap; sc->ti_cdata.ti_rx_jumbo_sparemap = map; sc->ti_cdata.ti_rx_jumbo_chain[i] = m; r = &sc->ti_rdata.ti_rx_jumbo_ring[i]; ti_hostaddr64(&r->ti_addr, segs[0].ds_addr); r->ti_len = segs[0].ds_len; r->ti_type = TI_BDTYPE_RECV_JUMBO_BD; r->ti_flags = TI_BDFLAG_JUMBO_RING; r->ti_vlan_tag = 0; r->ti_tcp_udp_cksum = 0; if (sc->ti_ifp->if_capenable & IFCAP_RXCSUM) r->ti_flags |= TI_BDFLAG_TCP_UDP_CKSUM | TI_BDFLAG_IP_CKSUM; r->ti_idx = i; bus_dmamap_sync(sc->ti_cdata.ti_rx_jumbo_tag, sc->ti_cdata.ti_rx_jumbo_maps[i], BUS_DMASYNC_PREREAD); return (0); } #else #if (PAGE_SIZE == 4096) #define NPAYLOAD 2 #else #define NPAYLOAD 1 #endif #define TCP_HDR_LEN (52 + sizeof(struct ether_header)) #define UDP_HDR_LEN (28 + sizeof(struct ether_header)) #define NFS_HDR_LEN (UDP_HDR_LEN) static int HDR_LEN = TCP_HDR_LEN; /* * Initialize a jumbo receive ring descriptor. This allocates * a jumbo buffer from the pool managed internally by the driver. */ static int ti_newbuf_jumbo(struct ti_softc *sc, int idx, struct mbuf *m_old) { bus_dmamap_t map; struct mbuf *cur, *m_new = NULL; struct mbuf *m[3] = {NULL, NULL, NULL}; struct ti_rx_desc_ext *r; vm_page_t frame; /* 1 extra buf to make nobufs easy*/ struct sf_buf *sf[3] = {NULL, NULL, NULL}; int i; bus_dma_segment_t segs[4]; int nsegs; if (m_old != NULL) { m_new = m_old; cur = m_old->m_next; for (i = 0; i <= NPAYLOAD; i++){ m[i] = cur; cur = cur->m_next; } } else { /* Allocate the mbufs. */ MGETHDR(m_new, M_NOWAIT, MT_DATA); if (m_new == NULL) { device_printf(sc->ti_dev, "mbuf allocation failed " "-- packet dropped!\n"); goto nobufs; } MGET(m[NPAYLOAD], M_NOWAIT, MT_DATA); if (m[NPAYLOAD] == NULL) { device_printf(sc->ti_dev, "cluster mbuf allocation " "failed -- packet dropped!\n"); goto nobufs; } if (!(MCLGET(m[NPAYLOAD], M_NOWAIT))) { device_printf(sc->ti_dev, "mbuf allocation failed " "-- packet dropped!\n"); goto nobufs; } m[NPAYLOAD]->m_len = MCLBYTES; for (i = 0; i < NPAYLOAD; i++){ MGET(m[i], M_NOWAIT, MT_DATA); if (m[i] == NULL) { device_printf(sc->ti_dev, "mbuf allocation " "failed -- packet dropped!\n"); goto nobufs; } frame = vm_page_alloc(NULL, 0, VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED); if (frame == NULL) { device_printf(sc->ti_dev, "buffer allocation " "failed -- packet dropped!\n"); printf(" index %d page %d\n", idx, i); goto nobufs; } sf[i] = sf_buf_alloc(frame, SFB_NOWAIT); if (sf[i] == NULL) { vm_page_unwire(frame, PQ_INACTIVE); vm_page_free(frame); device_printf(sc->ti_dev, "buffer allocation " "failed -- packet dropped!\n"); printf(" index %d page %d\n", idx, i); goto nobufs; } } for (i = 0; i < NPAYLOAD; i++){ /* Attach the buffer to the mbuf. */ m[i]->m_data = (void *)sf_buf_kva(sf[i]); m[i]->m_len = PAGE_SIZE; MEXTADD(m[i], sf_buf_kva(sf[i]), PAGE_SIZE, sf_mext_free, (void*)sf_buf_kva(sf[i]), sf[i], 0, EXT_DISPOSABLE); m[i]->m_next = m[i+1]; } /* link the buffers to the header */ m_new->m_next = m[0]; m_new->m_data += ETHER_ALIGN; if (sc->ti_hdrsplit) m_new->m_len = MHLEN - ETHER_ALIGN; else m_new->m_len = HDR_LEN; m_new->m_pkthdr.len = NPAYLOAD * PAGE_SIZE + m_new->m_len; } /* Set up the descriptor. */ r = &sc->ti_rdata.ti_rx_jumbo_ring[idx]; sc->ti_cdata.ti_rx_jumbo_chain[idx] = m_new; map = sc->ti_cdata.ti_rx_jumbo_maps[i]; if (bus_dmamap_load_mbuf_sg(sc->ti_cdata.ti_rx_jumbo_tag, map, m_new, segs, &nsegs, 0)) return (ENOBUFS); if ((nsegs < 1) || (nsegs > 4)) return (ENOBUFS); ti_hostaddr64(&r->ti_addr0, segs[0].ds_addr); r->ti_len0 = m_new->m_len; ti_hostaddr64(&r->ti_addr1, segs[1].ds_addr); r->ti_len1 = PAGE_SIZE; ti_hostaddr64(&r->ti_addr2, segs[2].ds_addr); r->ti_len2 = m[1]->m_ext.ext_size; /* could be PAGE_SIZE or MCLBYTES */ if (PAGE_SIZE == 4096) { ti_hostaddr64(&r->ti_addr3, segs[3].ds_addr); r->ti_len3 = MCLBYTES; } else { r->ti_len3 = 0; } r->ti_type = TI_BDTYPE_RECV_JUMBO_BD; r->ti_flags = TI_BDFLAG_JUMBO_RING|TI_RCB_FLAG_USE_EXT_RX_BD; if (sc->ti_ifp->if_capenable & IFCAP_RXCSUM) r->ti_flags |= TI_BDFLAG_TCP_UDP_CKSUM|TI_BDFLAG_IP_CKSUM; r->ti_idx = idx; bus_dmamap_sync(sc->ti_cdata.ti_rx_jumbo_tag, map, BUS_DMASYNC_PREREAD); return (0); nobufs: /* * Warning! : * This can only be called before the mbufs are strung together. * If the mbufs are strung together, m_freem() will free the chain, * so that the later mbufs will be freed multiple times. */ if (m_new) m_freem(m_new); for (i = 0; i < 3; i++) { if (m[i]) m_freem(m[i]); if (sf[i]) sf_mext_free((void *)sf_buf_kva(sf[i]), sf[i]); } return (ENOBUFS); } #endif /* * The standard receive ring has 512 entries in it. At 2K per mbuf cluster, * that's 1MB or memory, which is a lot. For now, we fill only the first * 256 ring entries and hope that our CPU is fast enough to keep up with * the NIC. */ static int ti_init_rx_ring_std(struct ti_softc *sc) { int i; struct ti_cmd_desc cmd; for (i = 0; i < TI_STD_RX_RING_CNT; i++) { if (ti_newbuf_std(sc, i) != 0) return (ENOBUFS); } sc->ti_std = TI_STD_RX_RING_CNT - 1; TI_UPDATE_STDPROD(sc, TI_STD_RX_RING_CNT - 1); return (0); } static void ti_free_rx_ring_std(struct ti_softc *sc) { bus_dmamap_t map; int i; for (i = 0; i < TI_STD_RX_RING_CNT; i++) { if (sc->ti_cdata.ti_rx_std_chain[i] != NULL) { map = sc->ti_cdata.ti_rx_std_maps[i]; bus_dmamap_sync(sc->ti_cdata.ti_rx_std_tag, map, BUS_DMASYNC_POSTREAD); bus_dmamap_unload(sc->ti_cdata.ti_rx_std_tag, map); m_freem(sc->ti_cdata.ti_rx_std_chain[i]); sc->ti_cdata.ti_rx_std_chain[i] = NULL; } } bzero(sc->ti_rdata.ti_rx_std_ring, TI_STD_RX_RING_SZ); bus_dmamap_sync(sc->ti_cdata.ti_rx_std_ring_tag, sc->ti_cdata.ti_rx_std_ring_map, BUS_DMASYNC_PREWRITE); } static int ti_init_rx_ring_jumbo(struct ti_softc *sc) { struct ti_cmd_desc cmd; int i; for (i = 0; i < TI_JUMBO_RX_RING_CNT; i++) { if (ti_newbuf_jumbo(sc, i, NULL) != 0) return (ENOBUFS); } sc->ti_jumbo = TI_JUMBO_RX_RING_CNT - 1; TI_UPDATE_JUMBOPROD(sc, TI_JUMBO_RX_RING_CNT - 1); return (0); } static void ti_free_rx_ring_jumbo(struct ti_softc *sc) { bus_dmamap_t map; int i; for (i = 0; i < TI_JUMBO_RX_RING_CNT; i++) { if (sc->ti_cdata.ti_rx_jumbo_chain[i] != NULL) { map = sc->ti_cdata.ti_rx_jumbo_maps[i]; bus_dmamap_sync(sc->ti_cdata.ti_rx_jumbo_tag, map, BUS_DMASYNC_POSTREAD); bus_dmamap_unload(sc->ti_cdata.ti_rx_jumbo_tag, map); m_freem(sc->ti_cdata.ti_rx_jumbo_chain[i]); sc->ti_cdata.ti_rx_jumbo_chain[i] = NULL; } } bzero(sc->ti_rdata.ti_rx_jumbo_ring, TI_JUMBO_RX_RING_SZ); bus_dmamap_sync(sc->ti_cdata.ti_rx_jumbo_ring_tag, sc->ti_cdata.ti_rx_jumbo_ring_map, BUS_DMASYNC_PREWRITE); } static int ti_init_rx_ring_mini(struct ti_softc *sc) { int i; for (i = 0; i < TI_MINI_RX_RING_CNT; i++) { if (ti_newbuf_mini(sc, i) != 0) return (ENOBUFS); } sc->ti_mini = TI_MINI_RX_RING_CNT - 1; TI_UPDATE_MINIPROD(sc, TI_MINI_RX_RING_CNT - 1); return (0); } static void ti_free_rx_ring_mini(struct ti_softc *sc) { bus_dmamap_t map; int i; if (sc->ti_rdata.ti_rx_mini_ring == NULL) return; for (i = 0; i < TI_MINI_RX_RING_CNT; i++) { if (sc->ti_cdata.ti_rx_mini_chain[i] != NULL) { map = sc->ti_cdata.ti_rx_mini_maps[i]; bus_dmamap_sync(sc->ti_cdata.ti_rx_mini_tag, map, BUS_DMASYNC_POSTREAD); bus_dmamap_unload(sc->ti_cdata.ti_rx_mini_tag, map); m_freem(sc->ti_cdata.ti_rx_mini_chain[i]); sc->ti_cdata.ti_rx_mini_chain[i] = NULL; } } bzero(sc->ti_rdata.ti_rx_mini_ring, TI_MINI_RX_RING_SZ); bus_dmamap_sync(sc->ti_cdata.ti_rx_mini_ring_tag, sc->ti_cdata.ti_rx_mini_ring_map, BUS_DMASYNC_PREWRITE); } static void ti_free_tx_ring(struct ti_softc *sc) { struct ti_txdesc *txd; int i; if (sc->ti_rdata.ti_tx_ring == NULL) return; for (i = 0; i < TI_TX_RING_CNT; i++) { txd = &sc->ti_cdata.ti_txdesc[i]; if (txd->tx_m != NULL) { bus_dmamap_sync(sc->ti_cdata.ti_tx_tag, txd->tx_dmamap, BUS_DMASYNC_POSTWRITE); bus_dmamap_unload(sc->ti_cdata.ti_tx_tag, txd->tx_dmamap); m_freem(txd->tx_m); txd->tx_m = NULL; } } bzero(sc->ti_rdata.ti_tx_ring, TI_TX_RING_SZ); bus_dmamap_sync(sc->ti_cdata.ti_tx_ring_tag, sc->ti_cdata.ti_tx_ring_map, BUS_DMASYNC_PREWRITE); } static int ti_init_tx_ring(struct ti_softc *sc) { struct ti_txdesc *txd; int i; STAILQ_INIT(&sc->ti_cdata.ti_txfreeq); STAILQ_INIT(&sc->ti_cdata.ti_txbusyq); for (i = 0; i < TI_TX_RING_CNT; i++) { txd = &sc->ti_cdata.ti_txdesc[i]; STAILQ_INSERT_TAIL(&sc->ti_cdata.ti_txfreeq, txd, tx_q); } sc->ti_txcnt = 0; sc->ti_tx_saved_considx = 0; sc->ti_tx_saved_prodidx = 0; CSR_WRITE_4(sc, TI_MB_SENDPROD_IDX, 0); return (0); } /* * The Tigon 2 firmware has a new way to add/delete multicast addresses, * but we have to support the old way too so that Tigon 1 cards will * work. */ static void ti_add_mcast(struct ti_softc *sc, struct ether_addr *addr) { struct ti_cmd_desc cmd; uint16_t *m; uint32_t ext[2] = {0, 0}; m = (uint16_t *)&addr->octet[0]; switch (sc->ti_hwrev) { case TI_HWREV_TIGON: CSR_WRITE_4(sc, TI_GCR_MAR0, htons(m[0])); CSR_WRITE_4(sc, TI_GCR_MAR1, (htons(m[1]) << 16) | htons(m[2])); TI_DO_CMD(TI_CMD_ADD_MCAST_ADDR, 0, 0); break; case TI_HWREV_TIGON_II: ext[0] = htons(m[0]); ext[1] = (htons(m[1]) << 16) | htons(m[2]); TI_DO_CMD_EXT(TI_CMD_EXT_ADD_MCAST, 0, 0, (caddr_t)&ext, 2); break; default: device_printf(sc->ti_dev, "unknown hwrev\n"); break; } } static void ti_del_mcast(struct ti_softc *sc, struct ether_addr *addr) { struct ti_cmd_desc cmd; uint16_t *m; uint32_t ext[2] = {0, 0}; m = (uint16_t *)&addr->octet[0]; switch (sc->ti_hwrev) { case TI_HWREV_TIGON: CSR_WRITE_4(sc, TI_GCR_MAR0, htons(m[0])); CSR_WRITE_4(sc, TI_GCR_MAR1, (htons(m[1]) << 16) | htons(m[2])); TI_DO_CMD(TI_CMD_DEL_MCAST_ADDR, 0, 0); break; case TI_HWREV_TIGON_II: ext[0] = htons(m[0]); ext[1] = (htons(m[1]) << 16) | htons(m[2]); TI_DO_CMD_EXT(TI_CMD_EXT_DEL_MCAST, 0, 0, (caddr_t)&ext, 2); break; default: device_printf(sc->ti_dev, "unknown hwrev\n"); break; } } /* * Configure the Tigon's multicast address filter. * * The actual multicast table management is a bit of a pain, thanks to * slight brain damage on the part of both Alteon and us. With our * multicast code, we are only alerted when the multicast address table * changes and at that point we only have the current list of addresses: * we only know the current state, not the previous state, so we don't * actually know what addresses were removed or added. The firmware has * state, but we can't get our grubby mits on it, and there is no 'delete * all multicast addresses' command. Hence, we have to maintain our own * state so we know what addresses have been programmed into the NIC at * any given time. */ static void ti_setmulti(struct ti_softc *sc) { struct ifnet *ifp; struct ifmultiaddr *ifma; struct ti_cmd_desc cmd; struct ti_mc_entry *mc; uint32_t intrs; TI_LOCK_ASSERT(sc); ifp = sc->ti_ifp; if (ifp->if_flags & IFF_ALLMULTI) { TI_DO_CMD(TI_CMD_SET_ALLMULTI, TI_CMD_CODE_ALLMULTI_ENB, 0); return; } else { TI_DO_CMD(TI_CMD_SET_ALLMULTI, TI_CMD_CODE_ALLMULTI_DIS, 0); } /* Disable interrupts. */ intrs = CSR_READ_4(sc, TI_MB_HOSTINTR); CSR_WRITE_4(sc, TI_MB_HOSTINTR, 1); /* First, zot all the existing filters. */ while (SLIST_FIRST(&sc->ti_mc_listhead) != NULL) { mc = SLIST_FIRST(&sc->ti_mc_listhead); ti_del_mcast(sc, &mc->mc_addr); SLIST_REMOVE_HEAD(&sc->ti_mc_listhead, mc_entries); free(mc, M_DEVBUF); } /* Now program new ones. */ if_maddr_rlock(ifp); TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) { if (ifma->ifma_addr->sa_family != AF_LINK) continue; mc = malloc(sizeof(struct ti_mc_entry), M_DEVBUF, M_NOWAIT); if (mc == NULL) { device_printf(sc->ti_dev, "no memory for mcast filter entry\n"); continue; } bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr), (char *)&mc->mc_addr, ETHER_ADDR_LEN); SLIST_INSERT_HEAD(&sc->ti_mc_listhead, mc, mc_entries); ti_add_mcast(sc, &mc->mc_addr); } if_maddr_runlock(ifp); /* Re-enable interrupts. */ CSR_WRITE_4(sc, TI_MB_HOSTINTR, intrs); } /* * Check to see if the BIOS has configured us for a 64 bit slot when * we aren't actually in one. If we detect this condition, we can work * around it on the Tigon 2 by setting a bit in the PCI state register, * but for the Tigon 1 we must give up and abort the interface attach. */ static int ti_64bitslot_war(struct ti_softc *sc) { if (!(CSR_READ_4(sc, TI_PCI_STATE) & TI_PCISTATE_32BIT_BUS)) { CSR_WRITE_4(sc, 0x600, 0); CSR_WRITE_4(sc, 0x604, 0); CSR_WRITE_4(sc, 0x600, 0x5555AAAA); if (CSR_READ_4(sc, 0x604) == 0x5555AAAA) { if (sc->ti_hwrev == TI_HWREV_TIGON) return (EINVAL); else { TI_SETBIT(sc, TI_PCI_STATE, TI_PCISTATE_32BIT_BUS); return (0); } } } return (0); } /* * Do endian, PCI and DMA initialization. Also check the on-board ROM * self-test results. */ static int ti_chipinit(struct ti_softc *sc) { uint32_t cacheline; uint32_t pci_writemax = 0; uint32_t hdrsplit; /* Initialize link to down state. */ sc->ti_linkstat = TI_EV_CODE_LINK_DOWN; /* Set endianness before we access any non-PCI registers. */ #if 0 && BYTE_ORDER == BIG_ENDIAN CSR_WRITE_4(sc, TI_MISC_HOST_CTL, TI_MHC_BIGENDIAN_INIT | (TI_MHC_BIGENDIAN_INIT << 24)); #else CSR_WRITE_4(sc, TI_MISC_HOST_CTL, TI_MHC_LITTLEENDIAN_INIT | (TI_MHC_LITTLEENDIAN_INIT << 24)); #endif /* Check the ROM failed bit to see if self-tests passed. */ if (CSR_READ_4(sc, TI_CPU_STATE) & TI_CPUSTATE_ROMFAIL) { device_printf(sc->ti_dev, "board self-diagnostics failed!\n"); return (ENODEV); } /* Halt the CPU. */ TI_SETBIT(sc, TI_CPU_STATE, TI_CPUSTATE_HALT); /* Figure out the hardware revision. */ switch (CSR_READ_4(sc, TI_MISC_HOST_CTL) & TI_MHC_CHIP_REV_MASK) { case TI_REV_TIGON_I: sc->ti_hwrev = TI_HWREV_TIGON; break; case TI_REV_TIGON_II: sc->ti_hwrev = TI_HWREV_TIGON_II; break; default: device_printf(sc->ti_dev, "unsupported chip revision\n"); return (ENODEV); } /* Do special setup for Tigon 2. */ if (sc->ti_hwrev == TI_HWREV_TIGON_II) { TI_SETBIT(sc, TI_CPU_CTL_B, TI_CPUSTATE_HALT); TI_SETBIT(sc, TI_MISC_LOCAL_CTL, TI_MLC_SRAM_BANK_512K); TI_SETBIT(sc, TI_MISC_CONF, TI_MCR_SRAM_SYNCHRONOUS); } /* * We don't have firmware source for the Tigon 1, so Tigon 1 boards * can't do header splitting. */ #ifdef TI_JUMBO_HDRSPLIT if (sc->ti_hwrev != TI_HWREV_TIGON) sc->ti_hdrsplit = 1; else device_printf(sc->ti_dev, "can't do header splitting on a Tigon I board\n"); #endif /* TI_JUMBO_HDRSPLIT */ /* Set up the PCI state register. */ CSR_WRITE_4(sc, TI_PCI_STATE, TI_PCI_READ_CMD|TI_PCI_WRITE_CMD); if (sc->ti_hwrev == TI_HWREV_TIGON_II) { TI_SETBIT(sc, TI_PCI_STATE, TI_PCISTATE_USE_MEM_RD_MULT); } /* Clear the read/write max DMA parameters. */ TI_CLRBIT(sc, TI_PCI_STATE, (TI_PCISTATE_WRITE_MAXDMA| TI_PCISTATE_READ_MAXDMA)); /* Get cache line size. */ cacheline = CSR_READ_4(sc, TI_PCI_BIST) & 0xFF; /* * If the system has set enabled the PCI memory write * and invalidate command in the command register, set * the write max parameter accordingly. This is necessary * to use MWI with the Tigon 2. */ if (CSR_READ_4(sc, TI_PCI_CMDSTAT) & PCIM_CMD_MWIEN) { switch (cacheline) { case 1: case 4: case 8: case 16: case 32: case 64: break; default: /* Disable PCI memory write and invalidate. */ if (bootverbose) device_printf(sc->ti_dev, "cache line size %d" " not supported; disabling PCI MWI\n", cacheline); CSR_WRITE_4(sc, TI_PCI_CMDSTAT, CSR_READ_4(sc, TI_PCI_CMDSTAT) & ~PCIM_CMD_MWIEN); break; } } TI_SETBIT(sc, TI_PCI_STATE, pci_writemax); /* This sets the min dma param all the way up (0xff). */ TI_SETBIT(sc, TI_PCI_STATE, TI_PCISTATE_MINDMA); if (sc->ti_hdrsplit) hdrsplit = TI_OPMODE_JUMBO_HDRSPLIT; else hdrsplit = 0; /* Configure DMA variables. */ #if BYTE_ORDER == BIG_ENDIAN CSR_WRITE_4(sc, TI_GCR_OPMODE, TI_OPMODE_BYTESWAP_BD | TI_OPMODE_BYTESWAP_DATA | TI_OPMODE_WORDSWAP_BD | TI_OPMODE_WARN_ENB | TI_OPMODE_FATAL_ENB | TI_OPMODE_DONT_FRAG_JUMBO | hdrsplit); #else /* BYTE_ORDER */ CSR_WRITE_4(sc, TI_GCR_OPMODE, TI_OPMODE_BYTESWAP_DATA| TI_OPMODE_WORDSWAP_BD|TI_OPMODE_DONT_FRAG_JUMBO| TI_OPMODE_WARN_ENB|TI_OPMODE_FATAL_ENB | hdrsplit); #endif /* BYTE_ORDER */ /* * Only allow 1 DMA channel to be active at a time. * I don't think this is a good idea, but without it * the firmware racks up lots of nicDmaReadRingFull * errors. This is not compatible with hardware checksums. */ if ((sc->ti_ifp->if_capenable & (IFCAP_TXCSUM | IFCAP_RXCSUM)) == 0) TI_SETBIT(sc, TI_GCR_OPMODE, TI_OPMODE_1_DMA_ACTIVE); /* Recommended settings from Tigon manual. */ CSR_WRITE_4(sc, TI_GCR_DMA_WRITECFG, TI_DMA_STATE_THRESH_8W); CSR_WRITE_4(sc, TI_GCR_DMA_READCFG, TI_DMA_STATE_THRESH_8W); if (ti_64bitslot_war(sc)) { device_printf(sc->ti_dev, "bios thinks we're in a 64 bit slot, " "but we aren't"); return (EINVAL); } return (0); } /* * Initialize the general information block and firmware, and * start the CPU(s) running. */ static int ti_gibinit(struct ti_softc *sc) { struct ifnet *ifp; struct ti_rcb *rcb; int i; TI_LOCK_ASSERT(sc); ifp = sc->ti_ifp; /* Disable interrupts for now. */ CSR_WRITE_4(sc, TI_MB_HOSTINTR, 1); /* Tell the chip where to find the general information block. */ CSR_WRITE_4(sc, TI_GCR_GENINFO_HI, (uint64_t)sc->ti_rdata.ti_info_paddr >> 32); CSR_WRITE_4(sc, TI_GCR_GENINFO_LO, sc->ti_rdata.ti_info_paddr & 0xFFFFFFFF); /* Load the firmware into SRAM. */ ti_loadfw(sc); /* Set up the contents of the general info and ring control blocks. */ /* Set up the event ring and producer pointer. */ bzero(sc->ti_rdata.ti_event_ring, TI_EVENT_RING_SZ); rcb = &sc->ti_rdata.ti_info->ti_ev_rcb; ti_hostaddr64(&rcb->ti_hostaddr, sc->ti_rdata.ti_event_ring_paddr); rcb->ti_flags = 0; ti_hostaddr64(&sc->ti_rdata.ti_info->ti_ev_prodidx_ptr, sc->ti_rdata.ti_status_paddr + offsetof(struct ti_status, ti_ev_prodidx_r)); sc->ti_ev_prodidx.ti_idx = 0; CSR_WRITE_4(sc, TI_GCR_EVENTCONS_IDX, 0); sc->ti_ev_saved_considx = 0; /* Set up the command ring and producer mailbox. */ rcb = &sc->ti_rdata.ti_info->ti_cmd_rcb; ti_hostaddr64(&rcb->ti_hostaddr, TI_GCR_NIC_ADDR(TI_GCR_CMDRING)); rcb->ti_flags = 0; rcb->ti_max_len = 0; for (i = 0; i < TI_CMD_RING_CNT; i++) { CSR_WRITE_4(sc, TI_GCR_CMDRING + (i * 4), 0); } CSR_WRITE_4(sc, TI_GCR_CMDCONS_IDX, 0); CSR_WRITE_4(sc, TI_MB_CMDPROD_IDX, 0); sc->ti_cmd_saved_prodidx = 0; /* * Assign the address of the stats refresh buffer. * We re-use the current stats buffer for this to * conserve memory. */ bzero(&sc->ti_rdata.ti_info->ti_stats, sizeof(struct ti_stats)); ti_hostaddr64(&sc->ti_rdata.ti_info->ti_refresh_stats_ptr, sc->ti_rdata.ti_info_paddr + offsetof(struct ti_gib, ti_stats)); /* Set up the standard receive ring. */ rcb = &sc->ti_rdata.ti_info->ti_std_rx_rcb; ti_hostaddr64(&rcb->ti_hostaddr, sc->ti_rdata.ti_rx_std_ring_paddr); rcb->ti_max_len = TI_FRAMELEN; rcb->ti_flags = 0; if (sc->ti_ifp->if_capenable & IFCAP_RXCSUM) rcb->ti_flags |= TI_RCB_FLAG_TCP_UDP_CKSUM | TI_RCB_FLAG_IP_CKSUM | TI_RCB_FLAG_NO_PHDR_CKSUM; if (sc->ti_ifp->if_capenable & IFCAP_VLAN_HWTAGGING) rcb->ti_flags |= TI_RCB_FLAG_VLAN_ASSIST; /* Set up the jumbo receive ring. */ rcb = &sc->ti_rdata.ti_info->ti_jumbo_rx_rcb; ti_hostaddr64(&rcb->ti_hostaddr, sc->ti_rdata.ti_rx_jumbo_ring_paddr); #ifndef TI_SF_BUF_JUMBO rcb->ti_max_len = MJUM9BYTES - ETHER_ALIGN; rcb->ti_flags = 0; #else rcb->ti_max_len = PAGE_SIZE; rcb->ti_flags = TI_RCB_FLAG_USE_EXT_RX_BD; #endif if (sc->ti_ifp->if_capenable & IFCAP_RXCSUM) rcb->ti_flags |= TI_RCB_FLAG_TCP_UDP_CKSUM | TI_RCB_FLAG_IP_CKSUM | TI_RCB_FLAG_NO_PHDR_CKSUM; if (sc->ti_ifp->if_capenable & IFCAP_VLAN_HWTAGGING) rcb->ti_flags |= TI_RCB_FLAG_VLAN_ASSIST; /* * Set up the mini ring. Only activated on the * Tigon 2 but the slot in the config block is * still there on the Tigon 1. */ rcb = &sc->ti_rdata.ti_info->ti_mini_rx_rcb; ti_hostaddr64(&rcb->ti_hostaddr, sc->ti_rdata.ti_rx_mini_ring_paddr); rcb->ti_max_len = MHLEN - ETHER_ALIGN; if (sc->ti_hwrev == TI_HWREV_TIGON) rcb->ti_flags = TI_RCB_FLAG_RING_DISABLED; else rcb->ti_flags = 0; if (sc->ti_ifp->if_capenable & IFCAP_RXCSUM) rcb->ti_flags |= TI_RCB_FLAG_TCP_UDP_CKSUM | TI_RCB_FLAG_IP_CKSUM | TI_RCB_FLAG_NO_PHDR_CKSUM; if (sc->ti_ifp->if_capenable & IFCAP_VLAN_HWTAGGING) rcb->ti_flags |= TI_RCB_FLAG_VLAN_ASSIST; /* * Set up the receive return ring. */ rcb = &sc->ti_rdata.ti_info->ti_return_rcb; ti_hostaddr64(&rcb->ti_hostaddr, sc->ti_rdata.ti_rx_return_ring_paddr); rcb->ti_flags = 0; rcb->ti_max_len = TI_RETURN_RING_CNT; ti_hostaddr64(&sc->ti_rdata.ti_info->ti_return_prodidx_ptr, sc->ti_rdata.ti_status_paddr + offsetof(struct ti_status, ti_return_prodidx_r)); /* * Set up the tx ring. Note: for the Tigon 2, we have the option * of putting the transmit ring in the host's address space and * letting the chip DMA it instead of leaving the ring in the NIC's * memory and accessing it through the shared memory region. We * do this for the Tigon 2, but it doesn't work on the Tigon 1, * so we have to revert to the shared memory scheme if we detect * a Tigon 1 chip. */ CSR_WRITE_4(sc, TI_WINBASE, TI_TX_RING_BASE); if (sc->ti_rdata.ti_tx_ring != NULL) bzero(sc->ti_rdata.ti_tx_ring, TI_TX_RING_SZ); rcb = &sc->ti_rdata.ti_info->ti_tx_rcb; if (sc->ti_hwrev == TI_HWREV_TIGON) rcb->ti_flags = 0; else rcb->ti_flags = TI_RCB_FLAG_HOST_RING; if (sc->ti_ifp->if_capenable & IFCAP_VLAN_HWTAGGING) rcb->ti_flags |= TI_RCB_FLAG_VLAN_ASSIST; if (sc->ti_ifp->if_capenable & IFCAP_TXCSUM) rcb->ti_flags |= TI_RCB_FLAG_TCP_UDP_CKSUM | TI_RCB_FLAG_IP_CKSUM | TI_RCB_FLAG_NO_PHDR_CKSUM; rcb->ti_max_len = TI_TX_RING_CNT; if (sc->ti_hwrev == TI_HWREV_TIGON) ti_hostaddr64(&rcb->ti_hostaddr, TI_TX_RING_BASE); else ti_hostaddr64(&rcb->ti_hostaddr, sc->ti_rdata.ti_tx_ring_paddr); ti_hostaddr64(&sc->ti_rdata.ti_info->ti_tx_considx_ptr, sc->ti_rdata.ti_status_paddr + offsetof(struct ti_status, ti_tx_considx_r)); bus_dmamap_sync(sc->ti_cdata.ti_gib_tag, sc->ti_cdata.ti_gib_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); bus_dmamap_sync(sc->ti_cdata.ti_status_tag, sc->ti_cdata.ti_status_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); bus_dmamap_sync(sc->ti_cdata.ti_event_ring_tag, sc->ti_cdata.ti_event_ring_map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); if (sc->ti_rdata.ti_tx_ring != NULL) bus_dmamap_sync(sc->ti_cdata.ti_tx_ring_tag, sc->ti_cdata.ti_tx_ring_map, BUS_DMASYNC_PREWRITE); /* Set up tunables */ #if 0 if (ifp->if_mtu > ETHERMTU + ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) CSR_WRITE_4(sc, TI_GCR_RX_COAL_TICKS, (sc->ti_rx_coal_ticks / 10)); else #endif CSR_WRITE_4(sc, TI_GCR_RX_COAL_TICKS, sc->ti_rx_coal_ticks); CSR_WRITE_4(sc, TI_GCR_TX_COAL_TICKS, sc->ti_tx_coal_ticks); CSR_WRITE_4(sc, TI_GCR_STAT_TICKS, sc->ti_stat_ticks); CSR_WRITE_4(sc, TI_GCR_RX_MAX_COAL_BD, sc->ti_rx_max_coal_bds); CSR_WRITE_4(sc, TI_GCR_TX_MAX_COAL_BD, sc->ti_tx_max_coal_bds); CSR_WRITE_4(sc, TI_GCR_TX_BUFFER_RATIO, sc->ti_tx_buf_ratio); /* Turn interrupts on. */ CSR_WRITE_4(sc, TI_GCR_MASK_INTRS, 0); CSR_WRITE_4(sc, TI_MB_HOSTINTR, 0); /* Start CPU. */ TI_CLRBIT(sc, TI_CPU_STATE, (TI_CPUSTATE_HALT|TI_CPUSTATE_STEP)); return (0); } /* * Probe for a Tigon chip. Check the PCI vendor and device IDs * against our list and return its name if we find a match. */ static int ti_probe(device_t dev) { const struct ti_type *t; t = ti_devs; while (t->ti_name != NULL) { if ((pci_get_vendor(dev) == t->ti_vid) && (pci_get_device(dev) == t->ti_did)) { device_set_desc(dev, t->ti_name); return (BUS_PROBE_DEFAULT); } t++; } return (ENXIO); } static int ti_attach(device_t dev) { struct ifnet *ifp; struct ti_softc *sc; int error = 0, rid; u_char eaddr[6]; sc = device_get_softc(dev); sc->ti_dev = dev; mtx_init(&sc->ti_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK, MTX_DEF); callout_init_mtx(&sc->ti_watchdog, &sc->ti_mtx, 0); ifmedia_init(&sc->ifmedia, IFM_IMASK, ti_ifmedia_upd, ti_ifmedia_sts); ifp = sc->ti_ifp = if_alloc(IFT_ETHER); if (ifp == NULL) { device_printf(dev, "can not if_alloc()\n"); error = ENOSPC; goto fail; } sc->ti_ifp->if_hwassist = TI_CSUM_FEATURES; sc->ti_ifp->if_capabilities = IFCAP_TXCSUM | IFCAP_RXCSUM; sc->ti_ifp->if_capenable = sc->ti_ifp->if_capabilities; /* * Map control/status registers. */ pci_enable_busmaster(dev); rid = PCIR_BAR(0); sc->ti_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE); if (sc->ti_res == NULL) { device_printf(dev, "couldn't map memory\n"); error = ENXIO; goto fail; } sc->ti_btag = rman_get_bustag(sc->ti_res); sc->ti_bhandle = rman_get_bushandle(sc->ti_res); /* Allocate interrupt */ rid = 0; sc->ti_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_SHAREABLE | RF_ACTIVE); if (sc->ti_irq == NULL) { device_printf(dev, "couldn't map interrupt\n"); error = ENXIO; goto fail; } if (ti_chipinit(sc)) { device_printf(dev, "chip initialization failed\n"); error = ENXIO; goto fail; } /* Zero out the NIC's on-board SRAM. */ ti_mem_zero(sc, 0x2000, 0x100000 - 0x2000); /* Init again -- zeroing memory may have clobbered some registers. */ if (ti_chipinit(sc)) { device_printf(dev, "chip initialization failed\n"); error = ENXIO; goto fail; } /* * Get station address from the EEPROM. Note: the manual states * that the MAC address is at offset 0x8c, however the data is * stored as two longwords (since that's how it's loaded into * the NIC). This means the MAC address is actually preceded * by two zero bytes. We need to skip over those. */ if (ti_read_eeprom(sc, eaddr, TI_EE_MAC_OFFSET + 2, ETHER_ADDR_LEN)) { device_printf(dev, "failed to read station address\n"); error = ENXIO; goto fail; } /* Allocate working area for memory dump. */ sc->ti_membuf = malloc(sizeof(uint8_t) * TI_WINLEN, M_DEVBUF, M_NOWAIT); sc->ti_membuf2 = malloc(sizeof(uint8_t) * TI_WINLEN, M_DEVBUF, M_NOWAIT); if (sc->ti_membuf == NULL || sc->ti_membuf2 == NULL) { device_printf(dev, "cannot allocate memory buffer\n"); error = ENOMEM; goto fail; } if ((error = ti_dma_alloc(sc)) != 0) goto fail; /* * We really need a better way to tell a 1000baseTX card * from a 1000baseSX one, since in theory there could be * OEMed 1000baseTX cards from lame vendors who aren't * clever enough to change the PCI ID. For the moment * though, the AceNIC is the only copper card available. */ if (pci_get_vendor(dev) == ALT_VENDORID && pci_get_device(dev) == ALT_DEVICEID_ACENIC_COPPER) sc->ti_copper = 1; /* Ok, it's not the only copper card available. */ if (pci_get_vendor(dev) == NG_VENDORID && pci_get_device(dev) == NG_DEVICEID_GA620T) sc->ti_copper = 1; /* Set default tunable values. */ ti_sysctl_node(sc); /* Set up ifnet structure */ ifp->if_softc = sc; if_initname(ifp, device_get_name(dev), device_get_unit(dev)); ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; ifp->if_ioctl = ti_ioctl; ifp->if_start = ti_start; ifp->if_init = ti_init; ifp->if_get_counter = ti_get_counter; ifp->if_baudrate = IF_Gbps(1UL); ifp->if_snd.ifq_drv_maxlen = TI_TX_RING_CNT - 1; IFQ_SET_MAXLEN(&ifp->if_snd, ifp->if_snd.ifq_drv_maxlen); IFQ_SET_READY(&ifp->if_snd); /* Set up ifmedia support. */ if (sc->ti_copper) { /* * Copper cards allow manual 10/100 mode selection, * but not manual 1000baseTX mode selection. Why? * Because currently there's no way to specify the * master/slave setting through the firmware interface, * so Alteon decided to just bag it and handle it * via autonegotiation. */ ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_10_T, 0, NULL); ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_10_T|IFM_FDX, 0, NULL); ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_100_TX, 0, NULL); ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_100_TX|IFM_FDX, 0, NULL); ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_1000_T, 0, NULL); ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_1000_T|IFM_FDX, 0, NULL); } else { /* Fiber cards don't support 10/100 modes. */ ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_1000_SX, 0, NULL); ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_1000_SX|IFM_FDX, 0, NULL); } ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_AUTO, 0, NULL); ifmedia_set(&sc->ifmedia, IFM_ETHER|IFM_AUTO); /* * We're assuming here that card initialization is a sequential * thing. If it isn't, multiple cards probing at the same time * could stomp on the list of softcs here. */ /* Register the device */ sc->dev = make_dev(&ti_cdevsw, device_get_unit(dev), UID_ROOT, GID_OPERATOR, 0600, "ti%d", device_get_unit(dev)); sc->dev->si_drv1 = sc; /* * Call MI attach routine. */ ether_ifattach(ifp, eaddr); /* VLAN capability setup. */ ifp->if_capabilities |= IFCAP_VLAN_MTU | IFCAP_VLAN_HWCSUM | IFCAP_VLAN_HWTAGGING; ifp->if_capenable = ifp->if_capabilities; /* Tell the upper layer we support VLAN over-sized frames. */ ifp->if_hdrlen = sizeof(struct ether_vlan_header); /* Driver supports link state tracking. */ ifp->if_capabilities |= IFCAP_LINKSTATE; ifp->if_capenable |= IFCAP_LINKSTATE; /* Hook interrupt last to avoid having to lock softc */ error = bus_setup_intr(dev, sc->ti_irq, INTR_TYPE_NET|INTR_MPSAFE, NULL, ti_intr, sc, &sc->ti_intrhand); if (error) { device_printf(dev, "couldn't set up irq\n"); goto fail; } fail: if (error) ti_detach(dev); return (error); } /* * Shutdown hardware and free up resources. This can be called any * time after the mutex has been initialized. It is called in both * the error case in attach and the normal detach case so it needs * to be careful about only freeing resources that have actually been * allocated. */ static int ti_detach(device_t dev) { struct ti_softc *sc; struct ifnet *ifp; sc = device_get_softc(dev); if (sc->dev) destroy_dev(sc->dev); KASSERT(mtx_initialized(&sc->ti_mtx), ("ti mutex not initialized")); ifp = sc->ti_ifp; if (device_is_attached(dev)) { ether_ifdetach(ifp); TI_LOCK(sc); ti_stop(sc); TI_UNLOCK(sc); } /* These should only be active if attach succeeded */ callout_drain(&sc->ti_watchdog); bus_generic_detach(dev); ti_dma_free(sc); ifmedia_removeall(&sc->ifmedia); if (sc->ti_intrhand) bus_teardown_intr(dev, sc->ti_irq, sc->ti_intrhand); if (sc->ti_irq) bus_release_resource(dev, SYS_RES_IRQ, 0, sc->ti_irq); if (sc->ti_res) { bus_release_resource(dev, SYS_RES_MEMORY, PCIR_BAR(0), sc->ti_res); } if (ifp) if_free(ifp); if (sc->ti_membuf) free(sc->ti_membuf, M_DEVBUF); if (sc->ti_membuf2) free(sc->ti_membuf2, M_DEVBUF); mtx_destroy(&sc->ti_mtx); return (0); } #ifdef TI_JUMBO_HDRSPLIT /* * If hdr_len is 0, that means that header splitting wasn't done on * this packet for some reason. The two most likely reasons are that * the protocol isn't a supported protocol for splitting, or this * packet had a fragment offset that wasn't 0. * * The header length, if it is non-zero, will always be the length of * the headers on the packet, but that length could be longer than the * first mbuf. So we take the minimum of the two as the actual * length. */ static __inline void ti_hdr_split(struct mbuf *top, int hdr_len, int pkt_len, int idx) { int i = 0; int lengths[4] = {0, 0, 0, 0}; struct mbuf *m, *mp; if (hdr_len != 0) top->m_len = min(hdr_len, top->m_len); pkt_len -= top->m_len; lengths[i++] = top->m_len; mp = top; for (m = top->m_next; m && pkt_len; m = m->m_next) { m->m_len = m->m_ext.ext_size = min(m->m_len, pkt_len); pkt_len -= m->m_len; lengths[i++] = m->m_len; mp = m; } #if 0 if (hdr_len != 0) printf("got split packet: "); else printf("got non-split packet: "); printf("%d,%d,%d,%d = %d\n", lengths[0], lengths[1], lengths[2], lengths[3], lengths[0] + lengths[1] + lengths[2] + lengths[3]); #endif if (pkt_len) panic("header splitting didn't"); if (m) { m_freem(m); mp->m_next = NULL; } if (mp->m_next != NULL) panic("ti_hdr_split: last mbuf in chain should be null"); } #endif /* TI_JUMBO_HDRSPLIT */ static void ti_discard_std(struct ti_softc *sc, int i) { struct ti_rx_desc *r; r = &sc->ti_rdata.ti_rx_std_ring[i]; r->ti_len = MCLBYTES - ETHER_ALIGN; r->ti_type = TI_BDTYPE_RECV_BD; r->ti_flags = 0; r->ti_vlan_tag = 0; r->ti_tcp_udp_cksum = 0; if (sc->ti_ifp->if_capenable & IFCAP_RXCSUM) r->ti_flags |= TI_BDFLAG_TCP_UDP_CKSUM | TI_BDFLAG_IP_CKSUM; r->ti_idx = i; } static void ti_discard_mini(struct ti_softc *sc, int i) { struct ti_rx_desc *r; r = &sc->ti_rdata.ti_rx_mini_ring[i]; r->ti_len = MHLEN - ETHER_ALIGN; r->ti_type = TI_BDTYPE_RECV_BD; r->ti_flags = TI_BDFLAG_MINI_RING; r->ti_vlan_tag = 0; r->ti_tcp_udp_cksum = 0; if (sc->ti_ifp->if_capenable & IFCAP_RXCSUM) r->ti_flags |= TI_BDFLAG_TCP_UDP_CKSUM | TI_BDFLAG_IP_CKSUM; r->ti_idx = i; } #ifndef TI_SF_BUF_JUMBO static void ti_discard_jumbo(struct ti_softc *sc, int i) { struct ti_rx_desc *r; r = &sc->ti_rdata.ti_rx_jumbo_ring[i]; r->ti_len = MJUM9BYTES - ETHER_ALIGN; r->ti_type = TI_BDTYPE_RECV_JUMBO_BD; r->ti_flags = TI_BDFLAG_JUMBO_RING; r->ti_vlan_tag = 0; r->ti_tcp_udp_cksum = 0; if (sc->ti_ifp->if_capenable & IFCAP_RXCSUM) r->ti_flags |= TI_BDFLAG_TCP_UDP_CKSUM | TI_BDFLAG_IP_CKSUM; r->ti_idx = i; } #endif /* * Frame reception handling. This is called if there's a frame * on the receive return list. * * Note: we have to be able to handle three possibilities here: * 1) the frame is from the mini receive ring (can only happen) * on Tigon 2 boards) * 2) the frame is from the jumbo receive ring * 3) the frame is from the standard receive ring */ static void ti_rxeof(struct ti_softc *sc) { struct ifnet *ifp; #ifdef TI_SF_BUF_JUMBO bus_dmamap_t map; #endif struct ti_cmd_desc cmd; int jumbocnt, minicnt, stdcnt, ti_len; TI_LOCK_ASSERT(sc); ifp = sc->ti_ifp; bus_dmamap_sync(sc->ti_cdata.ti_rx_std_ring_tag, sc->ti_cdata.ti_rx_std_ring_map, BUS_DMASYNC_POSTWRITE); if (ifp->if_mtu > ETHERMTU + ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) bus_dmamap_sync(sc->ti_cdata.ti_rx_jumbo_ring_tag, sc->ti_cdata.ti_rx_jumbo_ring_map, BUS_DMASYNC_POSTWRITE); if (sc->ti_rdata.ti_rx_mini_ring != NULL) bus_dmamap_sync(sc->ti_cdata.ti_rx_mini_ring_tag, sc->ti_cdata.ti_rx_mini_ring_map, BUS_DMASYNC_POSTWRITE); bus_dmamap_sync(sc->ti_cdata.ti_rx_return_ring_tag, sc->ti_cdata.ti_rx_return_ring_map, BUS_DMASYNC_POSTREAD); jumbocnt = minicnt = stdcnt = 0; while (sc->ti_rx_saved_considx != sc->ti_return_prodidx.ti_idx) { struct ti_rx_desc *cur_rx; uint32_t rxidx; struct mbuf *m = NULL; uint16_t vlan_tag = 0; int have_tag = 0; cur_rx = &sc->ti_rdata.ti_rx_return_ring[sc->ti_rx_saved_considx]; rxidx = cur_rx->ti_idx; ti_len = cur_rx->ti_len; TI_INC(sc->ti_rx_saved_considx, TI_RETURN_RING_CNT); if (cur_rx->ti_flags & TI_BDFLAG_VLAN_TAG) { have_tag = 1; vlan_tag = cur_rx->ti_vlan_tag; } if (cur_rx->ti_flags & TI_BDFLAG_JUMBO_RING) { jumbocnt++; TI_INC(sc->ti_jumbo, TI_JUMBO_RX_RING_CNT); m = sc->ti_cdata.ti_rx_jumbo_chain[rxidx]; #ifndef TI_SF_BUF_JUMBO if (cur_rx->ti_flags & TI_BDFLAG_ERROR) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); ti_discard_jumbo(sc, rxidx); continue; } if (ti_newbuf_jumbo(sc, rxidx, NULL) != 0) { if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1); ti_discard_jumbo(sc, rxidx); continue; } m->m_len = ti_len; #else /* !TI_SF_BUF_JUMBO */ sc->ti_cdata.ti_rx_jumbo_chain[rxidx] = NULL; map = sc->ti_cdata.ti_rx_jumbo_maps[rxidx]; bus_dmamap_sync(sc->ti_cdata.ti_rx_jumbo_tag, map, BUS_DMASYNC_POSTREAD); bus_dmamap_unload(sc->ti_cdata.ti_rx_jumbo_tag, map); if (cur_rx->ti_flags & TI_BDFLAG_ERROR) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); ti_newbuf_jumbo(sc, sc->ti_jumbo, m); continue; } if (ti_newbuf_jumbo(sc, sc->ti_jumbo, NULL) == ENOBUFS) { if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1); ti_newbuf_jumbo(sc, sc->ti_jumbo, m); continue; } #ifdef TI_JUMBO_HDRSPLIT if (sc->ti_hdrsplit) ti_hdr_split(m, TI_HOSTADDR(cur_rx->ti_addr), ti_len, rxidx); else #endif /* TI_JUMBO_HDRSPLIT */ m_adj(m, ti_len - m->m_pkthdr.len); #endif /* TI_SF_BUF_JUMBO */ } else if (cur_rx->ti_flags & TI_BDFLAG_MINI_RING) { minicnt++; TI_INC(sc->ti_mini, TI_MINI_RX_RING_CNT); m = sc->ti_cdata.ti_rx_mini_chain[rxidx]; if (cur_rx->ti_flags & TI_BDFLAG_ERROR) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); ti_discard_mini(sc, rxidx); continue; } if (ti_newbuf_mini(sc, rxidx) != 0) { if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1); ti_discard_mini(sc, rxidx); continue; } m->m_len = ti_len; } else { stdcnt++; TI_INC(sc->ti_std, TI_STD_RX_RING_CNT); m = sc->ti_cdata.ti_rx_std_chain[rxidx]; if (cur_rx->ti_flags & TI_BDFLAG_ERROR) { if_inc_counter(ifp, IFCOUNTER_IERRORS, 1); ti_discard_std(sc, rxidx); continue; } if (ti_newbuf_std(sc, rxidx) != 0) { if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1); ti_discard_std(sc, rxidx); continue; } m->m_len = ti_len; } m->m_pkthdr.len = ti_len; if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1); m->m_pkthdr.rcvif = ifp; if (ifp->if_capenable & IFCAP_RXCSUM) { if (cur_rx->ti_flags & TI_BDFLAG_IP_CKSUM) { m->m_pkthdr.csum_flags |= CSUM_IP_CHECKED; if ((cur_rx->ti_ip_cksum ^ 0xffff) == 0) m->m_pkthdr.csum_flags |= CSUM_IP_VALID; } if (cur_rx->ti_flags & TI_BDFLAG_TCP_UDP_CKSUM) { m->m_pkthdr.csum_data = cur_rx->ti_tcp_udp_cksum; m->m_pkthdr.csum_flags |= CSUM_DATA_VALID; } } /* * If we received a packet with a vlan tag, * tag it before passing the packet upward. */ if (have_tag) { m->m_pkthdr.ether_vtag = vlan_tag; m->m_flags |= M_VLANTAG; } TI_UNLOCK(sc); (*ifp->if_input)(ifp, m); TI_LOCK(sc); } bus_dmamap_sync(sc->ti_cdata.ti_rx_return_ring_tag, sc->ti_cdata.ti_rx_return_ring_map, BUS_DMASYNC_PREREAD); /* Only necessary on the Tigon 1. */ if (sc->ti_hwrev == TI_HWREV_TIGON) CSR_WRITE_4(sc, TI_GCR_RXRETURNCONS_IDX, sc->ti_rx_saved_considx); if (stdcnt > 0) { bus_dmamap_sync(sc->ti_cdata.ti_rx_std_ring_tag, sc->ti_cdata.ti_rx_std_ring_map, BUS_DMASYNC_PREWRITE); TI_UPDATE_STDPROD(sc, sc->ti_std); } if (minicnt > 0) { bus_dmamap_sync(sc->ti_cdata.ti_rx_mini_ring_tag, sc->ti_cdata.ti_rx_mini_ring_map, BUS_DMASYNC_PREWRITE); TI_UPDATE_MINIPROD(sc, sc->ti_mini); } if (jumbocnt > 0) { bus_dmamap_sync(sc->ti_cdata.ti_rx_jumbo_ring_tag, sc->ti_cdata.ti_rx_jumbo_ring_map, BUS_DMASYNC_PREWRITE); TI_UPDATE_JUMBOPROD(sc, sc->ti_jumbo); } } static void ti_txeof(struct ti_softc *sc) { struct ti_txdesc *txd; struct ti_tx_desc txdesc; struct ti_tx_desc *cur_tx = NULL; struct ifnet *ifp; int idx; ifp = sc->ti_ifp; txd = STAILQ_FIRST(&sc->ti_cdata.ti_txbusyq); if (txd == NULL) return; if (sc->ti_rdata.ti_tx_ring != NULL) bus_dmamap_sync(sc->ti_cdata.ti_tx_ring_tag, sc->ti_cdata.ti_tx_ring_map, BUS_DMASYNC_POSTWRITE); /* * Go through our tx ring and free mbufs for those * frames that have been sent. */ for (idx = sc->ti_tx_saved_considx; idx != sc->ti_tx_considx.ti_idx; TI_INC(idx, TI_TX_RING_CNT)) { if (sc->ti_hwrev == TI_HWREV_TIGON) { ti_mem_read(sc, TI_TX_RING_BASE + idx * sizeof(txdesc), sizeof(txdesc), &txdesc); cur_tx = &txdesc; } else cur_tx = &sc->ti_rdata.ti_tx_ring[idx]; sc->ti_txcnt--; ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; if ((cur_tx->ti_flags & TI_BDFLAG_END) == 0) continue; bus_dmamap_sync(sc->ti_cdata.ti_tx_tag, txd->tx_dmamap, BUS_DMASYNC_POSTWRITE); bus_dmamap_unload(sc->ti_cdata.ti_tx_tag, txd->tx_dmamap); if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1); m_freem(txd->tx_m); txd->tx_m = NULL; STAILQ_REMOVE_HEAD(&sc->ti_cdata.ti_txbusyq, tx_q); STAILQ_INSERT_TAIL(&sc->ti_cdata.ti_txfreeq, txd, tx_q); txd = STAILQ_FIRST(&sc->ti_cdata.ti_txbusyq); } sc->ti_tx_saved_considx = idx; if (sc->ti_txcnt == 0) sc->ti_timer = 0; } static void ti_intr(void *xsc) { struct ti_softc *sc; struct ifnet *ifp; sc = xsc; TI_LOCK(sc); ifp = sc->ti_ifp; /* Make sure this is really our interrupt. */ if (!(CSR_READ_4(sc, TI_MISC_HOST_CTL) & TI_MHC_INTSTATE)) { TI_UNLOCK(sc); return; } /* Ack interrupt and stop others from occurring. */ CSR_WRITE_4(sc, TI_MB_HOSTINTR, 1); if (ifp->if_drv_flags & IFF_DRV_RUNNING) { bus_dmamap_sync(sc->ti_cdata.ti_status_tag, sc->ti_cdata.ti_status_map, BUS_DMASYNC_POSTREAD); /* Check RX return ring producer/consumer */ ti_rxeof(sc); /* Check TX ring producer/consumer */ ti_txeof(sc); bus_dmamap_sync(sc->ti_cdata.ti_status_tag, sc->ti_cdata.ti_status_map, BUS_DMASYNC_PREREAD); } ti_handle_events(sc); if (ifp->if_drv_flags & IFF_DRV_RUNNING) { /* Re-enable interrupts. */ CSR_WRITE_4(sc, TI_MB_HOSTINTR, 0); if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) ti_start_locked(ifp); } TI_UNLOCK(sc); } static uint64_t ti_get_counter(struct ifnet *ifp, ift_counter cnt) { switch (cnt) { case IFCOUNTER_COLLISIONS: { struct ti_softc *sc; struct ti_stats *s; uint64_t rv; sc = if_getsoftc(ifp); s = &sc->ti_rdata.ti_info->ti_stats; TI_LOCK(sc); bus_dmamap_sync(sc->ti_cdata.ti_gib_tag, sc->ti_cdata.ti_gib_map, BUS_DMASYNC_POSTREAD); rv = s->dot3StatsSingleCollisionFrames + s->dot3StatsMultipleCollisionFrames + s->dot3StatsExcessiveCollisions + s->dot3StatsLateCollisions; bus_dmamap_sync(sc->ti_cdata.ti_gib_tag, sc->ti_cdata.ti_gib_map, BUS_DMASYNC_PREREAD); TI_UNLOCK(sc); return (rv); } default: return (if_get_counter_default(ifp, cnt)); } } /* * Encapsulate an mbuf chain in the tx ring by coupling the mbuf data * pointers to descriptors. */ static int ti_encap(struct ti_softc *sc, struct mbuf **m_head) { struct ti_txdesc *txd; struct ti_tx_desc *f; struct ti_tx_desc txdesc; struct mbuf *m; bus_dma_segment_t txsegs[TI_MAXTXSEGS]; uint16_t csum_flags; int error, frag, i, nseg; if ((txd = STAILQ_FIRST(&sc->ti_cdata.ti_txfreeq)) == NULL) return (ENOBUFS); error = bus_dmamap_load_mbuf_sg(sc->ti_cdata.ti_tx_tag, txd->tx_dmamap, *m_head, txsegs, &nseg, 0); if (error == EFBIG) { m = m_defrag(*m_head, M_NOWAIT); if (m == NULL) { m_freem(*m_head); *m_head = NULL; return (ENOMEM); } *m_head = m; error = bus_dmamap_load_mbuf_sg(sc->ti_cdata.ti_tx_tag, txd->tx_dmamap, *m_head, txsegs, &nseg, 0); if (error) { m_freem(*m_head); *m_head = NULL; return (error); } } else if (error != 0) return (error); if (nseg == 0) { m_freem(*m_head); *m_head = NULL; return (EIO); } if (sc->ti_txcnt + nseg >= TI_TX_RING_CNT) { bus_dmamap_unload(sc->ti_cdata.ti_tx_tag, txd->tx_dmamap); return (ENOBUFS); } bus_dmamap_sync(sc->ti_cdata.ti_tx_tag, txd->tx_dmamap, BUS_DMASYNC_PREWRITE); m = *m_head; csum_flags = 0; if (m->m_pkthdr.csum_flags & CSUM_IP) csum_flags |= TI_BDFLAG_IP_CKSUM; if (m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP)) csum_flags |= TI_BDFLAG_TCP_UDP_CKSUM; frag = sc->ti_tx_saved_prodidx; for (i = 0; i < nseg; i++) { if (sc->ti_hwrev == TI_HWREV_TIGON) { bzero(&txdesc, sizeof(txdesc)); f = &txdesc; } else f = &sc->ti_rdata.ti_tx_ring[frag]; ti_hostaddr64(&f->ti_addr, txsegs[i].ds_addr); f->ti_len = txsegs[i].ds_len; f->ti_flags = csum_flags; if (m->m_flags & M_VLANTAG) { f->ti_flags |= TI_BDFLAG_VLAN_TAG; f->ti_vlan_tag = m->m_pkthdr.ether_vtag; } else { f->ti_vlan_tag = 0; } if (sc->ti_hwrev == TI_HWREV_TIGON) ti_mem_write(sc, TI_TX_RING_BASE + frag * sizeof(txdesc), sizeof(txdesc), &txdesc); TI_INC(frag, TI_TX_RING_CNT); } sc->ti_tx_saved_prodidx = frag; /* set TI_BDFLAG_END on the last descriptor */ frag = (frag + TI_TX_RING_CNT - 1) % TI_TX_RING_CNT; if (sc->ti_hwrev == TI_HWREV_TIGON) { txdesc.ti_flags |= TI_BDFLAG_END; ti_mem_write(sc, TI_TX_RING_BASE + frag * sizeof(txdesc), sizeof(txdesc), &txdesc); } else sc->ti_rdata.ti_tx_ring[frag].ti_flags |= TI_BDFLAG_END; STAILQ_REMOVE_HEAD(&sc->ti_cdata.ti_txfreeq, tx_q); STAILQ_INSERT_TAIL(&sc->ti_cdata.ti_txbusyq, txd, tx_q); txd->tx_m = m; sc->ti_txcnt += nseg; return (0); } static void ti_start(struct ifnet *ifp) { struct ti_softc *sc; sc = ifp->if_softc; TI_LOCK(sc); ti_start_locked(ifp); TI_UNLOCK(sc); } /* * Main transmit routine. To avoid having to do mbuf copies, we put pointers * to the mbuf data regions directly in the transmit descriptors. */ static void ti_start_locked(struct ifnet *ifp) { struct ti_softc *sc; struct mbuf *m_head = NULL; int enq = 0; sc = ifp->if_softc; for (; !IFQ_DRV_IS_EMPTY(&ifp->if_snd) && sc->ti_txcnt < (TI_TX_RING_CNT - 16);) { IFQ_DRV_DEQUEUE(&ifp->if_snd, m_head); if (m_head == NULL) break; /* * Pack the data into the transmit ring. If we * don't have room, set the OACTIVE flag and wait * for the NIC to drain the ring. */ if (ti_encap(sc, &m_head)) { if (m_head == NULL) break; IFQ_DRV_PREPEND(&ifp->if_snd, m_head); ifp->if_drv_flags |= IFF_DRV_OACTIVE; break; } enq++; /* * If there's a BPF listener, bounce a copy of this frame * to him. */ ETHER_BPF_MTAP(ifp, m_head); } if (enq > 0) { if (sc->ti_rdata.ti_tx_ring != NULL) bus_dmamap_sync(sc->ti_cdata.ti_tx_ring_tag, sc->ti_cdata.ti_tx_ring_map, BUS_DMASYNC_PREWRITE); /* Transmit */ CSR_WRITE_4(sc, TI_MB_SENDPROD_IDX, sc->ti_tx_saved_prodidx); /* * Set a timeout in case the chip goes out to lunch. */ sc->ti_timer = 5; } } static void ti_init(void *xsc) { struct ti_softc *sc; sc = xsc; TI_LOCK(sc); ti_init_locked(sc); TI_UNLOCK(sc); } static void ti_init_locked(void *xsc) { struct ti_softc *sc = xsc; if (sc->ti_ifp->if_drv_flags & IFF_DRV_RUNNING) return; /* Cancel pending I/O and flush buffers. */ ti_stop(sc); /* Init the gen info block, ring control blocks and firmware. */ if (ti_gibinit(sc)) { device_printf(sc->ti_dev, "initialization failure\n"); return; } } static void ti_init2(struct ti_softc *sc) { struct ti_cmd_desc cmd; struct ifnet *ifp; uint8_t *ea; struct ifmedia *ifm; int tmp; TI_LOCK_ASSERT(sc); ifp = sc->ti_ifp; /* Specify MTU and interface index. */ CSR_WRITE_4(sc, TI_GCR_IFINDEX, device_get_unit(sc->ti_dev)); CSR_WRITE_4(sc, TI_GCR_IFMTU, ifp->if_mtu + ETHER_HDR_LEN + ETHER_CRC_LEN + ETHER_VLAN_ENCAP_LEN); TI_DO_CMD(TI_CMD_UPDATE_GENCOM, 0, 0); /* Load our MAC address. */ ea = IF_LLADDR(sc->ti_ifp); CSR_WRITE_4(sc, TI_GCR_PAR0, (ea[0] << 8) | ea[1]); CSR_WRITE_4(sc, TI_GCR_PAR1, (ea[2] << 24) | (ea[3] << 16) | (ea[4] << 8) | ea[5]); TI_DO_CMD(TI_CMD_SET_MAC_ADDR, 0, 0); /* Enable or disable promiscuous mode as needed. */ if (ifp->if_flags & IFF_PROMISC) { TI_DO_CMD(TI_CMD_SET_PROMISC_MODE, TI_CMD_CODE_PROMISC_ENB, 0); } else { TI_DO_CMD(TI_CMD_SET_PROMISC_MODE, TI_CMD_CODE_PROMISC_DIS, 0); } /* Program multicast filter. */ ti_setmulti(sc); /* * If this is a Tigon 1, we should tell the * firmware to use software packet filtering. */ if (sc->ti_hwrev == TI_HWREV_TIGON) { TI_DO_CMD(TI_CMD_FDR_FILTERING, TI_CMD_CODE_FILT_ENB, 0); } /* Init RX ring. */ if (ti_init_rx_ring_std(sc) != 0) { /* XXX */ device_printf(sc->ti_dev, "no memory for std Rx buffers.\n"); return; } /* Init jumbo RX ring. */ if (ifp->if_mtu > ETHERMTU + ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN) { if (ti_init_rx_ring_jumbo(sc) != 0) { /* XXX */ device_printf(sc->ti_dev, "no memory for jumbo Rx buffers.\n"); return; } } /* * If this is a Tigon 2, we can also configure the * mini ring. */ if (sc->ti_hwrev == TI_HWREV_TIGON_II) { if (ti_init_rx_ring_mini(sc) != 0) { /* XXX */ device_printf(sc->ti_dev, "no memory for mini Rx buffers.\n"); return; } } CSR_WRITE_4(sc, TI_GCR_RXRETURNCONS_IDX, 0); sc->ti_rx_saved_considx = 0; /* Init TX ring. */ ti_init_tx_ring(sc); /* Tell firmware we're alive. */ TI_DO_CMD(TI_CMD_HOST_STATE, TI_CMD_CODE_STACK_UP, 0); /* Enable host interrupts. */ CSR_WRITE_4(sc, TI_MB_HOSTINTR, 0); ifp->if_drv_flags |= IFF_DRV_RUNNING; ifp->if_drv_flags &= ~IFF_DRV_OACTIVE; callout_reset(&sc->ti_watchdog, hz, ti_watchdog, sc); /* * Make sure to set media properly. We have to do this * here since we have to issue commands in order to set * the link negotiation and we can't issue commands until * the firmware is running. */ ifm = &sc->ifmedia; tmp = ifm->ifm_media; ifm->ifm_media = ifm->ifm_cur->ifm_media; ti_ifmedia_upd_locked(sc); ifm->ifm_media = tmp; } /* * Set media options. */ static int ti_ifmedia_upd(struct ifnet *ifp) { struct ti_softc *sc; int error; sc = ifp->if_softc; TI_LOCK(sc); error = ti_ifmedia_upd_locked(sc); TI_UNLOCK(sc); return (error); } static int ti_ifmedia_upd_locked(struct ti_softc *sc) { struct ifmedia *ifm; struct ti_cmd_desc cmd; uint32_t flowctl; ifm = &sc->ifmedia; if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) return (EINVAL); flowctl = 0; switch (IFM_SUBTYPE(ifm->ifm_media)) { case IFM_AUTO: /* * Transmit flow control doesn't work on the Tigon 1. */ flowctl = TI_GLNK_RX_FLOWCTL_Y; /* * Transmit flow control can also cause problems on the * Tigon 2, apparently with both the copper and fiber * boards. The symptom is that the interface will just * hang. This was reproduced with Alteon 180 switches. */ #if 0 if (sc->ti_hwrev != TI_HWREV_TIGON) flowctl |= TI_GLNK_TX_FLOWCTL_Y; #endif CSR_WRITE_4(sc, TI_GCR_GLINK, TI_GLNK_PREF|TI_GLNK_1000MB| TI_GLNK_FULL_DUPLEX| flowctl | TI_GLNK_AUTONEGENB|TI_GLNK_ENB); flowctl = TI_LNK_RX_FLOWCTL_Y; #if 0 if (sc->ti_hwrev != TI_HWREV_TIGON) flowctl |= TI_LNK_TX_FLOWCTL_Y; #endif CSR_WRITE_4(sc, TI_GCR_LINK, TI_LNK_100MB|TI_LNK_10MB| TI_LNK_FULL_DUPLEX|TI_LNK_HALF_DUPLEX| flowctl | TI_LNK_AUTONEGENB|TI_LNK_ENB); TI_DO_CMD(TI_CMD_LINK_NEGOTIATION, TI_CMD_CODE_NEGOTIATE_BOTH, 0); break; case IFM_1000_SX: case IFM_1000_T: flowctl = TI_GLNK_RX_FLOWCTL_Y; #if 0 if (sc->ti_hwrev != TI_HWREV_TIGON) flowctl |= TI_GLNK_TX_FLOWCTL_Y; #endif CSR_WRITE_4(sc, TI_GCR_GLINK, TI_GLNK_PREF|TI_GLNK_1000MB| flowctl |TI_GLNK_ENB); CSR_WRITE_4(sc, TI_GCR_LINK, 0); if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX) { TI_SETBIT(sc, TI_GCR_GLINK, TI_GLNK_FULL_DUPLEX); } TI_DO_CMD(TI_CMD_LINK_NEGOTIATION, TI_CMD_CODE_NEGOTIATE_GIGABIT, 0); break; case IFM_100_FX: case IFM_10_FL: case IFM_100_TX: case IFM_10_T: flowctl = TI_LNK_RX_FLOWCTL_Y; #if 0 if (sc->ti_hwrev != TI_HWREV_TIGON) flowctl |= TI_LNK_TX_FLOWCTL_Y; #endif CSR_WRITE_4(sc, TI_GCR_GLINK, 0); CSR_WRITE_4(sc, TI_GCR_LINK, TI_LNK_ENB|TI_LNK_PREF|flowctl); if (IFM_SUBTYPE(ifm->ifm_media) == IFM_100_FX || IFM_SUBTYPE(ifm->ifm_media) == IFM_100_TX) { TI_SETBIT(sc, TI_GCR_LINK, TI_LNK_100MB); } else { TI_SETBIT(sc, TI_GCR_LINK, TI_LNK_10MB); } if ((ifm->ifm_media & IFM_GMASK) == IFM_FDX) { TI_SETBIT(sc, TI_GCR_LINK, TI_LNK_FULL_DUPLEX); } else { TI_SETBIT(sc, TI_GCR_LINK, TI_LNK_HALF_DUPLEX); } TI_DO_CMD(TI_CMD_LINK_NEGOTIATION, TI_CMD_CODE_NEGOTIATE_10_100, 0); break; } return (0); } /* * Report current media status. */ static void ti_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr) { struct ti_softc *sc; uint32_t media = 0; sc = ifp->if_softc; TI_LOCK(sc); ifmr->ifm_status = IFM_AVALID; ifmr->ifm_active = IFM_ETHER; if (sc->ti_linkstat == TI_EV_CODE_LINK_DOWN) { TI_UNLOCK(sc); return; } ifmr->ifm_status |= IFM_ACTIVE; if (sc->ti_linkstat == TI_EV_CODE_GIG_LINK_UP) { media = CSR_READ_4(sc, TI_GCR_GLINK_STAT); if (sc->ti_copper) ifmr->ifm_active |= IFM_1000_T; else ifmr->ifm_active |= IFM_1000_SX; if (media & TI_GLNK_FULL_DUPLEX) ifmr->ifm_active |= IFM_FDX; else ifmr->ifm_active |= IFM_HDX; } else if (sc->ti_linkstat == TI_EV_CODE_LINK_UP) { media = CSR_READ_4(sc, TI_GCR_LINK_STAT); if (sc->ti_copper) { if (media & TI_LNK_100MB) ifmr->ifm_active |= IFM_100_TX; if (media & TI_LNK_10MB) ifmr->ifm_active |= IFM_10_T; } else { if (media & TI_LNK_100MB) ifmr->ifm_active |= IFM_100_FX; if (media & TI_LNK_10MB) ifmr->ifm_active |= IFM_10_FL; } if (media & TI_LNK_FULL_DUPLEX) ifmr->ifm_active |= IFM_FDX; if (media & TI_LNK_HALF_DUPLEX) ifmr->ifm_active |= IFM_HDX; } TI_UNLOCK(sc); } static int ti_ioctl(struct ifnet *ifp, u_long command, caddr_t data) { struct ti_softc *sc = ifp->if_softc; struct ifreq *ifr = (struct ifreq *) data; struct ti_cmd_desc cmd; int mask, error = 0; switch (command) { case SIOCSIFMTU: TI_LOCK(sc); if (ifr->ifr_mtu < ETHERMIN || ifr->ifr_mtu > TI_JUMBO_MTU) error = EINVAL; else { ifp->if_mtu = ifr->ifr_mtu; if (ifp->if_drv_flags & IFF_DRV_RUNNING) { ifp->if_drv_flags &= ~IFF_DRV_RUNNING; ti_init_locked(sc); } } TI_UNLOCK(sc); break; case SIOCSIFFLAGS: TI_LOCK(sc); if (ifp->if_flags & IFF_UP) { /* * If only the state of the PROMISC flag changed, * then just use the 'set promisc mode' command * instead of reinitializing the entire NIC. Doing * a full re-init means reloading the firmware and * waiting for it to start up, which may take a * second or two. */ if (ifp->if_drv_flags & IFF_DRV_RUNNING && ifp->if_flags & IFF_PROMISC && !(sc->ti_if_flags & IFF_PROMISC)) { TI_DO_CMD(TI_CMD_SET_PROMISC_MODE, TI_CMD_CODE_PROMISC_ENB, 0); } else if (ifp->if_drv_flags & IFF_DRV_RUNNING && !(ifp->if_flags & IFF_PROMISC) && sc->ti_if_flags & IFF_PROMISC) { TI_DO_CMD(TI_CMD_SET_PROMISC_MODE, TI_CMD_CODE_PROMISC_DIS, 0); } else ti_init_locked(sc); } else { if (ifp->if_drv_flags & IFF_DRV_RUNNING) { ti_stop(sc); } } sc->ti_if_flags = ifp->if_flags; TI_UNLOCK(sc); break; case SIOCADDMULTI: case SIOCDELMULTI: TI_LOCK(sc); if (ifp->if_drv_flags & IFF_DRV_RUNNING) ti_setmulti(sc); TI_UNLOCK(sc); break; case SIOCSIFMEDIA: case SIOCGIFMEDIA: error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command); break; case SIOCSIFCAP: TI_LOCK(sc); mask = ifr->ifr_reqcap ^ ifp->if_capenable; if ((mask & IFCAP_TXCSUM) != 0 && (ifp->if_capabilities & IFCAP_TXCSUM) != 0) { ifp->if_capenable ^= IFCAP_TXCSUM; if ((ifp->if_capenable & IFCAP_TXCSUM) != 0) ifp->if_hwassist |= TI_CSUM_FEATURES; else ifp->if_hwassist &= ~TI_CSUM_FEATURES; } if ((mask & IFCAP_RXCSUM) != 0 && (ifp->if_capabilities & IFCAP_RXCSUM) != 0) ifp->if_capenable ^= IFCAP_RXCSUM; if ((mask & IFCAP_VLAN_HWTAGGING) != 0 && (ifp->if_capabilities & IFCAP_VLAN_HWTAGGING) != 0) ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING; if ((mask & IFCAP_VLAN_HWCSUM) != 0 && (ifp->if_capabilities & IFCAP_VLAN_HWCSUM) != 0) ifp->if_capenable ^= IFCAP_VLAN_HWCSUM; if ((mask & (IFCAP_TXCSUM | IFCAP_RXCSUM | IFCAP_VLAN_HWTAGGING)) != 0) { if (ifp->if_drv_flags & IFF_DRV_RUNNING) { ifp->if_drv_flags &= ~IFF_DRV_RUNNING; ti_init_locked(sc); } } TI_UNLOCK(sc); VLAN_CAPABILITIES(ifp); break; default: error = ether_ioctl(ifp, command, data); break; } return (error); } static int ti_open(struct cdev *dev, int flags, int fmt, struct thread *td) { struct ti_softc *sc; sc = dev->si_drv1; if (sc == NULL) return (ENODEV); TI_LOCK(sc); sc->ti_flags |= TI_FLAG_DEBUGING; TI_UNLOCK(sc); return (0); } static int ti_close(struct cdev *dev, int flag, int fmt, struct thread *td) { struct ti_softc *sc; sc = dev->si_drv1; if (sc == NULL) return (ENODEV); TI_LOCK(sc); sc->ti_flags &= ~TI_FLAG_DEBUGING; TI_UNLOCK(sc); return (0); } /* * This ioctl routine goes along with the Tigon character device. */ static int ti_ioctl2(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td) { struct ti_softc *sc; int error; sc = dev->si_drv1; if (sc == NULL) return (ENODEV); error = 0; switch (cmd) { case TIIOCGETSTATS: { struct ti_stats *outstats; outstats = (struct ti_stats *)addr; TI_LOCK(sc); bus_dmamap_sync(sc->ti_cdata.ti_gib_tag, sc->ti_cdata.ti_gib_map, BUS_DMASYNC_POSTREAD); bcopy(&sc->ti_rdata.ti_info->ti_stats, outstats, sizeof(struct ti_stats)); bus_dmamap_sync(sc->ti_cdata.ti_gib_tag, sc->ti_cdata.ti_gib_map, BUS_DMASYNC_PREREAD); TI_UNLOCK(sc); break; } case TIIOCGETPARAMS: { struct ti_params *params; params = (struct ti_params *)addr; TI_LOCK(sc); params->ti_stat_ticks = sc->ti_stat_ticks; params->ti_rx_coal_ticks = sc->ti_rx_coal_ticks; params->ti_tx_coal_ticks = sc->ti_tx_coal_ticks; params->ti_rx_max_coal_bds = sc->ti_rx_max_coal_bds; params->ti_tx_max_coal_bds = sc->ti_tx_max_coal_bds; params->ti_tx_buf_ratio = sc->ti_tx_buf_ratio; params->param_mask = TI_PARAM_ALL; TI_UNLOCK(sc); break; } case TIIOCSETPARAMS: { struct ti_params *params; params = (struct ti_params *)addr; TI_LOCK(sc); if (params->param_mask & TI_PARAM_STAT_TICKS) { sc->ti_stat_ticks = params->ti_stat_ticks; CSR_WRITE_4(sc, TI_GCR_STAT_TICKS, sc->ti_stat_ticks); } if (params->param_mask & TI_PARAM_RX_COAL_TICKS) { sc->ti_rx_coal_ticks = params->ti_rx_coal_ticks; CSR_WRITE_4(sc, TI_GCR_RX_COAL_TICKS, sc->ti_rx_coal_ticks); } if (params->param_mask & TI_PARAM_TX_COAL_TICKS) { sc->ti_tx_coal_ticks = params->ti_tx_coal_ticks; CSR_WRITE_4(sc, TI_GCR_TX_COAL_TICKS, sc->ti_tx_coal_ticks); } if (params->param_mask & TI_PARAM_RX_COAL_BDS) { sc->ti_rx_max_coal_bds = params->ti_rx_max_coal_bds; CSR_WRITE_4(sc, TI_GCR_RX_MAX_COAL_BD, sc->ti_rx_max_coal_bds); } if (params->param_mask & TI_PARAM_TX_COAL_BDS) { sc->ti_tx_max_coal_bds = params->ti_tx_max_coal_bds; CSR_WRITE_4(sc, TI_GCR_TX_MAX_COAL_BD, sc->ti_tx_max_coal_bds); } if (params->param_mask & TI_PARAM_TX_BUF_RATIO) { sc->ti_tx_buf_ratio = params->ti_tx_buf_ratio; CSR_WRITE_4(sc, TI_GCR_TX_BUFFER_RATIO, sc->ti_tx_buf_ratio); } TI_UNLOCK(sc); break; } case TIIOCSETTRACE: { ti_trace_type trace_type; trace_type = *(ti_trace_type *)addr; /* * Set tracing to whatever the user asked for. Setting * this register to 0 should have the effect of disabling * tracing. */ TI_LOCK(sc); CSR_WRITE_4(sc, TI_GCR_NIC_TRACING, trace_type); TI_UNLOCK(sc); break; } case TIIOCGETTRACE: { struct ti_trace_buf *trace_buf; uint32_t trace_start, cur_trace_ptr, trace_len; trace_buf = (struct ti_trace_buf *)addr; TI_LOCK(sc); trace_start = CSR_READ_4(sc, TI_GCR_NICTRACE_START); cur_trace_ptr = CSR_READ_4(sc, TI_GCR_NICTRACE_PTR); trace_len = CSR_READ_4(sc, TI_GCR_NICTRACE_LEN); #if 0 if_printf(sc->ti_ifp, "trace_start = %#x, cur_trace_ptr = %#x, " "trace_len = %d\n", trace_start, cur_trace_ptr, trace_len); if_printf(sc->ti_ifp, "trace_buf->buf_len = %d\n", trace_buf->buf_len); #endif error = ti_copy_mem(sc, trace_start, min(trace_len, trace_buf->buf_len), (caddr_t)trace_buf->buf, 1, 1); if (error == 0) { trace_buf->fill_len = min(trace_len, trace_buf->buf_len); if (cur_trace_ptr < trace_start) trace_buf->cur_trace_ptr = trace_start - cur_trace_ptr; else trace_buf->cur_trace_ptr = cur_trace_ptr - trace_start; } else trace_buf->fill_len = 0; TI_UNLOCK(sc); break; } /* * For debugging, five ioctls are needed: * ALT_ATTACH * ALT_READ_TG_REG * ALT_WRITE_TG_REG * ALT_READ_TG_MEM * ALT_WRITE_TG_MEM */ case ALT_ATTACH: /* * From what I can tell, Alteon's Solaris Tigon driver * only has one character device, so you have to attach * to the Tigon board you're interested in. This seems * like a not-so-good way to do things, since unless you * subsequently specify the unit number of the device * you're interested in every ioctl, you'll only be * able to debug one board at a time. */ break; case ALT_READ_TG_MEM: case ALT_WRITE_TG_MEM: { struct tg_mem *mem_param; uint32_t sram_end, scratch_end; mem_param = (struct tg_mem *)addr; if (sc->ti_hwrev == TI_HWREV_TIGON) { sram_end = TI_END_SRAM_I; scratch_end = TI_END_SCRATCH_I; } else { sram_end = TI_END_SRAM_II; scratch_end = TI_END_SCRATCH_II; } /* * For now, we'll only handle accessing regular SRAM, * nothing else. */ TI_LOCK(sc); if (mem_param->tgAddr >= TI_BEG_SRAM && mem_param->tgAddr + mem_param->len <= sram_end) { /* * In this instance, we always copy to/from user * space, so the user space argument is set to 1. */ error = ti_copy_mem(sc, mem_param->tgAddr, mem_param->len, mem_param->userAddr, 1, cmd == ALT_READ_TG_MEM ? 1 : 0); } else if (mem_param->tgAddr >= TI_BEG_SCRATCH && mem_param->tgAddr <= scratch_end) { error = ti_copy_scratch(sc, mem_param->tgAddr, mem_param->len, mem_param->userAddr, 1, cmd == ALT_READ_TG_MEM ? 1 : 0, TI_PROCESSOR_A); } else if (mem_param->tgAddr >= TI_BEG_SCRATCH_B_DEBUG && mem_param->tgAddr <= TI_BEG_SCRATCH_B_DEBUG) { if (sc->ti_hwrev == TI_HWREV_TIGON) { if_printf(sc->ti_ifp, "invalid memory range for Tigon I\n"); error = EINVAL; break; } error = ti_copy_scratch(sc, mem_param->tgAddr - TI_SCRATCH_DEBUG_OFF, mem_param->len, mem_param->userAddr, 1, cmd == ALT_READ_TG_MEM ? 1 : 0, TI_PROCESSOR_B); } else { if_printf(sc->ti_ifp, "memory address %#x len %d is " "out of supported range\n", mem_param->tgAddr, mem_param->len); error = EINVAL; } TI_UNLOCK(sc); break; } case ALT_READ_TG_REG: case ALT_WRITE_TG_REG: { struct tg_reg *regs; uint32_t tmpval; regs = (struct tg_reg *)addr; /* * Make sure the address in question isn't out of range. */ if (regs->addr > TI_REG_MAX) { error = EINVAL; break; } TI_LOCK(sc); if (cmd == ALT_READ_TG_REG) { bus_space_read_region_4(sc->ti_btag, sc->ti_bhandle, regs->addr, &tmpval, 1); regs->data = ntohl(tmpval); #if 0 if ((regs->addr == TI_CPU_STATE) || (regs->addr == TI_CPU_CTL_B)) { if_printf(sc->ti_ifp, "register %#x = %#x\n", regs->addr, tmpval); } #endif } else { tmpval = htonl(regs->data); bus_space_write_region_4(sc->ti_btag, sc->ti_bhandle, regs->addr, &tmpval, 1); } TI_UNLOCK(sc); break; } default: error = ENOTTY; break; } return (error); } static void ti_watchdog(void *arg) { struct ti_softc *sc; struct ifnet *ifp; sc = arg; TI_LOCK_ASSERT(sc); callout_reset(&sc->ti_watchdog, hz, ti_watchdog, sc); if (sc->ti_timer == 0 || --sc->ti_timer > 0) return; /* * When we're debugging, the chip is often stopped for long periods * of time, and that would normally cause the watchdog timer to fire. * Since that impedes debugging, we don't want to do that. */ if (sc->ti_flags & TI_FLAG_DEBUGING) return; ifp = sc->ti_ifp; if_printf(ifp, "watchdog timeout -- resetting\n"); ifp->if_drv_flags &= ~IFF_DRV_RUNNING; ti_init_locked(sc); if_inc_counter(ifp, IFCOUNTER_OERRORS, 1); } /* * Stop the adapter and free any mbufs allocated to the * RX and TX lists. */ static void ti_stop(struct ti_softc *sc) { struct ifnet *ifp; struct ti_cmd_desc cmd; TI_LOCK_ASSERT(sc); ifp = sc->ti_ifp; /* Disable host interrupts. */ CSR_WRITE_4(sc, TI_MB_HOSTINTR, 1); /* * Tell firmware we're shutting down. */ TI_DO_CMD(TI_CMD_HOST_STATE, TI_CMD_CODE_STACK_DOWN, 0); /* Halt and reinitialize. */ if (ti_chipinit(sc) == 0) { ti_mem_zero(sc, 0x2000, 0x100000 - 0x2000); /* XXX ignore init errors. */ ti_chipinit(sc); } /* Free the RX lists. */ ti_free_rx_ring_std(sc); /* Free jumbo RX list. */ ti_free_rx_ring_jumbo(sc); /* Free mini RX list. */ ti_free_rx_ring_mini(sc); /* Free TX buffers. */ ti_free_tx_ring(sc); sc->ti_ev_prodidx.ti_idx = 0; sc->ti_return_prodidx.ti_idx = 0; sc->ti_tx_considx.ti_idx = 0; sc->ti_tx_saved_considx = TI_TXCONS_UNSET; ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE); callout_stop(&sc->ti_watchdog); } /* * Stop all chip I/O so that the kernel's probe routines don't * get confused by errant DMAs when rebooting. */ static int ti_shutdown(device_t dev) { struct ti_softc *sc; sc = device_get_softc(dev); TI_LOCK(sc); ti_chipinit(sc); TI_UNLOCK(sc); return (0); } static void ti_sysctl_node(struct ti_softc *sc) { struct sysctl_ctx_list *ctx; struct sysctl_oid_list *child; char tname[32]; ctx = device_get_sysctl_ctx(sc->ti_dev); child = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->ti_dev)); /* Use DAC */ sc->ti_dac = 1; snprintf(tname, sizeof(tname), "dev.ti.%d.dac", device_get_unit(sc->ti_dev)); TUNABLE_INT_FETCH(tname, &sc->ti_dac); SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "rx_coal_ticks", CTLFLAG_RW, &sc->ti_rx_coal_ticks, 0, "Receive coalcesced ticks"); SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "rx_max_coal_bds", CTLFLAG_RW, &sc->ti_rx_max_coal_bds, 0, "Receive max coalcesced BDs"); SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "tx_coal_ticks", CTLFLAG_RW, &sc->ti_tx_coal_ticks, 0, "Send coalcesced ticks"); SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "tx_max_coal_bds", CTLFLAG_RW, &sc->ti_tx_max_coal_bds, 0, "Send max coalcesced BDs"); SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "tx_buf_ratio", CTLFLAG_RW, &sc->ti_tx_buf_ratio, 0, "Ratio of NIC memory devoted to TX buffer"); SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "stat_ticks", CTLFLAG_RW, &sc->ti_stat_ticks, 0, "Number of clock ticks for statistics update interval"); /* Pull in device tunables. */ sc->ti_rx_coal_ticks = 170; resource_int_value(device_get_name(sc->ti_dev), device_get_unit(sc->ti_dev), "rx_coal_ticks", &sc->ti_rx_coal_ticks); sc->ti_rx_max_coal_bds = 64; resource_int_value(device_get_name(sc->ti_dev), device_get_unit(sc->ti_dev), "rx_max_coal_bds", &sc->ti_rx_max_coal_bds); sc->ti_tx_coal_ticks = TI_TICKS_PER_SEC / 500; resource_int_value(device_get_name(sc->ti_dev), device_get_unit(sc->ti_dev), "tx_coal_ticks", &sc->ti_tx_coal_ticks); sc->ti_tx_max_coal_bds = 32; resource_int_value(device_get_name(sc->ti_dev), device_get_unit(sc->ti_dev), "tx_max_coal_bds", &sc->ti_tx_max_coal_bds); sc->ti_tx_buf_ratio = 21; resource_int_value(device_get_name(sc->ti_dev), device_get_unit(sc->ti_dev), "tx_buf_ratio", &sc->ti_tx_buf_ratio); sc->ti_stat_ticks = 2 * TI_TICKS_PER_SEC; resource_int_value(device_get_name(sc->ti_dev), device_get_unit(sc->ti_dev), "stat_ticks", &sc->ti_stat_ticks); }
27.515032
80
0.695099
032ac11690d69fda117e23f999f4586e7cdb161d
1,754
h
C
src/queues/WorkQueue.h
amecky/space
b0b50e4578d0de64ca2b09b32768d0733fa7b4f4
[ "Apache-2.0" ]
null
null
null
src/queues/WorkQueue.h
amecky/space
b0b50e4578d0de64ca2b09b32768d0733fa7b4f4
[ "Apache-2.0" ]
null
null
null
src/queues/WorkQueue.h
amecky/space
b0b50e4578d0de64ca2b09b32768d0733fa7b4f4
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vector> #include "..\Common.h" #include "..\registries\PriceRegistry.h" class Serializer; // ------------------------------------------------------ // Work item // ------------------------------------------------------ struct WorkItem { int tile_x; int tile_y; WorkType work_type; int timer; int duration; int price_index; int building_id; int level; bool reschedule; bool done; }; // ------------------------------------------------------ // Event // ------------------------------------------------------ struct Event { WorkType work_type; int tile_x; int tile_y; int building_id; int level; }; // ------------------------------------------------------ // event buffer // ------------------------------------------------------ struct EventBuffer { Event events[256]; int size; void clear() { size = 0; } void add(const Event& e) { events[size++] = e; } const Event& get(int index) const { return events[index]; } }; // ------------------------------------------------------ // Work queue // ------------------------------------------------------ class WorkQueue { typedef std::vector<WorkItem> Queue; public: WorkQueue(PriceRegistry* price_registry); ~WorkQueue(void); void tick(int timeUnits); void createWork(WorkType work_type,int x,int y,int building_id, int level,int duration); bool hasEvents() { return _buffer.size > 0; } const Event& getEvent(int index) const { return _buffer.get(index); } const int event_size() const { return _buffer.size; } void remove(WorkType work_type, int x,int y); void show() const; void save(Serializer& writer); void load(Serializer& reader); private: PriceRegistry* _price_registry; Queue _queue; EventBuffer _buffer; };
19.488889
89
0.517104
03df7b1e77bfef861fee0171c4d205bada39a414
32,692
h
C
linux-3.0.1/arch/tile/include/asm/opcode-tile_32.h
tonghua209/samsun6410_linux_3_0_0_1_for_aws
31aa0dc27c4aab51a92309a74fd84ca65e8c6a58
[ "Apache-2.0" ]
4
2016-07-01T04:50:02.000Z
2021-11-14T21:29:42.000Z
linux-3.0/arch/tile/include/asm/opcode-tile_32.h
spartan263/vizio_oss
74270002d874391148119b48882db6816e7deedc
[ "Linux-OpenIB" ]
null
null
null
linux-3.0/arch/tile/include/asm/opcode-tile_32.h
spartan263/vizio_oss
74270002d874391148119b48882db6816e7deedc
[ "Linux-OpenIB" ]
1
2020-04-03T14:00:39.000Z
2020-04-03T14:00:39.000Z
/* tile.h -- Header file for TILE opcode table Copyright (C) 2005 Free Software Foundation, Inc. Contributed by Tilera Corp. */ #ifndef opcode_tile_h #define opcode_tile_h typedef unsigned long long tile_bundle_bits; enum { TILE_MAX_OPERANDS = 5 /* mm */ }; typedef enum { TILE_OPC_BPT, TILE_OPC_INFO, TILE_OPC_INFOL, TILE_OPC_J, TILE_OPC_JAL, TILE_OPC_MOVE, TILE_OPC_MOVE_SN, TILE_OPC_MOVEI, TILE_OPC_MOVEI_SN, TILE_OPC_MOVELI, TILE_OPC_MOVELI_SN, TILE_OPC_MOVELIS, TILE_OPC_PREFETCH, TILE_OPC_RAISE, TILE_OPC_ADD, TILE_OPC_ADD_SN, TILE_OPC_ADDB, TILE_OPC_ADDB_SN, TILE_OPC_ADDBS_U, TILE_OPC_ADDBS_U_SN, TILE_OPC_ADDH, TILE_OPC_ADDH_SN, TILE_OPC_ADDHS, TILE_OPC_ADDHS_SN, TILE_OPC_ADDI, TILE_OPC_ADDI_SN, TILE_OPC_ADDIB, TILE_OPC_ADDIB_SN, TILE_OPC_ADDIH, TILE_OPC_ADDIH_SN, TILE_OPC_ADDLI, TILE_OPC_ADDLI_SN, TILE_OPC_ADDLIS, TILE_OPC_ADDS, TILE_OPC_ADDS_SN, TILE_OPC_ADIFFB_U, TILE_OPC_ADIFFB_U_SN, TILE_OPC_ADIFFH, TILE_OPC_ADIFFH_SN, TILE_OPC_AND, TILE_OPC_AND_SN, TILE_OPC_ANDI, TILE_OPC_ANDI_SN, TILE_OPC_AULI, TILE_OPC_AVGB_U, TILE_OPC_AVGB_U_SN, TILE_OPC_AVGH, TILE_OPC_AVGH_SN, TILE_OPC_BBNS, TILE_OPC_BBNS_SN, TILE_OPC_BBNST, TILE_OPC_BBNST_SN, TILE_OPC_BBS, TILE_OPC_BBS_SN, TILE_OPC_BBST, TILE_OPC_BBST_SN, TILE_OPC_BGEZ, TILE_OPC_BGEZ_SN, TILE_OPC_BGEZT, TILE_OPC_BGEZT_SN, TILE_OPC_BGZ, TILE_OPC_BGZ_SN, TILE_OPC_BGZT, TILE_OPC_BGZT_SN, TILE_OPC_BITX, TILE_OPC_BITX_SN, TILE_OPC_BLEZ, TILE_OPC_BLEZ_SN, TILE_OPC_BLEZT, TILE_OPC_BLEZT_SN, TILE_OPC_BLZ, TILE_OPC_BLZ_SN, TILE_OPC_BLZT, TILE_OPC_BLZT_SN, TILE_OPC_BNZ, TILE_OPC_BNZ_SN, TILE_OPC_BNZT, TILE_OPC_BNZT_SN, TILE_OPC_BYTEX, TILE_OPC_BYTEX_SN, TILE_OPC_BZ, TILE_OPC_BZ_SN, TILE_OPC_BZT, TILE_OPC_BZT_SN, TILE_OPC_CLZ, TILE_OPC_CLZ_SN, TILE_OPC_CRC32_32, TILE_OPC_CRC32_32_SN, TILE_OPC_CRC32_8, TILE_OPC_CRC32_8_SN, TILE_OPC_CTZ, TILE_OPC_CTZ_SN, TILE_OPC_DRAIN, TILE_OPC_DTLBPR, TILE_OPC_DWORD_ALIGN, TILE_OPC_DWORD_ALIGN_SN, TILE_OPC_FINV, TILE_OPC_FLUSH, TILE_OPC_FNOP, TILE_OPC_ICOH, TILE_OPC_ILL, TILE_OPC_INTHB, TILE_OPC_INTHB_SN, TILE_OPC_INTHH, TILE_OPC_INTHH_SN, TILE_OPC_INTLB, TILE_OPC_INTLB_SN, TILE_OPC_INTLH, TILE_OPC_INTLH_SN, TILE_OPC_INV, TILE_OPC_IRET, TILE_OPC_JALB, TILE_OPC_JALF, TILE_OPC_JALR, TILE_OPC_JALRP, TILE_OPC_JB, TILE_OPC_JF, TILE_OPC_JR, TILE_OPC_JRP, TILE_OPC_LB, TILE_OPC_LB_SN, TILE_OPC_LB_U, TILE_OPC_LB_U_SN, TILE_OPC_LBADD, TILE_OPC_LBADD_SN, TILE_OPC_LBADD_U, TILE_OPC_LBADD_U_SN, TILE_OPC_LH, TILE_OPC_LH_SN, TILE_OPC_LH_U, TILE_OPC_LH_U_SN, TILE_OPC_LHADD, TILE_OPC_LHADD_SN, TILE_OPC_LHADD_U, TILE_OPC_LHADD_U_SN, TILE_OPC_LNK, TILE_OPC_LNK_SN, TILE_OPC_LW, TILE_OPC_LW_SN, TILE_OPC_LW_NA, TILE_OPC_LW_NA_SN, TILE_OPC_LWADD, TILE_OPC_LWADD_SN, TILE_OPC_LWADD_NA, TILE_OPC_LWADD_NA_SN, TILE_OPC_MAXB_U, TILE_OPC_MAXB_U_SN, TILE_OPC_MAXH, TILE_OPC_MAXH_SN, TILE_OPC_MAXIB_U, TILE_OPC_MAXIB_U_SN, TILE_OPC_MAXIH, TILE_OPC_MAXIH_SN, TILE_OPC_MF, TILE_OPC_MFSPR, TILE_OPC_MINB_U, TILE_OPC_MINB_U_SN, TILE_OPC_MINH, TILE_OPC_MINH_SN, TILE_OPC_MINIB_U, TILE_OPC_MINIB_U_SN, TILE_OPC_MINIH, TILE_OPC_MINIH_SN, TILE_OPC_MM, TILE_OPC_MNZ, TILE_OPC_MNZ_SN, TILE_OPC_MNZB, TILE_OPC_MNZB_SN, TILE_OPC_MNZH, TILE_OPC_MNZH_SN, TILE_OPC_MTSPR, TILE_OPC_MULHH_SS, TILE_OPC_MULHH_SS_SN, TILE_OPC_MULHH_SU, TILE_OPC_MULHH_SU_SN, TILE_OPC_MULHH_UU, TILE_OPC_MULHH_UU_SN, TILE_OPC_MULHHA_SS, TILE_OPC_MULHHA_SS_SN, TILE_OPC_MULHHA_SU, TILE_OPC_MULHHA_SU_SN, TILE_OPC_MULHHA_UU, TILE_OPC_MULHHA_UU_SN, TILE_OPC_MULHHSA_UU, TILE_OPC_MULHHSA_UU_SN, TILE_OPC_MULHL_SS, TILE_OPC_MULHL_SS_SN, TILE_OPC_MULHL_SU, TILE_OPC_MULHL_SU_SN, TILE_OPC_MULHL_US, TILE_OPC_MULHL_US_SN, TILE_OPC_MULHL_UU, TILE_OPC_MULHL_UU_SN, TILE_OPC_MULHLA_SS, TILE_OPC_MULHLA_SS_SN, TILE_OPC_MULHLA_SU, TILE_OPC_MULHLA_SU_SN, TILE_OPC_MULHLA_US, TILE_OPC_MULHLA_US_SN, TILE_OPC_MULHLA_UU, TILE_OPC_MULHLA_UU_SN, TILE_OPC_MULHLSA_UU, TILE_OPC_MULHLSA_UU_SN, TILE_OPC_MULLL_SS, TILE_OPC_MULLL_SS_SN, TILE_OPC_MULLL_SU, TILE_OPC_MULLL_SU_SN, TILE_OPC_MULLL_UU, TILE_OPC_MULLL_UU_SN, TILE_OPC_MULLLA_SS, TILE_OPC_MULLLA_SS_SN, TILE_OPC_MULLLA_SU, TILE_OPC_MULLLA_SU_SN, TILE_OPC_MULLLA_UU, TILE_OPC_MULLLA_UU_SN, TILE_OPC_MULLLSA_UU, TILE_OPC_MULLLSA_UU_SN, TILE_OPC_MVNZ, TILE_OPC_MVNZ_SN, TILE_OPC_MVZ, TILE_OPC_MVZ_SN, TILE_OPC_MZ, TILE_OPC_MZ_SN, TILE_OPC_MZB, TILE_OPC_MZB_SN, TILE_OPC_MZH, TILE_OPC_MZH_SN, TILE_OPC_NAP, TILE_OPC_NOP, TILE_OPC_NOR, TILE_OPC_NOR_SN, TILE_OPC_OR, TILE_OPC_OR_SN, TILE_OPC_ORI, TILE_OPC_ORI_SN, TILE_OPC_PACKBS_U, TILE_OPC_PACKBS_U_SN, TILE_OPC_PACKHB, TILE_OPC_PACKHB_SN, TILE_OPC_PACKHS, TILE_OPC_PACKHS_SN, TILE_OPC_PACKLB, TILE_OPC_PACKLB_SN, TILE_OPC_PCNT, TILE_OPC_PCNT_SN, TILE_OPC_RL, TILE_OPC_RL_SN, TILE_OPC_RLI, TILE_OPC_RLI_SN, TILE_OPC_S1A, TILE_OPC_S1A_SN, TILE_OPC_S2A, TILE_OPC_S2A_SN, TILE_OPC_S3A, TILE_OPC_S3A_SN, TILE_OPC_SADAB_U, TILE_OPC_SADAB_U_SN, TILE_OPC_SADAH, TILE_OPC_SADAH_SN, TILE_OPC_SADAH_U, TILE_OPC_SADAH_U_SN, TILE_OPC_SADB_U, TILE_OPC_SADB_U_SN, TILE_OPC_SADH, TILE_OPC_SADH_SN, TILE_OPC_SADH_U, TILE_OPC_SADH_U_SN, TILE_OPC_SB, TILE_OPC_SBADD, TILE_OPC_SEQ, TILE_OPC_SEQ_SN, TILE_OPC_SEQB, TILE_OPC_SEQB_SN, TILE_OPC_SEQH, TILE_OPC_SEQH_SN, TILE_OPC_SEQI, TILE_OPC_SEQI_SN, TILE_OPC_SEQIB, TILE_OPC_SEQIB_SN, TILE_OPC_SEQIH, TILE_OPC_SEQIH_SN, TILE_OPC_SH, TILE_OPC_SHADD, TILE_OPC_SHL, TILE_OPC_SHL_SN, TILE_OPC_SHLB, TILE_OPC_SHLB_SN, TILE_OPC_SHLH, TILE_OPC_SHLH_SN, TILE_OPC_SHLI, TILE_OPC_SHLI_SN, TILE_OPC_SHLIB, TILE_OPC_SHLIB_SN, TILE_OPC_SHLIH, TILE_OPC_SHLIH_SN, TILE_OPC_SHR, TILE_OPC_SHR_SN, TILE_OPC_SHRB, TILE_OPC_SHRB_SN, TILE_OPC_SHRH, TILE_OPC_SHRH_SN, TILE_OPC_SHRI, TILE_OPC_SHRI_SN, TILE_OPC_SHRIB, TILE_OPC_SHRIB_SN, TILE_OPC_SHRIH, TILE_OPC_SHRIH_SN, TILE_OPC_SLT, TILE_OPC_SLT_SN, TILE_OPC_SLT_U, TILE_OPC_SLT_U_SN, TILE_OPC_SLTB, TILE_OPC_SLTB_SN, TILE_OPC_SLTB_U, TILE_OPC_SLTB_U_SN, TILE_OPC_SLTE, TILE_OPC_SLTE_SN, TILE_OPC_SLTE_U, TILE_OPC_SLTE_U_SN, TILE_OPC_SLTEB, TILE_OPC_SLTEB_SN, TILE_OPC_SLTEB_U, TILE_OPC_SLTEB_U_SN, TILE_OPC_SLTEH, TILE_OPC_SLTEH_SN, TILE_OPC_SLTEH_U, TILE_OPC_SLTEH_U_SN, TILE_OPC_SLTH, TILE_OPC_SLTH_SN, TILE_OPC_SLTH_U, TILE_OPC_SLTH_U_SN, TILE_OPC_SLTI, TILE_OPC_SLTI_SN, TILE_OPC_SLTI_U, TILE_OPC_SLTI_U_SN, TILE_OPC_SLTIB, TILE_OPC_SLTIB_SN, TILE_OPC_SLTIB_U, TILE_OPC_SLTIB_U_SN, TILE_OPC_SLTIH, TILE_OPC_SLTIH_SN, TILE_OPC_SLTIH_U, TILE_OPC_SLTIH_U_SN, TILE_OPC_SNE, TILE_OPC_SNE_SN, TILE_OPC_SNEB, TILE_OPC_SNEB_SN, TILE_OPC_SNEH, TILE_OPC_SNEH_SN, TILE_OPC_SRA, TILE_OPC_SRA_SN, TILE_OPC_SRAB, TILE_OPC_SRAB_SN, TILE_OPC_SRAH, TILE_OPC_SRAH_SN, TILE_OPC_SRAI, TILE_OPC_SRAI_SN, TILE_OPC_SRAIB, TILE_OPC_SRAIB_SN, TILE_OPC_SRAIH, TILE_OPC_SRAIH_SN, TILE_OPC_SUB, TILE_OPC_SUB_SN, TILE_OPC_SUBB, TILE_OPC_SUBB_SN, TILE_OPC_SUBBS_U, TILE_OPC_SUBBS_U_SN, TILE_OPC_SUBH, TILE_OPC_SUBH_SN, TILE_OPC_SUBHS, TILE_OPC_SUBHS_SN, TILE_OPC_SUBS, TILE_OPC_SUBS_SN, TILE_OPC_SW, TILE_OPC_SWADD, TILE_OPC_SWINT0, TILE_OPC_SWINT1, TILE_OPC_SWINT2, TILE_OPC_SWINT3, TILE_OPC_TBLIDXB0, TILE_OPC_TBLIDXB0_SN, TILE_OPC_TBLIDXB1, TILE_OPC_TBLIDXB1_SN, TILE_OPC_TBLIDXB2, TILE_OPC_TBLIDXB2_SN, TILE_OPC_TBLIDXB3, TILE_OPC_TBLIDXB3_SN, TILE_OPC_TNS, TILE_OPC_TNS_SN, TILE_OPC_WH64, TILE_OPC_XOR, TILE_OPC_XOR_SN, TILE_OPC_XORI, TILE_OPC_XORI_SN, TILE_OPC_NONE } tile_mnemonic; /* 64-bit pattern for a { bpt ; nop } bundle. */ #define TILE_BPT_BUNDLE 0x400b3cae70166000ULL #define TILE_ELF_MACHINE_CODE EM_TILEPRO #define TILE_ELF_NAME "elf32-tilepro" static __inline unsigned int get_BrOff_SN(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 0)) & 0x3ff); } static __inline unsigned int get_BrOff_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 43)) & 0x00007fff) | (((unsigned int)(n >> 20)) & 0x00018000); } static __inline unsigned int get_BrType_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 31)) & 0xf); } static __inline unsigned int get_Dest_Imm8_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 31)) & 0x0000003f) | (((unsigned int)(n >> 43)) & 0x000000c0); } static __inline unsigned int get_Dest_SN(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 2)) & 0x3); } static __inline unsigned int get_Dest_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 0)) & 0x3f); } static __inline unsigned int get_Dest_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 31)) & 0x3f); } static __inline unsigned int get_Dest_Y0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 0)) & 0x3f); } static __inline unsigned int get_Dest_Y1(tile_bundle_bits n) { return (((unsigned int)(n >> 31)) & 0x3f); } static __inline unsigned int get_Imm16_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 12)) & 0xffff); } static __inline unsigned int get_Imm16_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 43)) & 0xffff); } static __inline unsigned int get_Imm8_SN(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 0)) & 0xff); } static __inline unsigned int get_Imm8_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 12)) & 0xff); } static __inline unsigned int get_Imm8_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 43)) & 0xff); } static __inline unsigned int get_Imm8_Y0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 12)) & 0xff); } static __inline unsigned int get_Imm8_Y1(tile_bundle_bits n) { return (((unsigned int)(n >> 43)) & 0xff); } static __inline unsigned int get_ImmOpcodeExtension_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 20)) & 0x7f); } static __inline unsigned int get_ImmOpcodeExtension_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 51)) & 0x7f); } static __inline unsigned int get_ImmRROpcodeExtension_SN(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 8)) & 0x3); } static __inline unsigned int get_JOffLong_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 43)) & 0x00007fff) | (((unsigned int)(n >> 20)) & 0x00018000) | (((unsigned int)(n >> 14)) & 0x001e0000) | (((unsigned int)(n >> 16)) & 0x07e00000) | (((unsigned int)(n >> 31)) & 0x18000000); } static __inline unsigned int get_JOff_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 43)) & 0x00007fff) | (((unsigned int)(n >> 20)) & 0x00018000) | (((unsigned int)(n >> 14)) & 0x001e0000) | (((unsigned int)(n >> 16)) & 0x07e00000) | (((unsigned int)(n >> 31)) & 0x08000000); } static __inline unsigned int get_MF_Imm15_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 37)) & 0x00003fff) | (((unsigned int)(n >> 44)) & 0x00004000); } static __inline unsigned int get_MMEnd_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 18)) & 0x1f); } static __inline unsigned int get_MMEnd_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 49)) & 0x1f); } static __inline unsigned int get_MMStart_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 23)) & 0x1f); } static __inline unsigned int get_MMStart_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 54)) & 0x1f); } static __inline unsigned int get_MT_Imm15_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 31)) & 0x0000003f) | (((unsigned int)(n >> 37)) & 0x00003fc0) | (((unsigned int)(n >> 44)) & 0x00004000); } static __inline unsigned int get_Mode(tile_bundle_bits n) { return (((unsigned int)(n >> 63)) & 0x1); } static __inline unsigned int get_NoRegOpcodeExtension_SN(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 0)) & 0xf); } static __inline unsigned int get_Opcode_SN(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 10)) & 0x3f); } static __inline unsigned int get_Opcode_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 28)) & 0x7); } static __inline unsigned int get_Opcode_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 59)) & 0xf); } static __inline unsigned int get_Opcode_Y0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 27)) & 0xf); } static __inline unsigned int get_Opcode_Y1(tile_bundle_bits n) { return (((unsigned int)(n >> 59)) & 0xf); } static __inline unsigned int get_Opcode_Y2(tile_bundle_bits n) { return (((unsigned int)(n >> 56)) & 0x7); } static __inline unsigned int get_RROpcodeExtension_SN(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 4)) & 0xf); } static __inline unsigned int get_RRROpcodeExtension_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 18)) & 0x1ff); } static __inline unsigned int get_RRROpcodeExtension_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 49)) & 0x1ff); } static __inline unsigned int get_RRROpcodeExtension_Y0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 18)) & 0x3); } static __inline unsigned int get_RRROpcodeExtension_Y1(tile_bundle_bits n) { return (((unsigned int)(n >> 49)) & 0x3); } static __inline unsigned int get_RouteOpcodeExtension_SN(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 0)) & 0x3ff); } static __inline unsigned int get_S_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 27)) & 0x1); } static __inline unsigned int get_S_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 58)) & 0x1); } static __inline unsigned int get_ShAmt_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 12)) & 0x1f); } static __inline unsigned int get_ShAmt_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 43)) & 0x1f); } static __inline unsigned int get_ShAmt_Y0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 12)) & 0x1f); } static __inline unsigned int get_ShAmt_Y1(tile_bundle_bits n) { return (((unsigned int)(n >> 43)) & 0x1f); } static __inline unsigned int get_SrcA_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 6)) & 0x3f); } static __inline unsigned int get_SrcA_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 37)) & 0x3f); } static __inline unsigned int get_SrcA_Y0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 6)) & 0x3f); } static __inline unsigned int get_SrcA_Y1(tile_bundle_bits n) { return (((unsigned int)(n >> 37)) & 0x3f); } static __inline unsigned int get_SrcA_Y2(tile_bundle_bits n) { return (((n >> 26)) & 0x00000001) | (((unsigned int)(n >> 50)) & 0x0000003e); } static __inline unsigned int get_SrcBDest_Y2(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 20)) & 0x3f); } static __inline unsigned int get_SrcB_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 12)) & 0x3f); } static __inline unsigned int get_SrcB_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 43)) & 0x3f); } static __inline unsigned int get_SrcB_Y0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 12)) & 0x3f); } static __inline unsigned int get_SrcB_Y1(tile_bundle_bits n) { return (((unsigned int)(n >> 43)) & 0x3f); } static __inline unsigned int get_Src_SN(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 0)) & 0x3); } static __inline unsigned int get_UnOpcodeExtension_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 12)) & 0x1f); } static __inline unsigned int get_UnOpcodeExtension_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 43)) & 0x1f); } static __inline unsigned int get_UnOpcodeExtension_Y0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 12)) & 0x1f); } static __inline unsigned int get_UnOpcodeExtension_Y1(tile_bundle_bits n) { return (((unsigned int)(n >> 43)) & 0x1f); } static __inline unsigned int get_UnShOpcodeExtension_X0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 17)) & 0x3ff); } static __inline unsigned int get_UnShOpcodeExtension_X1(tile_bundle_bits n) { return (((unsigned int)(n >> 48)) & 0x3ff); } static __inline unsigned int get_UnShOpcodeExtension_Y0(tile_bundle_bits num) { const unsigned int n = (unsigned int)num; return (((n >> 17)) & 0x7); } static __inline unsigned int get_UnShOpcodeExtension_Y1(tile_bundle_bits n) { return (((unsigned int)(n >> 48)) & 0x7); } static __inline int sign_extend(int n, int num_bits) { int shift = (int)(sizeof(int) * 8 - num_bits); return (n << shift) >> shift; } static __inline tile_bundle_bits create_BrOff_SN(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3ff) << 0); } static __inline tile_bundle_bits create_BrOff_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x00007fff)) << 43) | (((tile_bundle_bits)(n & 0x00018000)) << 20); } static __inline tile_bundle_bits create_BrType_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0xf)) << 31); } static __inline tile_bundle_bits create_Dest_Imm8_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x0000003f)) << 31) | (((tile_bundle_bits)(n & 0x000000c0)) << 43); } static __inline tile_bundle_bits create_Dest_SN(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3) << 2); } static __inline tile_bundle_bits create_Dest_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3f) << 0); } static __inline tile_bundle_bits create_Dest_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x3f)) << 31); } static __inline tile_bundle_bits create_Dest_Y0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3f) << 0); } static __inline tile_bundle_bits create_Dest_Y1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x3f)) << 31); } static __inline tile_bundle_bits create_Imm16_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0xffff) << 12); } static __inline tile_bundle_bits create_Imm16_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0xffff)) << 43); } static __inline tile_bundle_bits create_Imm8_SN(int num) { const unsigned int n = (unsigned int)num; return ((n & 0xff) << 0); } static __inline tile_bundle_bits create_Imm8_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0xff) << 12); } static __inline tile_bundle_bits create_Imm8_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0xff)) << 43); } static __inline tile_bundle_bits create_Imm8_Y0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0xff) << 12); } static __inline tile_bundle_bits create_Imm8_Y1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0xff)) << 43); } static __inline tile_bundle_bits create_ImmOpcodeExtension_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x7f) << 20); } static __inline tile_bundle_bits create_ImmOpcodeExtension_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x7f)) << 51); } static __inline tile_bundle_bits create_ImmRROpcodeExtension_SN(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3) << 8); } static __inline tile_bundle_bits create_JOffLong_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x00007fff)) << 43) | (((tile_bundle_bits)(n & 0x00018000)) << 20) | (((tile_bundle_bits)(n & 0x001e0000)) << 14) | (((tile_bundle_bits)(n & 0x07e00000)) << 16) | (((tile_bundle_bits)(n & 0x18000000)) << 31); } static __inline tile_bundle_bits create_JOff_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x00007fff)) << 43) | (((tile_bundle_bits)(n & 0x00018000)) << 20) | (((tile_bundle_bits)(n & 0x001e0000)) << 14) | (((tile_bundle_bits)(n & 0x07e00000)) << 16) | (((tile_bundle_bits)(n & 0x08000000)) << 31); } static __inline tile_bundle_bits create_MF_Imm15_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x00003fff)) << 37) | (((tile_bundle_bits)(n & 0x00004000)) << 44); } static __inline tile_bundle_bits create_MMEnd_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x1f) << 18); } static __inline tile_bundle_bits create_MMEnd_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x1f)) << 49); } static __inline tile_bundle_bits create_MMStart_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x1f) << 23); } static __inline tile_bundle_bits create_MMStart_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x1f)) << 54); } static __inline tile_bundle_bits create_MT_Imm15_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x0000003f)) << 31) | (((tile_bundle_bits)(n & 0x00003fc0)) << 37) | (((tile_bundle_bits)(n & 0x00004000)) << 44); } static __inline tile_bundle_bits create_Mode(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x1)) << 63); } static __inline tile_bundle_bits create_NoRegOpcodeExtension_SN(int num) { const unsigned int n = (unsigned int)num; return ((n & 0xf) << 0); } static __inline tile_bundle_bits create_Opcode_SN(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3f) << 10); } static __inline tile_bundle_bits create_Opcode_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x7) << 28); } static __inline tile_bundle_bits create_Opcode_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0xf)) << 59); } static __inline tile_bundle_bits create_Opcode_Y0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0xf) << 27); } static __inline tile_bundle_bits create_Opcode_Y1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0xf)) << 59); } static __inline tile_bundle_bits create_Opcode_Y2(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x7)) << 56); } static __inline tile_bundle_bits create_RROpcodeExtension_SN(int num) { const unsigned int n = (unsigned int)num; return ((n & 0xf) << 4); } static __inline tile_bundle_bits create_RRROpcodeExtension_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x1ff) << 18); } static __inline tile_bundle_bits create_RRROpcodeExtension_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x1ff)) << 49); } static __inline tile_bundle_bits create_RRROpcodeExtension_Y0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3) << 18); } static __inline tile_bundle_bits create_RRROpcodeExtension_Y1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x3)) << 49); } static __inline tile_bundle_bits create_RouteOpcodeExtension_SN(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3ff) << 0); } static __inline tile_bundle_bits create_S_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x1) << 27); } static __inline tile_bundle_bits create_S_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x1)) << 58); } static __inline tile_bundle_bits create_ShAmt_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x1f) << 12); } static __inline tile_bundle_bits create_ShAmt_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x1f)) << 43); } static __inline tile_bundle_bits create_ShAmt_Y0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x1f) << 12); } static __inline tile_bundle_bits create_ShAmt_Y1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x1f)) << 43); } static __inline tile_bundle_bits create_SrcA_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3f) << 6); } static __inline tile_bundle_bits create_SrcA_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x3f)) << 37); } static __inline tile_bundle_bits create_SrcA_Y0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3f) << 6); } static __inline tile_bundle_bits create_SrcA_Y1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x3f)) << 37); } static __inline tile_bundle_bits create_SrcA_Y2(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x00000001) << 26) | (((tile_bundle_bits)(n & 0x0000003e)) << 50); } static __inline tile_bundle_bits create_SrcBDest_Y2(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3f) << 20); } static __inline tile_bundle_bits create_SrcB_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3f) << 12); } static __inline tile_bundle_bits create_SrcB_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x3f)) << 43); } static __inline tile_bundle_bits create_SrcB_Y0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3f) << 12); } static __inline tile_bundle_bits create_SrcB_Y1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x3f)) << 43); } static __inline tile_bundle_bits create_Src_SN(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3) << 0); } static __inline tile_bundle_bits create_UnOpcodeExtension_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x1f) << 12); } static __inline tile_bundle_bits create_UnOpcodeExtension_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x1f)) << 43); } static __inline tile_bundle_bits create_UnOpcodeExtension_Y0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x1f) << 12); } static __inline tile_bundle_bits create_UnOpcodeExtension_Y1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x1f)) << 43); } static __inline tile_bundle_bits create_UnShOpcodeExtension_X0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x3ff) << 17); } static __inline tile_bundle_bits create_UnShOpcodeExtension_X1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x3ff)) << 48); } static __inline tile_bundle_bits create_UnShOpcodeExtension_Y0(int num) { const unsigned int n = (unsigned int)num; return ((n & 0x7) << 17); } static __inline tile_bundle_bits create_UnShOpcodeExtension_Y1(int num) { const unsigned int n = (unsigned int)num; return (((tile_bundle_bits)(n & 0x7)) << 48); } typedef enum { TILE_PIPELINE_X0, TILE_PIPELINE_X1, TILE_PIPELINE_Y0, TILE_PIPELINE_Y1, TILE_PIPELINE_Y2, } tile_pipeline; #define tile_is_x_pipeline(p) ((int)(p) <= (int)TILE_PIPELINE_X1) typedef enum { TILE_OP_TYPE_REGISTER, TILE_OP_TYPE_IMMEDIATE, TILE_OP_TYPE_ADDRESS, TILE_OP_TYPE_SPR } tile_operand_type; /* This is the bit that determines if a bundle is in the Y encoding. */ #define TILE_BUNDLE_Y_ENCODING_MASK ((tile_bundle_bits)1 << 63) enum { /* Maximum number of instructions in a bundle (2 for X, 3 for Y). */ TILE_MAX_INSTRUCTIONS_PER_BUNDLE = 3, /* How many different pipeline encodings are there? X0, X1, Y0, Y1, Y2. */ TILE_NUM_PIPELINE_ENCODINGS = 5, /* Log base 2 of TILE_BUNDLE_SIZE_IN_BYTES. */ TILE_LOG2_BUNDLE_SIZE_IN_BYTES = 3, /* Instructions take this many bytes. */ TILE_BUNDLE_SIZE_IN_BYTES = 1 << TILE_LOG2_BUNDLE_SIZE_IN_BYTES, /* Log base 2 of TILE_BUNDLE_ALIGNMENT_IN_BYTES. */ TILE_LOG2_BUNDLE_ALIGNMENT_IN_BYTES = 3, /* Bundles should be aligned modulo this number of bytes. */ TILE_BUNDLE_ALIGNMENT_IN_BYTES = (1 << TILE_LOG2_BUNDLE_ALIGNMENT_IN_BYTES), /* Log base 2 of TILE_SN_INSTRUCTION_SIZE_IN_BYTES. */ TILE_LOG2_SN_INSTRUCTION_SIZE_IN_BYTES = 1, /* Static network instructions take this many bytes. */ TILE_SN_INSTRUCTION_SIZE_IN_BYTES = (1 << TILE_LOG2_SN_INSTRUCTION_SIZE_IN_BYTES), /* Number of registers (some are magic, such as network I/O). */ TILE_NUM_REGISTERS = 64, /* Number of static network registers. */ TILE_NUM_SN_REGISTERS = 4 }; struct tile_operand { /* Is this operand a register, immediate or address? */ tile_operand_type type; /* The default relocation type for this operand. */ signed int default_reloc : 16; /* How many bits is this value? (used for range checking) */ unsigned int num_bits : 5; /* Is the value signed? (used for range checking) */ unsigned int is_signed : 1; /* Is this operand a source register? */ unsigned int is_src_reg : 1; /* Is this operand written? (i.e. is it a destination register) */ unsigned int is_dest_reg : 1; /* Is this operand PC-relative? */ unsigned int is_pc_relative : 1; /* By how many bits do we right shift the value before inserting? */ unsigned int rightshift : 2; /* Return the bits for this operand to be ORed into an existing bundle. */ tile_bundle_bits (*insert) (int op); /* Extract this operand and return it. */ unsigned int (*extract) (tile_bundle_bits bundle); }; extern const struct tile_operand tile_operands[]; /* One finite-state machine per pipe for rapid instruction decoding. */ extern const unsigned short * const tile_bundle_decoder_fsms[TILE_NUM_PIPELINE_ENCODINGS]; struct tile_opcode { /* The opcode mnemonic, e.g. "add" */ const char *name; /* The enum value for this mnemonic. */ tile_mnemonic mnemonic; /* A bit mask of which of the five pipes this instruction is compatible with: X0 0x01 X1 0x02 Y0 0x04 Y1 0x08 Y2 0x10 */ unsigned char pipes; /* How many operands are there? */ unsigned char num_operands; /* Which register does this write implicitly, or TREG_ZERO if none? */ unsigned char implicitly_written_register; /* Can this be bundled with other instructions (almost always true). */ unsigned char can_bundle; /* The description of the operands. Each of these is an * index into the tile_operands[] table. */ unsigned char operands[TILE_NUM_PIPELINE_ENCODINGS][TILE_MAX_OPERANDS]; }; extern const struct tile_opcode tile_opcodes[]; /* Used for non-textual disassembly into structs. */ struct tile_decoded_instruction { const struct tile_opcode *opcode; const struct tile_operand *operands[TILE_MAX_OPERANDS]; int operand_values[TILE_MAX_OPERANDS]; }; /* Disassemble a bundle into a struct for machine processing. */ extern int parse_insn_tile(tile_bundle_bits bits, unsigned int pc, struct tile_decoded_instruction decoded[TILE_MAX_INSTRUCTIONS_PER_BUNDLE]); /* Given a set of bundle bits and a specific pipe, returns which * instruction the bundle contains in that pipe. */ extern const struct tile_opcode * find_opcode(tile_bundle_bits bits, tile_pipeline pipe); #endif /* opcode_tile_h */
21.593131
76
0.720329
83cfe4452fc1da70388218b5889bdf7dcdc87d7c
2,359
h
C
Pod/Classes/CPAudioPlayer.h
clementprem/CPAudioPlayer
b180c1aa17710c9fad0f245c10dbc972f4f200a1
[ "MIT" ]
2
2015-07-04T09:54:07.000Z
2022-02-16T17:51:40.000Z
Pod/Classes/CPAudioPlayer.h
clementprem/CPAudioPlayer
b180c1aa17710c9fad0f245c10dbc972f4f200a1
[ "MIT" ]
null
null
null
Pod/Classes/CPAudioPlayer.h
clementprem/CPAudioPlayer
b180c1aa17710c9fad0f245c10dbc972f4f200a1
[ "MIT" ]
null
null
null
// // CPAudioPlayer.h // // // Created by Clement Prem on 8/16/14. // Copyright (c) 2014 Clement Prem. All rights reserved. // #import <Foundation/Foundation.h> #import <AudioToolbox/AudioToolbox.h> typedef struct { AUGraph graph; AudioFileID inputFile; AudioStreamBasicDescription asbd; AudioUnit bandEQUnit; AudioUnit mxUnit; AudioUnit eqUnit; AudioUnit delayUnit; AudioUnit bassBoostUnit; AudioUnit treble; AudioUnit filePlayerUnit; AudioUnit reverbUnit; AudioUnit testUnit; Float64 playBackStartFrame; //indicating the frame the player should start playing, when pauesed & resume ScheduledAudioFileRegion region; }CPPlayer; typedef enum { LEFT = 0, RIGHT = 1 }CHANNEL; typedef void (^_songPlayCompletionHandler)(); @interface CPAudioPlayer : NSObject { @private CFArrayRef eqPresetArray; } @property (nonatomic)double playBackduration; @property (nonatomic, strong, readonly)NSURL *songUrl; @property (readonly, nonatomic)double currentPlaybackTime; @property (nonatomic, copy)_songPlayCompletionHandler songCompletion; /** Audio Controll & cycle methods */ -(BOOL)play; -(void)pause; -(void)stop; -(void)setupAudioFileWithURL:(NSURL *)audioUrl playBackDuration:(double)playBackDuration isError:(Boolean *)isError; -(void)handleSongPlayingCompletion:(_songPlayCompletionHandler)handler; -(void)setPlayBackTime:(double)time; /** Audio manipulation methods */ #pragma mark iPod Eq presets -(CFArrayRef)getEqulizerPresets; -(void)setiPodEQPreset:(UInt32)index; #pragma mark Band Equlizer -(void)setBandValue:(NSArray *)value; -(float)getValueForBand:(NSInteger)bandPosition; -(NSArray *)getAllBands; #pragma Room Size -(void)setRoomSize:(float)value; -(float)getRommSize; /** pan -1 -> 1 :0 */ -(void)setChannelBalance:(float)pan; -(float)getChannelBalance; //Bass boost -(void)setbassBoost:(float)value; -(float)getBassBoost; //Treble boost -(void)setTreble:(float)value; -(float)getTreble; //Reverb //-(void)setReverbType:(int)reverbParam value:(float)value; //-(float)getReverbVauleForType:(int)reverbParam; //Testing //-(void)setDynamicProcess:(float)value parameter:(UInt32)parameterID; -(void)setVauleForComponent:(NSString *)compenentId parameter:(int)param value:(float)value; -(float)getVauleForComponent:(NSString *)compenentId parameter:(int)param; @end
25.641304
116
0.756677
23d160e2e96e857371e39a01e506d06ebc8ebb9c
152
h
C
catboost/libs/model/ut/model_test_helpers.h
Kim2212/catboost
b9ad3b0dac6269c2638e8ee4e7bb85662677a921
[ "Apache-2.0" ]
null
null
null
catboost/libs/model/ut/model_test_helpers.h
Kim2212/catboost
b9ad3b0dac6269c2638e8ee4e7bb85662677a921
[ "Apache-2.0" ]
null
null
null
catboost/libs/model/ut/model_test_helpers.h
Kim2212/catboost
b9ad3b0dac6269c2638e8ee4e7bb85662677a921
[ "Apache-2.0" ]
null
null
null
#pragma once #include <catboost/libs/data/pool.h> #include <catboost/libs/model/model.h> TFullModel TrainFloatCatboostModel(); TPool GetAdultPool();
16.888889
38
0.776316
c1613e23fe5d55c4fabe4cb3c4a3c3acec37b93b
2,235
h
C
Sample/Chipset/AdvancedConfiguration/AcpiReset/RuntimeDxe/Reset.h
kontais/EFI-MIPS
c4de746e6a926fc9df71231a539e2c0a170bcc90
[ "BSD-3-Clause" ]
11
2016-07-21T11:39:51.000Z
2022-01-06T10:35:12.000Z
Sample/Chipset/AdvancedConfiguration/AcpiReset/RuntimeDxe/Reset.h
kontais/EFI-MIPS
c4de746e6a926fc9df71231a539e2c0a170bcc90
[ "BSD-3-Clause" ]
1
2019-09-03T04:11:46.000Z
2019-09-03T04:11:46.000Z
Sample/Chipset/AdvancedConfiguration/AcpiReset/RuntimeDxe/Reset.h
kontais/EFI-MIPS
c4de746e6a926fc9df71231a539e2c0a170bcc90
[ "BSD-3-Clause" ]
3
2019-09-04T02:59:01.000Z
2021-08-23T06:07:28.000Z
/*++ Copyright (c) 2006 - 2007, Intel Corporation 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. Module Name: Reset.h Abstract: some definitions for reset --*/ #ifndef _ACPI_RESET_H #define _ACPI_RESET_H #include "Tiano.h" #include "EfiRuntimeLib.h" #include "EfiCommonLib.h" #include "EfiHobLib.h" // // Driver Consumes GUIDs // #include EFI_GUID_DEFINITION (Hob) #include EFI_GUID_DEFINITION (AcpiDescription) EFI_STATUS EFIAPI InitializeReset ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) /*++ Routine Description: Initialize the state information for the Reset Architectural Protocol Arguments: ImageHandle of the loaded driver Pointer to the System Table Returns: Status EFI_SUCCESS - thread can be successfully created EFI_OUT_OF_RESOURCES - cannot allocate protocol data structure EFI_DEVICE_ERROR - cannot create the timer service --*/ ; VOID EFIAPI AcpiResetSystem ( IN EFI_RESET_TYPE ResetType, IN EFI_STATUS ResetStatus, IN UINTN DataSize, IN CHAR16 *ResetData, OPTIONAL IN EFI_ACPI_DESCRIPTION *AcpiDescription ) /*++ Routine Description: Reset the system. Arguments: ResetType - warm or cold ResetStatus - possible cause of reset DataSize - Size of ResetData in bytes ResetData - Optional Unicode string AcpiDescription - Global variable to record reset info Returns: Does not return if the reset takes place. --*/ ; EFI_ACPI_DESCRIPTION * GetAcpiDescription ( IN EFI_ACPI_DESCRIPTION *AcpiDescription ); #endif
22.806122
101
0.656376
af48aceefc7ab21d058e4e8ef24592e8ffbcb81f
278
c
C
code/3065.c
Tarpelite/OJ_research
5c23591a50e755dac800dfaedb561290ce35fc5b
[ "MIT" ]
null
null
null
code/3065.c
Tarpelite/OJ_research
5c23591a50e755dac800dfaedb561290ce35fc5b
[ "MIT" ]
null
null
null
code/3065.c
Tarpelite/OJ_research
5c23591a50e755dac800dfaedb561290ce35fc5b
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> int main() {int k[100001]={0},i,j,n,th; scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d",&j); k[j]=k[j]+1; } j=0; scanf("%d",&th); for(i=100000;j<th;i--){ if(k[i]!=0) j++; } printf("%d %d",i,k[++i]); return 0; }
13.238095
28
0.44964
766fb65cc734cd00539929f966020279b5fa8088
2,942
c
C
src/clib/u8g2_font_freedoomr10_mu.c
kzhioki/U8g2_Arduino
42bac40675ab7404e6df3444cb01124aa9bd17b2
[ "BSD-2-Clause" ]
null
null
null
src/clib/u8g2_font_freedoomr10_mu.c
kzhioki/U8g2_Arduino
42bac40675ab7404e6df3444cb01124aa9bd17b2
[ "BSD-2-Clause" ]
null
null
null
src/clib/u8g2_font_freedoomr10_mu.c
kzhioki/U8g2_Arduino
42bac40675ab7404e6df3444cb01124aa9bd17b2
[ "BSD-2-Clause" ]
null
null
null
#include "u8g2.h" /* Fontname: -FreeType-FreeDooM-Bold-R-Normal--34-340-72-72-P-170-ISO8859-1 Copyright: FreeUniveral (c) Stephen Wilson 2009 Original Font Sil-Sophia Copyright (c) SIL International, 1994-2008. Glyphs: 64/256 BBX Build Mode: 2 */ const uint8_t u8g2_font_freedoomr10_mu[904] U8G2_FONT_SECTION("u8g2_font_freedoomr10_mu") = "@\2\4\3\4\4\1\2\5\10\13\0\1\14\0\14\2\1W\0\0\3k \7\270\307\217\327\0!\7" "\270\307\217\327\0\42\7\270\307\217\327\0#\7\270\307\217\327\0$\7\270\307\217\327\0%\7\270\307\217\327" "\0&\7\270\307\217\327\0'\7\270\307\217\327\0(\12\270\307!\25\227\37J\3)\12\270\307#\30\227" "_\311\2*\15\270\307\221\321X\330PDz\254\0+\14\270\307\33\227\350(.=\64\0,\11\270\307" "\23\26\217'\0-\11\270\307\217\344\36#\0.\10\270\307\217\63\305\0/\15\270\307\226.,]X\272" "\260x\0\60\27\270\307`\22\24\22\24\22\24\22\24\22\24\22\24\22\24\22\24b\12\61\10\270\307$\227" "\177\12\62\14\270\307`\227\23\223\270t\246\0\63\13\270\307`\227\21]NL\1\64\22\270\307\20\24\22" "\24\22\24\22\24\22\24b\227S\0\65\14\270\307`\22\227\316.'\246\0\66\23\270\307`\22\227\316$" "($($($(\304\24\0\67\10\270\307`\227\177\12\70\26\270\307`\22\24\22\24\22\24b\22\24" "\22\24\22\24\22\24b\12\71\20\270\307`\22\24\22\24\22\24b\227\23S\0:\14\270\307\17+&\217" "@L\30\0;\7\270\307\217\327\0<\7\270\307\217\327\0=\7\270\307\217\327\0>\7\270\307\217\327\0" "\77\7\270\307\217\327\0@\7\270\307\217\327\0A\27\270\307p\21\25\21\25\21\25\21\25q\21\25\21\25" "\21\25\21\25\11B\26\270\307p\21\25\21\25\21\25a\22\25\21\25\21\25\21\25q\11C\12\270\307p" "\21\227\337]\2D\27\270\307`\22\25\21\25\21\25\21\25\21\25\21\25\21\25\21\25a\12E\15\270\307" "p\21\227\256&.\273K\0F\14\270\307p\21\227\256&.\367\0G\23\270\307p\21\227\11ETD" "TDTDT\304%\0H\30\270\307\20\25\21\25\21\25\21\25q\21\25\21\25\21\25\21\25\21\25\11" "I\10\270\307\23\227\177\14J\17\270\307C\227\27Q\21Q\21Q!\245\0K\27\270\307\20\25\21\24\22" "\223$h*\42*$(&QHT$\0L\11\270\307\20\227\277\273\4M\30\270\307\20\25!#\221" "')\242\42\242\42\242\42\242\42\242\42\242\42\1N\32\270\307 \24!\24\221&\42MDH\212\220\24" "\61\21i\42\22I\4I\2O\27\270\307Q\22\25\21\25\21\25\21\25\21\25\21\25\21\25\21\25R\12" "P\20\270\307p\21\25\21\25\21\25q\21\227{\0Q\27\270\307A\23\24\22\24\22\24\22\24\22\24\22" "\24\22\24\22\24c\11R\26\270\307p\21\25\21\25\21\25q\221*$(&QHT$\0S\14\270" "\307p\21\227\335]\26\227\0T\12\270\307p\24\227\337C\1U\30\270\307\20\25\21\25\21\25\21\25\21" "\25\21\25\21\25\21\25\21\25q\11V\26\270\307\20\25\21\25\21\25\22\223\215\204PDTDX\134\60" "\0W\30\270\307\20\25\21\25\21\25\21\25\21\25\21\222\42$E\376BF\22\0X\24\270\307\20\25\22" "\223QDX\134XDPL&Q\221\0Y\21\270\307\20\25\21\25\21\25\21\25q\24\227c\0Z\14" "\270\307p\27&\245gq\227\0[\12\270\307@\24\227\337\21\3\134\17\270\307\20\30\27\30\27\30\27\30" "\27\30\12]\11\270\307B\227\77\42\5^\14\270\307\23\26\21\24\23\217\63\0_\10\270\307\217cS\0" "\0\0\0\4\377\377\0";
77.421053
122
0.655337
639d8c33a608c3742e705d421999b76d742c2f41
326
c
C
tp2/ask4exit.c
vrunoa/aus
b9dbb23275fc0ba27300f5110bcab4684da7f2c4
[ "MIT" ]
null
null
null
tp2/ask4exit.c
vrunoa/aus
b9dbb23275fc0ba27300f5110bcab4684da7f2c4
[ "MIT" ]
null
null
null
tp2/ask4exit.c
vrunoa/aus
b9dbb23275fc0ba27300f5110bcab4684da7f2c4
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include <string.h> void askForExit(char* q){ printf("desea salir (S/N)\n"); scanf("%s", q); } int main() { char* q = malloc(1*sizeof(char)); while(strcmp(q,"s") != 0) { askForExit(q); printf("%s\n", q); } free(q); printf("Thank you! Come again!"); return 0; }
16.3
35
0.564417
17d509a95ec32871da366014ac313bdb280a250b
656
h
C
voodoopadplugins/htmltools/HTMLToolsPlugin.h
ccgus/flycode
a8b97ca99bcf6f109962c4547f38e179f17e44ef
[ "BSD-2-Clause-FreeBSD" ]
13
2015-07-19T21:15:38.000Z
2022-02-16T04:36:50.000Z
voodoopadplugins/htmltools/HTMLToolsPlugin.h
ccgus/flycode
a8b97ca99bcf6f109962c4547f38e179f17e44ef
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
voodoopadplugins/htmltools/HTMLToolsPlugin.h
ccgus/flycode
a8b97ca99bcf6f109962c4547f38e179f17e44ef
[ "BSD-2-Clause-FreeBSD" ]
6
2015-01-12T08:17:00.000Z
2021-12-09T05:46:35.000Z
// Created by August Mueller on 10/25/04. // Copyright 2004 __MyCompanyName__. All rights reserved. #import <Cocoa/Cocoa.h> #import <VPPlugin/VPPlugin.h> #import <WebKit/WebKit.h> @interface HTMLToolsPlugin : VPPlugin <VPURLHandler> { IBOutlet NSWindow *previewWindow; IBOutlet WebView *webView; IBOutlet NSPopUpButton *formattingSelection; NSString *previewKey; id<VPPluginDocument> previewDoc; } - (void) updateHTMLPreview:(id)sender; - (NSString *)previewKey; - (void)setPreviewKey:(NSString *)newPreviewKey; - (id<VPPluginDocument>)previewDoc; - (void)setPreviewDoc:(id<VPPluginDocument>)newPreviewDoc; @end
22.62069
58
0.733232
4fb4464cd8aaa2ebd22fb8fcbc67a543ed86a979
1,041
h
C
core/profiler.h
ut-osa/gpunet
10a6da3b4bbfced885272c535ba661301f49a551
[ "Apache-2.0" ]
67
2015-01-16T22:38:52.000Z
2022-02-08T23:45:16.000Z
core/profiler.h
ut-osa/gpunet
10a6da3b4bbfced885272c535ba661301f49a551
[ "Apache-2.0" ]
1
2015-05-06T19:32:15.000Z
2015-12-28T01:57:27.000Z
core-dgram/profiler.h
ut-osa/gpunet
10a6da3b4bbfced885272c535ba661301f49a551
[ "Apache-2.0" ]
19
2015-02-11T05:48:16.000Z
2021-11-15T01:02:01.000Z
#ifndef PROFILER_H #define PROFILER_H #include <stdio.h> #include "clock_cat.h" #ifdef __cplusplus extern "C" { #endif #ifdef ENABLE_PROFILER void profiler_output(FILE*); int ev_start(clock_category cat, int socket); int ev_stop(clock_category cat, int socket); #define EV_START(x, y) ev_start(x,y) #define EV_STOP(x, y) ev_stop(x,y) #define PROFILER_OUTPUT(x) profiler_output(x) #define EV_FLIPPER(start_ev, stop_ev, label) flipper ____this_flipper(start_ev, stop_ev, label); #else #define EV_START(x,y) #define EV_STOP(x,y) #define PROFILER_OUTPUT(x) do { fprintf(x, "Profiler disabled\n"); } while (0) #define EV_FLIPPER(start_ev, stop_ev, label) #endif #ifdef __cplusplus }; #endif class flipper { public: flipper(clock_category start, clock_category stop, int soc) :start_(start), stop_(stop), socket_(soc) { EV_STOP(stop_, socket_); EV_START(start_, socket_); } ~flipper() { EV_START(stop_, socket_); EV_STOP(start_, socket_); } private: clock_category start_; clock_category stop_; int socket_; }; #endif
19.277778
96
0.740634
a054a97b1265e3efaffc1e1602afac2618b27d55
651
h
C
Source/EngineStd/UserInterface/UserInterface.h
vivienneanthony/MyForkEditor
273e15ca3610b3d3b68fdf2efbac2ba1b3659e7f
[ "Apache-2.0" ]
2
2015-12-30T00:32:09.000Z
2016-02-27T14:50:06.000Z
Source/EngineStd/UserInterface/UserInterface.h
vivienneanthony/MyForkEditor
273e15ca3610b3d3b68fdf2efbac2ba1b3659e7f
[ "Apache-2.0" ]
null
null
null
Source/EngineStd/UserInterface/UserInterface.h
vivienneanthony/MyForkEditor
273e15ca3610b3d3b68fdf2efbac2ba1b3659e7f
[ "Apache-2.0" ]
null
null
null
#ifndef USER_INTERFACE_H #define USER_INTERFACE_H // This was factored to create a common class that // implements some of the IScreenElement class common // to modal/modeless dialogs class BaseUI : public IScreenElement { URHO3D_OBJECT(BaseUI,IScreenElement); protected: int m_PosX, m_PosY; int m_Width, m_Height; int m_Result; bool m_bIsVisible; public: BaseUI(Context* context); virtual ~BaseUI(); virtual void VOnUpdate(float timeStep); virtual bool VOnLostDevice() { return true; }; virtual bool VIsVisible() const; virtual void VSetVisible(bool visible); }; #endif //USER_INTERFACE_H
21.7
54
0.718894
3f4151cc4e8f46b1c5b6519d999a0f0124c26560
182
h
C
frameworks/3rd/sqlite3/lsqlite3.h
bsqgm/cocos-lua
cbad3eb61c75bbb3f9fdba866cdc30d0dac54af8
[ "MIT" ]
141
2019-07-09T06:29:35.000Z
2022-03-30T06:25:16.000Z
frameworks/3rd/sqlite3/lsqlite3.h
bsqgm/cocos-lua
cbad3eb61c75bbb3f9fdba866cdc30d0dac54af8
[ "MIT" ]
16
2019-12-23T06:53:18.000Z
2021-10-19T17:01:01.000Z
frameworks/3rd/sqlite3/lsqlite3.h
bsqgm/cocos-lua
cbad3eb61c75bbb3f9fdba866cdc30d0dac54af8
[ "MIT" ]
47
2019-08-14T11:12:34.000Z
2022-03-30T06:25:19.000Z
#ifndef __LSQLITE3_H__ #define __LSQLITE3_H__ #if __cplusplus extern "C" { #endif #include "lua.h" LUALIB_API int luaopen_lsqlite3(lua_State *L); #if __cplusplus } #endif #endif
11.375
46
0.758242
8f713342b7d6837fc1e30b5a0e52dd2c99f10ad3
9,561
c
C
SensorNode/SW/APP2_Audio/SensorNode/Src/Motion_Sensors.c
tommasopolonelli/SynthSense-WSN-UAV
95f4f574c0211720f7fceb6ae90e555e04b9bd1e
[ "Unlicense" ]
3
2020-07-03T08:15:03.000Z
2021-07-13T16:12:27.000Z
SensorNode/SW/APP2_Audio/SensorNode/Src/Motion_Sensors.c
tommasopolonelli/SynthSense-WSN-UAV
95f4f574c0211720f7fceb6ae90e555e04b9bd1e
[ "Unlicense" ]
null
null
null
SensorNode/SW/APP2_Audio/SensorNode/Src/Motion_Sensors.c
tommasopolonelli/SynthSense-WSN-UAV
95f4f574c0211720f7fceb6ae90e555e04b9bd1e
[ "Unlicense" ]
1
2021-07-13T16:12:32.000Z
2021-07-13T16:12:32.000Z
/** ****************************************************************************** * @file : Int_Sensors.c * @brief : Sensors Management ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "macro.h" #include "cmsis_os.h" #include "sai.h" #include "gpio.h" #include "Int_Sensors.h" #include "Motion_Sensors.h" #include "pdm2pcm_glo.h" #include "Flash_Mngm.h" /* Private includes ----------------------------------------------------------*/ /* Private typedef -----------------------------------------------------------*/ /* Number of conversions */ /* Private define ------------------------------------------------------------*/ /* Rec timer after the last trigger */ #define REC_TIMER_MS (5000) /* The high-pass filter is a one-pole recursive filter. The cut-off frequency is configured by modifying the parameter high_pass_tap from the PDM_Filter_Handler_t. This coefficient value must be in the range [0 : 1]. The format used is Q0.31, meaning that 1 corresponds to the maximum integer value obtainable with 31-bit resolution. For example, configuring the high_pass_tap parameter to 0.98 corresponds to 0.98*(231-1) = 2104533974. */ #define HIGH_PASS_FILT (2122358088) #define PDM_FILTER_NO_ERROR (0) #define DEFAULT_MIC_GAIN (15) /* chanche both numbers */ #define DEC_FAC PDM_FILTER_DEC_FACTOR_128 #define DEC_FAC_NUM (128) /* number of samples generated at every filter operations */ /* must be larger as possible to reduce the load */ /* increasing the size increases the RAM size */ #define PCM_SAMPLES 128 #define MIC_BUFF_TYPE uint16_t #define MIC_BUFF_SIZE ((DEC_FAC_NUM * PCM_SAMPLES) / (8*sizeof(MIC_BUFF_TYPE))) #define MIC_BUFF_LEN (MIC_BUFF_SIZE*2) /* Private macro -------------------------------------------------------------*/ enum { EVT_RECHALF = (1 << 0), /* 0b0000000000000001 */ EVT_RECFULL = (1 << 1), /* 0b0000000000000010 */ EVT_MOTIONSTART = (1 << 2), /* 0b0000000000000100 */ EVT_MOTIONEND = (1 << 3), /* 0b0000000000001000 */ EVT_MOTIONSEND = (1 << 4), /* 0b0000000000010000 */ kCGDisplayRemoveFlag = (1 << 5), /* 0b0000000000100000 */ kCGDisplayEnabledFlag = (1 << 8), /* 0b0000000100000000 */ kCGDisplayDisabledFlag = (1 << 9), /* 0b0000001000000000 */ kCGDisplayMirrorFlag = (1 << 10),/* 0b0000010000000000 */ kCGDisplayUnMirrorFlag = (1 << 11),/* 0b0000100000000000 */ kCGDisplayDesktopShapeChangedFlag = (1 << 12) /* 0b0001000000000000 */ }; typedef enum { M_S_SLEEP, M_S_START, M_S_REC, M_S_DATATX }motion_stat_e; /* Private variables ---------------------------------------------------------*/ MIC_BUFF_TYPE mic_buff[MIC_BUFF_LEN]; static int16_t pcm_buffer[PCM_SAMPLES]; static StaticEventGroup_t Motion_EventGroupBuffer; EventGroupHandle_t Motion_Event; // An array to hold handles to the created timers. static xTimerHandle Rec_Timer; static StaticTimer_t Rec_Timer_Buffer; /* status */ motion_stat_e motion_stat = M_S_SLEEP; /* PDM filter */ static PDM_Filter_Handler_t PDM1_filter_handler; static PDM_Filter_Config_t PDM1_filter_config; /* Private function prototypes -----------------------------------------------*/ static void Rec_Timer_Callback( TimerHandle_t xTimer ); /* Private user code ---------------------------------------------------------*/ void MotionSensors_Task (void const * argument){ EventBits_t uxBits; uint8_t start = (uint8_t)((uint8_t *)argument); /* task disabled */ if (!start){ /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(PW_SAI_GPIO_Port, PW_SAI_Pin, GPIO_PIN_RESET); /* delete task */ vTaskDelete( osThreadGetId () ); return; } MX_SAI1_Init(); /* Set the sampling freq a 2048KHz */ hsai_BlockA1.Init.Mckdiv = 2; hsai_BlockA1.Instance->CR1 |= (hsai_BlockA1.Init.Mckdiv << 20); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(PW_SAI_GPIO_Port, PW_SAI_Pin, GPIO_PIN_SET); osDelay(1000); // Create the event group Motion_Event = xEventGroupCreateStatic( &Motion_EventGroupBuffer ); // Create low frequency timer Rec_Timer = xTimerCreateStatic("Rec_Timer", // Just a text name, not used by the kernel. REC_TIMER_MS , // The timer period in ticks. pdFALSE, // The timers will auto-reload themselves when they expire. "Rec_Timer", // Assign each timer a unique id equal to its array index. Rec_Timer_Callback, // Each timer calls the same callback when it expires. &Rec_Timer_Buffer ); //Init PDM Filter /* Initialize PDM Filter structure */ PDM1_filter_handler.bit_order = PDM_FILTER_BIT_ORDER_LSB; PDM1_filter_handler.endianness = PDM_FILTER_ENDIANNESS_LE; PDM1_filter_handler.high_pass_tap = HIGH_PASS_FILT; PDM1_filter_handler.out_ptr_channels = 1; PDM1_filter_handler.in_ptr_channels = 1; if(PDM_Filter_Init((PDM_Filter_Handler_t *)(&PDM1_filter_handler)) != PDM_FILTER_NO_ERROR){ while(1); } PDM1_filter_config.output_samples_number = PCM_SAMPLES; PDM1_filter_config.mic_gain = DEFAULT_MIC_GAIN; PDM1_filter_config.decimation_factor = DEC_FAC; if(PDM_Filter_setConfig((PDM_Filter_Handler_t *)&PDM1_filter_handler, &PDM1_filter_config) != PDM_FILTER_NO_ERROR){ while(1); } /* start application */ while (1){ switch(motion_stat){ case M_S_SLEEP : HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin,0); uxBits = xEventGroupWaitBits( /* The event group being tested. */ Motion_Event, /* The bits within the event group to wait for. */ EVT_MOTIONSTART | EVT_MOTIONSEND, /* BIT_0 & BIT_4 should be cleared before returning. */ pdTRUE, /* Don't wait for both bits, either bit will do. */ pdFALSE, /* Wait a maximum of 100ms for either bit to be set. */ portMAX_DELAY ); if(IS_EVT(EVT_MOTIONSTART)){ HAL_SAI_Receive_DMA(&hsai_BlockA1, (uint8_t *)mic_buff, MIC_BUFF_LEN); xTimerStart( Rec_Timer, 1000 ); motion_stat = M_S_REC; } if(IS_EVT(EVT_MOTIONSEND)){ motion_stat = M_S_DATATX; } break; case M_S_START: break; case M_S_REC: uxBits = xEventGroupWaitBits( /* The event group being tested. */ Motion_Event, /* The bits within the event group to wait for. */ EVT_MOTIONSTART | EVT_RECHALF | EVT_RECFULL | EVT_MOTIONEND | EVT_MOTIONSEND, /* BIT_0 & BIT_4 should be cleared before returning. */ pdTRUE, /* Don't wait for both bits, either bit will do. */ pdFALSE, /* Wait a maximum of 100ms for either bit to be set. */ portMAX_DELAY ); if(IS_EVT(EVT_MOTIONSTART)){ xTimerReset( Rec_Timer, 1000 ); } if(IS_EVT(EVT_RECHALF)){ HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin); /* process current frame */ PDM_Filter(&mic_buff[0], &pcm_buffer[0], &PDM1_filter_handler); /* Store data to Flash */ Flash_Write_Req ((uint8_t *)&pcm_buffer[0], sizeof(pcm_buffer)); } if(IS_EVT(EVT_RECFULL)){ /* process current frame */ PDM_Filter(&mic_buff[MIC_BUFF_SIZE], &pcm_buffer[0], &PDM1_filter_handler); /* Store data to Flash */ Flash_Write_Req ((uint8_t *)&pcm_buffer[0], sizeof(pcm_buffer)); } if(IS_EVT(EVT_MOTIONEND)){ HAL_SAI_DMAStop(&hsai_BlockA1); motion_stat = M_S_SLEEP; } if(IS_EVT(EVT_MOTIONSEND)){ HAL_SAI_DMAStop(&hsai_BlockA1); xTimerStop( Rec_Timer, 1000 ); motion_stat = M_S_DATATX; } break; case M_S_DATATX: HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin,0); uxBits = xEventGroupWaitBits( /* The event group being tested. */ Motion_Event, /* The bits within the event group to wait for. */ EVT_MOTIONSTART | EVT_RECHALF | EVT_RECFULL | EVT_MOTIONEND | EVT_MOTIONSEND, /* BIT_0 & BIT_4 should be cleared before returning. */ pdTRUE, /* Don't wait for both bits, either bit will do. */ pdFALSE, /* Wait a maximum of 100ms for either bit to be set. */ portMAX_DELAY ); if(IS_EVT(EVT_MOTIONSEND)){ /* end of transfer */ motion_stat = M_S_SLEEP; } break; } //HAL_SAI_Receive(&hsai_BlockA1, (uint8_t *)mic_buff, MIC_BUFF_LEN, 100); //osDelay(1000); //HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin,0); //HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin); //HAL_PWR_EnterSTOPMode(PWR_MAINREGULATOR_ON, PWR_STOPENTRY_WFI); /* exit stop mode */ //SystemClock_Config(); } } #pragma GCC push_options #pragma GCC optimize ("O3") void HAL_SAI_RxHalfCpltCallback(SAI_HandleTypeDef *hsai){ EVENTSETBIT(Motion_Event,EVT_RECHALF); } void HAL_SAI_RxCpltCallback(SAI_HandleTypeDef *hsai){ EVENTSETBIT(Motion_Event,EVT_RECFULL); } static void Rec_Timer_Callback( TimerHandle_t xTimer ){ EVENTSETBIT(Motion_Event,EVT_MOTIONEND); } void WUA_Callback( void ){ EVENTSETBIT(Motion_Event,EVT_MOTIONSTART); } void MotionSens_SendState( void ){ EVENTSETBIT(Motion_Event,EVT_MOTIONSEND); } #pragma GCC pop_options
30.644231
94
0.648049
5811bced2ed2501722e44d08ffc40298c0b810ca
1,013
c
C
tools/cyan_imageviewer/src/main.c
DavyL/cyan
da96ac974d87a118f0ab4da1f7fd61258eb613ec
[ "WTFPL" ]
null
null
null
tools/cyan_imageviewer/src/main.c
DavyL/cyan
da96ac974d87a118f0ab4da1f7fd61258eb613ec
[ "WTFPL" ]
null
null
null
tools/cyan_imageviewer/src/main.c
DavyL/cyan
da96ac974d87a118f0ab4da1f7fd61258eb613ec
[ "WTFPL" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <cyan/color/color.h> #include <cyan/image/image.h> //#include "load_png.h" #include <cyan_fileio/load_png.h> #include <cyan_fileio/save_ppm.h> //Basic program to open a .jpg file through cyan //(Probably deprecated... see cyan_transforms ) int main( int argc, char** argv, char* envv ) { int i, j ; int result ; image_t* image ; FILE * fp; if (argc != 3 ) { fprintf(stderr,"Usage : %s input_file.png output_file.ppm\n", argv[0] ) ; return -1 ; } fp = fopen( argv[1] , "r" ); if( fp == NULL){ fprintf(stderr, "Couldn't open file.\n Error : %d, (%s)\n", errno, strerror(errno)); return -1; } image = png2image(fp); if ( image == NULL ) { fprintf(stderr,"image allocation of %s failed \n", argv[1]) ; return -1 ; } result = image_save_ppm( image, argv[2] ) ; if (result != 0) { fprintf(stderr, "cannot save file\n") ; return -1 ; } image_free( image) ; fclose(fp); return 0 ; }
19.480769
86
0.624877
55f6c5af4ec87199e6a6becc5f1cbb171e19f2a3
2,212
h
C
test/time_test.h
project-eutopia/vega
c7b536c5e949094a908fa8f378729dbffc657f4a
[ "MIT" ]
18
2018-01-23T12:28:13.000Z
2022-02-13T12:23:21.000Z
test/time_test.h
project-eutopia/vega
c7b536c5e949094a908fa8f378729dbffc657f4a
[ "MIT" ]
2
2018-11-29T01:51:25.000Z
2022-03-22T14:14:22.000Z
test/time_test.h
project-eutopia/vega
c7b536c5e949094a908fa8f378729dbffc657f4a
[ "MIT" ]
6
2019-02-01T09:54:44.000Z
2022-01-09T22:13:54.000Z
#pragma once #include "test_helper.h" #include "vega/string.h" #include "vega/time.h" #include "vega/manipulators/padded_string_manipulator.h" using namespace vega; TEST(TimeTest, constructor_test) { Time time("235959.999999"); EXPECT_EQ(time.str(), "235959.999999"); } TEST(TimeTest, range_test) { { Time time(" - 120000 "); EXPECT_TRUE(time.is_range()); EXPECT_FALSE(time.lower()); EXPECT_TRUE(time.upper()); EXPECT_EQ(time.str(), "-120000"); } { Time time(" 2330 - "); EXPECT_TRUE(time.is_range()); EXPECT_TRUE(time.lower()); EXPECT_FALSE(time.upper()); EXPECT_EQ(time.str(), "2330-"); } { Time time("08-17"); EXPECT_TRUE(time.is_range()); EXPECT_TRUE(time.lower()); EXPECT_TRUE(time.upper()); EXPECT_EQ(time.str(), "08-17"); } } TEST(TimeTest, element_from_string_test) { Time time = vega::from_string<Time>("120000"); EXPECT_EQ(time.str(), "120000"); } TEST(TimeTest, to_string_test) { Time time("112233"); EXPECT_EQ(vega::to_string(time), std::string("112233")); } TEST(TimeTest, manipulator_test) { vega::manipulators::PaddedStringManipulator<Time> time_manipulator{}; time_manipulator.emplace_back(std::string("120000")); time_manipulator.emplace_back(std::string("180059")); EXPECT_EQ(time_manipulator[0].str(), "120000"); EXPECT_EQ(time_manipulator[1].str(), "180059"); EXPECT_EQ(time_manipulator.str(), std::string("120000\\180059 ")); } TEST(TimeTest, stream_test) { std::vector<std::string> time_strings = { "23", "-1212", "200011-", "112233-223344.1", "000000.000000-235959.999999" }; for (const auto& time_string : time_strings) { Time time(time_string); std::stringstream ss; ss << time; const std::string s = ss.str(); EXPECT_EQ(s, time_string); ss = std::stringstream(s); Time time2; ss >> time2; EXPECT_EQ(time, time2); } std::string comma_separated_times = "12:00:00-130000,235959.999999"; std::stringstream ss(comma_separated_times); Time time; ss >> time; EXPECT_EQ(time.str(), "120000-130000"); char c; ss >> c; EXPECT_EQ(c, ','); ss >> time; EXPECT_EQ(time.str(), "235959.999999"); }
21.269231
71
0.651447
df860b3cadff2a94b598f1a72b625df5f432fd5b
16,342
h
C
kernel-module/ethosn_firmware.h
ARM-software/npu-driver-stack
1e6b00b21ed4cf39b2df625fa242c6f67c05b19f
[ "Apache-2.0" ]
4
2019-05-31T18:48:24.000Z
2019-06-04T07:59:39.000Z
kernel-module/ethosn_firmware.h
ARM-software/npu-driver-stack
1e6b00b21ed4cf39b2df625fa242c6f67c05b19f
[ "Apache-2.0" ]
null
null
null
kernel-module/ethosn_firmware.h
ARM-software/npu-driver-stack
1e6b00b21ed4cf39b2df625fa242c6f67c05b19f
[ "Apache-2.0" ]
null
null
null
/* * * (C) COPYRIGHT 2018-2022 Arm Limited. * * This program is free software and is provided to you under the terms of the * GNU General Public License version 2 as published by the Free Software * Foundation, and any use by you of this program is subject to the terms * of such GNU licence. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, you can access it online at * http://www.gnu.org/licenses/gpl-2.0.html. * * SPDX-License-Identifier: GPL-2.0-only * */ #ifndef _ETHOSN_FIRMWARE_H_ #define _ETHOSN_FIRMWARE_H_ /* This file defines structs using zero-length arrays which are not available * in the C++ standard. The compilers we use do however support them as * extensions to the standard, so we can disable the warnings they produce. * Disabling of warnings is compiler-specific. */ #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4200) #endif #include "uapi/ethosn_shared.h" #ifdef __KERNEL__ #include <linux/types.h> #else #include <stdint.h> #endif /** * Version information * * This is common for the fat binary (ethosn.bin) and the individual * firmware binaries (sub-components of the fat binary). */ #define ETHOSN_FIRMWARE_VERSION_MAJOR 4 #define ETHOSN_FIRMWARE_VERSION_MINOR 0 #define ETHOSN_FIRMWARE_VERSION_PATCH 0 /** Max length of a cache line. Used to separate host and Ethos-N data. */ #define ETHOSN_CACHE_LINE_SIZE 128 /* Stack size */ #define ETHOSN_STACK_SIZE 0x40000 #pragma pack(push, 1) /****************************************************************************** * Mailbox ******************************************************************************/ /** * Pointer to memory that will be accessed directly by the MCU should be 32 bit. * * Pointer to memory that will be copied with help of DMA may be up to 49 bits. */ typedef uint64_t ethosn_address_t; /** * struct ethosn_queue - Dynamic size queue designed to be written from * one CPU and read from another. * @var capacity: Size in bytes of the queue. * @var read: Read index in bytes in the Data array. * The "reading" CPU advances this as it reads data from the * queue. * It should never read past the 'write' offset as that means * the end of the queue has been reached and it should wait * for the writing end to write some more data. * @var write: Write index in bytes in the Data array. * The "writing" CPU advances this as it writes data into the * queue. * It should never write past the 'read' pointer as that means * the queue has become full and it should wait for the reading * end to catch up. * @var data: Data array. * * * The queue is empty if-and-only-if: read == write. * Note that the queue can never be completely full, as that would be * indistinguishable from being empty! */ struct ethosn_queue { union { struct { uint32_t capacity; uint32_t read; }; /* Padding added to avoid caching issues between non-coherent * CPUs. */ uint8_t pad_0[ETHOSN_CACHE_LINE_SIZE]; }; union { uint32_t write; /* Padding added to avoid caching issues between non-coherent * CPUs. */ uint8_t pad_1[ETHOSN_CACHE_LINE_SIZE]; }; uint8_t data[]; }; /** * Checks if data of the given size could ever fit in the queue, even * if it was completely empty. This is a simple check against the capacity, * but is wrapped in a function as the comparison is slightly different * to what you might naively expect. */ static inline bool ethosn_queue_can_ever_fit(const struct ethosn_queue *queue, uint32_t size) { /* Note we disallow the queue from ever becoming * completely full, as that would be indistinguishable from being * completely empty! */ return size < queue->capacity; } /** * Gets the current size of the given queue, i.e. how many bytes are available * to read. */ static inline uint32_t ethosn_queue_get_size(const struct ethosn_queue *queue) { const uint32_t mask = queue->capacity - 1; return (queue->write - queue->read) & mask; } /** * Gets the amount of free space in the given queue, i.e. how many bytes can be * written. */ static inline uint32_t ethosn_queue_get_free_space( const struct ethosn_queue *queue) { /* Note we subtract one to prevent the queue from ever becoming * completely full, as that would be indistinguishable from being * completely empty! */ return queue->capacity - ethosn_queue_get_size(queue) - 1; } /** * Skips the given number of bytes from the queue. This is equivalent to reading * those bytes and discarding them. * Returns false if there is not enough data in the queue to skip. */ static inline bool ethosn_queue_skip(struct ethosn_queue *queue, uint8_t size) { const uint32_t mask = queue->capacity - 1; /* Check that there is enough data for us to read */ if (size > ethosn_queue_get_size(queue)) return false; queue->read = (queue->read + size) & mask; return true; } /** * Reads the given number of bytes from the queue. * Returns false if there is not enough data in the queue to read. */ static inline bool ethosn_queue_read(struct ethosn_queue *queue, uint8_t *dst, uint32_t size) { const uint32_t mask = queue->capacity - 1; uint32_t read = queue->read; uint32_t i; /* Check that there is enough data for us to read */ if (size > ethosn_queue_get_size(queue)) return false; for (i = 0; i < size; ++i) { dst[i] = queue->data[read]; read = (read + 1) & mask; } queue->read = read; return true; } /** * Writes the given buffers of bytes to the queue. * The caller is required to commit the out_write_pending pointer * to queue->write when they have ensured that the payload is * readable (e.g. flushed) by the "reading" CPU. * Returns false if there is not enough free space in the queue. * @buffers: Array of length num_buffers, each element is a pointer to a * buffer to be written to the queue. * @sizes: Array of length num_buffers, each element is the length of the * corrresponding buffer in @buffers */ static inline bool ethosn_queue_write(struct ethosn_queue *queue, const uint8_t *const *buffers, const uint32_t *sizes, uint32_t num_buffers, uint32_t *out_write_pending) { const uint32_t mask = queue->capacity - 1; uint32_t write = queue->write; uint32_t i, j; uint32_t total_bytes = 0; /* Check if there is enough space for our data */ for (i = 0; i < num_buffers; ++i) total_bytes += sizes[i]; if (ethosn_queue_get_free_space(queue) < total_bytes) return false; /* Write each buffer, one after the other */ for (i = 0; i < num_buffers; ++i) for (j = 0; j < sizes[i]; ++j) { queue->data[write] = buffers[i][j]; write = (write + 1) & mask; } *out_write_pending = write; return true; } /** * struct ethosn_mailbox - Mailbox structure * @var request: Pointer to message queue going from host to Ethos-N . * @var response: Pointer to message queue going from Ethos-N to host. * @var severity: Log severity level. @see ethosn_log_severity. * * This is the interface between the host and the Ethos-N . */ struct ethosn_mailbox { ethosn_address_t request; ethosn_address_t response; uint32_t severity; }; /****************************************************************************** * Message types ******************************************************************************/ /** * Message types. */ enum ethosn_message_type { /* The order of the message type matters for the enriched RTL testing * system. Inference request and response must not change to avoid * problems. */ /* ethosn_message_inference_request */ ETHOSN_MESSAGE_INFERENCE_REQUEST, /* ethosn_message_inference_response */ ETHOSN_MESSAGE_INFERENCE_RESPONSE, /* ethosn_message_text */ ETHOSN_MESSAGE_TEXT, /* ethosn_firmware_profiling_configuration */ ETHOSN_MESSAGE_CONFIGURE_PROFILING, /* void */ ETHOSN_MESSAGE_CONFIGURE_PROFILING_ACK, /* ethosn_message_region_request */ ETHOSN_MESSAGE_REGION_REQUEST, /* ethosn_message_region_response */ ETHOSN_MESSAGE_REGION_RESPONSE, /* ethosn_message_time_sync_request */ ETHOSN_MESSAGE_TIME_SYNC, /* uint32_t */ ETHOSN_MESSAGE_DELAY, /* void */ ETHOSN_MESSAGE_MPU_ENABLE_REQUEST, ETHOSN_MESSAGE_MPU_ENABLE_RESPONSE, ETHOSN_MESSAGE_PING, ETHOSN_MESSAGE_PONG, ETHOSN_MESSAGE_FW_HW_CAPS_REQUEST, ETHOSN_MESSAGE_FW_HW_CAPS_RESPONSE, ETHOSN_MESSAGE_STASH_REQUEST, ETHOSN_MESSAGE_ERROR_RESPONSE, ETHOSN_MESSAGE_MAX }; /** * struct ethosn_message_header - Message header * @var type: Message type. @see ethosn_message_type. * @var length: Length in bytes of Value array. * * Every message between host and Ethos-N should begin with a message header. * The type of the message determines if the header is followed by additional * payload data. */ struct ethosn_message_header { uint32_t type; uint32_t length; uint8_t value[]; }; /****************************************************************************** * Inference ******************************************************************************/ /** * struct ethosn_buffer_desc - Buffer descriptor * @var address: Pointer to buffer. * @var size: Size in bytes of buffer. */ struct ethosn_buffer_desc { ethosn_address_t address; uint32_t size; }; /** * struct ethosn_buffer_array - Dynamic size buffer array * @var num_buffers: Number of buffers. * @var buffers: Array of buffer descriptors. */ struct ethosn_buffer_array { uint32_t num_buffers; struct ethosn_buffer_desc buffers[]; }; /** * Inference status. */ enum ethosn_inference_status { ETHOSN_INFERENCE_STATUS_OK, ETHOSN_INFERENCE_STATUS_ERROR, ETHOSN_INFERENCE_STATUS_MAX }; /** * struct ethosn_message_inference_request - Inference request message * @var user_argument: User argument. * @var buffer_array: Pointer to buffer array. @see ethosn_buffer_header. * * Following a ethosn_message_header. */ struct ethosn_message_inference_request { uint64_t user_argument; ethosn_address_t buffer_array; }; /** * struct ethosn_message_inference_response - Inference response message * @var user_argument: User argument. * @var status: Inference status. * * Following a ethosn_message_header. */ struct ethosn_message_inference_response { uint64_t user_argument; uint32_t status; }; /****************************************************************************** * Text message logging ******************************************************************************/ /** * Severity of log message. */ enum ethosn_log_severity { ETHOSN_LOG_PANIC, ETHOSN_LOG_ERROR, ETHOSN_LOG_WARNING, ETHOSN_LOG_INFO, ETHOSN_LOG_DEBUG, ETHOSN_LOG_VERBOSE }; /** * struct ethosn_message_text - Text message * @var severity: Severity of log message. * * Following a ethosn_message_type. */ struct ethosn_message_text { uint32_t severity; char text[]; }; /****************************************************************************** * Profiling ******************************************************************************/ /** * Max number of hardware profiling counters */ #define ETHOSN_PROFILING_MAX_HW_COUNTERS 6U /** * struct ethosn_firmware_profiling_configuration - Message payload sent to the * firmware for a ETHOSN_MESSAGE_CONFIGURE_PROFILING message. Describes the * profiling configuration that the firmware should set itself to. * * @buffer_address: Firmware-accessible address to a struct of type * ethosn_profiling_buffer which is where the firmware should * write its profiling data. */ struct ethosn_firmware_profiling_configuration { bool enable_profiling; ethosn_address_t buffer_address; uint32_t buffer_size; uint32_t num_hw_counters; enum ethosn_profiling_hw_counter_types hw_counters[ETHOSN_PROFILING_MAX_HW_COUNTERS]; }; /** * struct ethosn_profiling_buffer - Layout of the firmware's profiling buffer. * This is a circular buffer which the firmware writes into and the kernel * reads from. When the firmware reaches the end, it simply starts * overwriting at the beginning again. There is no mechanism in place to * prevent the firmware from overwriting data which the kernel has not yet * read. * This is intentional as we do not want to stall the firmware waiting for * the kernel (especially as there may not be anyone reading the profiling * data at the other side!). * * @firmware_write_index: Index into the entries array that the firmware * should write to next. This is updated by the firmware * and read-only for the kernel. * @entries: Payload of the buffer. */ struct ethosn_profiling_buffer { union { uint32_t firmware_write_index; /* Padding to ensure firmware_write_index and entries are on * different cache lines, so flushing is independent. */ uint8_t padding[ETHOSN_CACHE_LINE_SIZE]; }; struct ethosn_profiling_entry entries[]; }; /** * struct ethosn_message_profiling_entries - Profiling entries message * @num_entries: Number of entries. * @entries: @see ethosn_profiling_entry. * * Following a ethosn_message_type. */ struct ethosn_message_profiling_entries { uint32_t num_entries; struct ethosn_profiling_entry entries[]; }; /** * struct ethosn_message_time_sync_request - Message sync request * @var timestamp: Application processor timestamp * * Following a ethosn_message_type. */ struct ethosn_message_time_sync_request { uint64_t timestamp; }; /****************************************************************************** * Memory regions management ******************************************************************************/ /** * Region identifier */ enum ethosn_region_id { ETHOSN_REGION_FIRMWARE = 0, ETHOSN_REGION_WORKING_DATA_MAIN = 1, ETHOSN_REGION_WORKING_DATA_TASK = 2, ETHOSN_REGION_COMMAND_STREAM = 3, }; /** * struct ethosn_message_region_request - Memory region message * @var id: Region id * @var addr: Region starting address * @var size: Region size * * Following a ethosn_message_type. */ struct ethosn_message_region_request { uint32_t id; uint32_t addr; uint32_t size; }; /** * Region setup status. */ enum ethosn_region_status { ETHOSN_REGION_STATUS_OK, ETHOSN_REGION_STATUS_ERROR, ETHOSN_REGION_STATUS_MAX }; /** * struct ethosn_message_region_response - Memory region response message * @var id: Region id * @var status: Memory region setup status * * Following a ethosn_message_header. */ struct ethosn_message_region_response { uint32_t id; uint32_t status; }; /****************************************************************************** * Error reporting ******************************************************************************/ /** * Request error status */ enum ethosn_error_status { ETHOSN_ERROR_STATUS_INVALID_STATE, ETHOSN_ERROR_STATUS_INVALID_MESSAGE, ETHOSN_ERROR_STATUS_FAILED, ETHOSN_ERROR_STATUS_MAX }; /** * struct ethosn_message_error_response - Error response message * @var type: Message type the error occured for * @var status: General error status * * Following a ethosn_message_header. */ struct ethosn_message_error_response { uint32_t type; uint32_t status; }; /* * Define the DL1_GP registers to be used for special purpose communication * between kernel driver and firmware */ #define GP_IRQ DL1_GP0 #define GP_MMUSID0 DL1_GP1 #define GP_MAILBOX DL1_GP2 #define GP_STREAM1_ADDRESS_EXTEND DL1_GP3 #define GP_STREAM2_ADDRESS_EXTEND DL1_GP4 #define GP_TASK_STACK DL1_GP5 #pragma pack(pop) #if defined(_MSC_VER) #pragma warning(pop) #endif #endif /* _ETHOSN_FIRMWARE_H_ */
27.887372
80
0.670542
0e3b2203a9dcfdac71ef1cbbfa1338c4004d5ba2
2,566
h
C
src/ripple/protocol/SOTemplate.h
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
5
2019-01-23T04:36:03.000Z
2020-02-04T07:10:39.000Z
src/ripple/protocol/SOTemplate.h
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
null
null
null
src/ripple/protocol/SOTemplate.h
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
2
2019-05-14T07:26:59.000Z
2020-06-15T07:25:01.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //———————————————————————————————————————————————————————————————————————————————————————————————————————————————— /* 此文件是Rippled的一部分:https://github.com/ripple/rippled 版权所有(c)2012,2013 Ripple Labs Inc. 使用、复制、修改和/或分发本软件的权限 特此授予免费或不收费的目的,前提是 版权声明和本许可声明出现在所有副本中。 本软件按“原样”提供,作者不作任何保证。 关于本软件,包括 适销性和适用性。在任何情况下,作者都不对 任何特殊、直接、间接或后果性损害或任何损害 因使用、数据或利润损失而导致的任何情况,无论是在 合同行为、疏忽或其他侵权行为 或与本软件的使用或性能有关。 **/ //============================================================== #ifndef RIPPLE_PROTOCOL_SOTEMPLATE_H_INCLUDED #define RIPPLE_PROTOCOL_SOTEMPLATE_H_INCLUDED #include <ripple/protocol/SField.h> #include <boost/range.hpp> #include <memory> namespace ripple { /*sotemplate中元素的标志。*/ //vvalco注意到这些看起来不像位标记… enum SOE_Flags { SOE_INVALID = -1, SOE_REQUIRED = 0, //必修的 SOE_OPTIONAL = 1, //可选,可以使用默认值显示 SOE_DEFAULT = 2, //可选,如果存在,则不能有默认值 }; //———————————————————————————————————————————————————————————————————————————————————————————————————————————————— /*sotemplate中的元素。*/ class SOElement { public: SField const& e_field; SOE_Flags const flags; SOElement (SField const& fieldName, SOE_Flags flags) : e_field (fieldName) , flags (flags) { } }; //———————————————————————————————————————————————————————————————————————————————————————————————————————————————— /*定义对象中的字段及其属性。 serializedObject的每个子类都将提供自己的模板 描述可用字段及其元数据属性。 **/ class SOTemplate { public: using list_type = std::vector <std::unique_ptr <SOElement const>>; using iterator_range = boost::iterator_range<list_type::const_iterator>; /*创建空模板。 创建模板后,使用 期望字段。 “见推后背” **/ SOTemplate () = default; SOTemplate(SOTemplate&& other) : mTypes(std::move(other.mTypes)) , mIndex(std::move(other.mIndex)) { } /*提供字段的枚举*/ iterator_range all () const { return boost::make_iterator_range(mTypes); } /*此模板中的条目数*/ std::size_t size () const { return mTypes.size (); } /*向模板中添加元素。*/ void push_back (SOElement const& r); /*检索命名字段的位置。*/ int getIndex (SField const&) const; SOE_Flags style(SField const& sf) const { return mTypes[mIndex[sf.getNum()]]->flags; } private: list_type mTypes; std::vector <int> mIndex; //字段编号->索引 }; } //涟漪 #endif
20.693548
114
0.547935
e06f7a790c4fd6e0ccee69f2783327a467b2bc23
1,479
h
C
tensorflow_serving/model_servers/test_util/storage_path_error_injecting_source_adapter.h
mzhang-code/serving
527c6f2173eba584ebdca4f8b11ae3c0550ab1a9
[ "Apache-2.0" ]
5,791
2016-02-16T17:50:06.000Z
2022-03-31T11:53:10.000Z
tensorflow_serving/model_servers/test_util/storage_path_error_injecting_source_adapter.h
mzhang-code/serving
527c6f2173eba584ebdca4f8b11ae3c0550ab1a9
[ "Apache-2.0" ]
1,618
2016-02-16T18:04:00.000Z
2022-03-30T07:24:28.000Z
tensorflow_serving/model_servers/test_util/storage_path_error_injecting_source_adapter.h
mzhang-code/serving
527c6f2173eba584ebdca4f8b11ae3c0550ab1a9
[ "Apache-2.0" ]
2,501
2016-02-16T19:57:43.000Z
2022-03-27T02:43:49.000Z
/* Copyright 2016 Google 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. ==============================================================================*/ #ifndef TENSORFLOW_SERVING_MODEL_SERVERS_TEST_UTIL_STORAGE_PATH_ERROR_INJECTING_SOURCE_ADAPTER_H_ #define TENSORFLOW_SERVING_MODEL_SERVERS_TEST_UTIL_STORAGE_PATH_ERROR_INJECTING_SOURCE_ADAPTER_H_ #include "tensorflow_serving/core/source_adapter.h" namespace tensorflow { namespace serving { namespace test_util { // An ErrorInjectingSourceAdapter<StoragePath, std::unique_ptr<Loader>> (see // source_adapter.h) registered in StoragePathSourceAdapterRegistry and keyed on // StoragePathErrorInjectingSourceAdapterConfig. using StoragePathErrorInjectingSourceAdapter = ErrorInjectingSourceAdapter<StoragePath, std::unique_ptr<Loader>>; } // namespace test_util } // namespace serving } // namespace tensorflow #endif // TENSORFLOW_SERVING_MODEL_SERVERS_TEST_UTIL_STORAGE_PATH_ERROR_INJECTING_SOURCE_ADAPTER_H_
41.083333
100
0.787018
0d40898ba6655ef97d2c18de9ac7e88292502b07
264
c
C
err/err_except.c
hapejot/hape_c
764b3abaa7156b788131375433c6dd3a2a176e1d
[ "Apache-2.0" ]
null
null
null
err/err_except.c
hapejot/hape_c
764b3abaa7156b788131375433c6dd3a2a176e1d
[ "Apache-2.0" ]
null
null
null
err/err_except.c
hapejot/hape_c
764b3abaa7156b788131375433c6dd3a2a176e1d
[ "Apache-2.0" ]
null
null
null
#include "err.h" #include <stdio.h> #include <setjmp.h> #include <stdbool.h> static jmp_buf _exitbuf; void err_throw( ERR_LOG_ENTRY *entry ) { err_log_add( entry ); longjmp( _exitbuf, true ); } bool err_catch(){ return (bool)setjmp( _exitbuf ); }
14.666667
40
0.670455
0d8a7b011b00b494e5fd44187712e45ecbb9be79
1,561
h
C
src/types/types.h
mprammer2/hustle
f1dbbe672d54ee79b863d11710c2854c6d62af29
[ "Apache-2.0" ]
null
null
null
src/types/types.h
mprammer2/hustle
f1dbbe672d54ee79b863d11710c2854c6d62af29
[ "Apache-2.0" ]
null
null
null
src/types/types.h
mprammer2/hustle
f1dbbe672d54ee79b863d11710c2854c6d62af29
[ "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. #ifndef HUSTLE_SRC_TYPES_TYPES_H_ #define HUSTLE_SRC_TYPES_TYPES_H_ #include <better-enums/enum.h> namespace hustle { namespace types { BETTER_ENUM(ComparativeType, int, NE, EQ, GT, LE, LT, GE) BETTER_ENUM(ArithmeticType, int, PLUS, MINUS, STAR, SLASH) BETTER_ENUM(AggFuncType, int, AVG, COUNT, SUM) BETTER_ENUM(ExprType, int, ColumnReference, IntLiteral, StrLiteral, Comparative, Disjunctive, Conjunctive, Arithmetic, AggFunc) BETTER_ENUM(QueryOperatorType, int, TableReference, Select, Project, Join, Aggregate, OrderBy) BETTER_ENUM(OrderByDirection, int, ASC, DESC) // TODO(Lichengxi): to add more BETTER_ENUM(PlanType, int, Query, Create) } // namespace types } // namespace hustle #endif // HUSTLE_SRC_TYPES_TYPES_H_
33.934783
80
0.755926
ef76a154249ac75854b29bdf7ea8b18fc51adef1
1,837
h
C
src/common/sockets/SocketClient.h
Samsung/cynara
be455dcaf1400bec0272a6ce90852b9147393a60
[ "Apache-2.0" ]
22
2015-05-19T08:33:30.000Z
2022-02-27T02:19:32.000Z
src/common/sockets/SocketClient.h
Samsung/cynara
be455dcaf1400bec0272a6ce90852b9147393a60
[ "Apache-2.0" ]
10
2015-05-07T19:01:54.000Z
2016-07-07T07:37:37.000Z
src/common/sockets/SocketClient.h
Samsung/cynara
be455dcaf1400bec0272a6ce90852b9147393a60
[ "Apache-2.0" ]
23
2015-02-28T21:31:58.000Z
2020-04-23T02:25:37.000Z
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd 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 */ /** * @file src/common/sockets/SocketClient.h * @author Lukasz Wojciechowski <l.wojciechow@partner.samsung.com> * @version 1.0 * @brief This file contains definition of cynara's socket client */ #ifndef SRC_COMMON_SOCKETS_SOCKETCLIENT_H_ #define SRC_COMMON_SOCKETS_SOCKETCLIENT_H_ #include <memory> #include <string> #include <containers/BinaryQueue.h> #include <protocol/Protocol.h> #include <request/pointers.h> #include <response/pointers.h> #include <sockets/Socket.h> namespace Cynara { class SocketClient; typedef std::shared_ptr<SocketClient> SocketClientPtr; class SocketClient { private: Socket m_socket; ProtocolPtr m_protocol; BinaryQueuePtr m_readQueue; BinaryQueuePtr m_writeQueue; public: SocketClient(const std::string &socketPath, ProtocolPtr protocol); virtual ~SocketClient() {}; bool connect(void); bool isConnected(void); //returns pointer to response // or nullptr when connection to cynara service is lost ResponsePtr askCynaraServer(const Request &request); bool sendAndForget(const Request &request); }; } // namespace Cynara #endif /* SRC_COMMON_SOCKETS_SOCKETCLIENT_H_ */
28.703125
76
0.734894
89192604dd3f3d074b68716678728e038752ab6c
10,373
h
C
pioneer/net/net_pools.h
galaxyeye/pioneer
cfc3aa3c4917b19000753ea3144bded79380d289
[ "Apache-2.0" ]
4
2017-05-12T07:37:17.000Z
2019-11-14T10:52:28.000Z
pioneer/net/net_pools.h
galaxyeye/pioneer
cfc3aa3c4917b19000753ea3144bded79380d289
[ "Apache-2.0" ]
null
null
null
pioneer/net/net_pools.h
galaxyeye/pioneer
cfc3aa3c4917b19000753ea3144bded79380d289
[ "Apache-2.0" ]
7
2017-06-21T03:35:51.000Z
2020-10-14T04:58:26.000Z
/* * net_pools.h * * Created on: Jul 22, 2013 * Author: vincent */ /* Copyright 2011 ~ 2013 Vincent Zhang, ivincent.zhang@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PIONEER_NET_POOLS_H_ #define PIONEER_NET_POOLS_H_ #include <string> #include <atomic> #include <map> #include <mutex> #include <condition_variable> #include <boost/bind.hpp> #include <boost/ptr_container/ptr_map.hpp> #include <glog/logging.h> #include <atlas/singleton.h> #include <atlas/container/blocking_concurrent_box.h> #include <muduo/net/EventLoop.h> #include <muduo/net/EventLoopThreadPool.h> #include <muduo/net/TcpClient.h> #include <muduo/net/TcpConnection.h> #include <pioneer/net/net_error.h> namespace pioneer { namespace net { namespace mn = muduo::net; template<typename pool_tag> class connection_pool : public atlas::singleton<connection_pool<pool_tag>> { public: const uint64_t default_wait_time = 60 * 1000; // 1 minute typedef std::map<std::string, mn::TcpConnectionPtr>::const_iterator iterator; private: friend class atlas::singleton<connection_pool<pool_tag>>; connection_pool(connection_pool&)= delete; connection_pool& operator=(const connection_pool&)= delete; public: // TODO : make it private connection_pool() : _connections(std::chrono::microseconds(default_wait_time)) {} // take a connection and remove it from the pool mn::TcpConnectionPtr take(const std::string& ip_port) { DLOG(INFO) << "take connection for" << ip_port; return *_connections.take(ip_port); } mn::TcpConnectionPtr random_take() { return *_connections.random_take(); } void put(const mn::TcpConnectionPtr& conn) { auto ip_port = conn->peerAddress().toIpPort(); _connections.put(ip_port, conn); DLOG(INFO) << "put " << ip_port << ", pool size : " << _connections.size(); } void erase(const std::string& ip_port) { _connections.erase(ip_port); DLOG(INFO) << "pool size : " << _connections.size(); } void clear() { _connections.clear(); } bool empty() const { return _connections.empty(); } size_t size() const { return _connections.size(); } private: atlas::blocking_concurrent_box<std::string, mn::TcpConnectionPtr> _connections; }; // we may need several different TCP client pool singletons, so we make it a template // for example, if we need a catalog server in the cluster template<typename pool_tag> class tcp_client_pool : public atlas::singleton<tcp_client_pool<pool_tag>> { private: friend class atlas::singleton<tcp_client_pool<pool_tag>>; tcp_client_pool(tcp_client_pool&)= delete; tcp_client_pool& operator=(const tcp_client_pool&)= delete; typedef boost::ptr_multimap<std::string, mn::TcpClient> tcp_client_container; public: // TODO : make it private tcp_client_pool() : _stopping(false), _stopped(false), _thread_num(1), _server_port(0), _base_loop(nullptr) {} /// init/deinit section public: ~tcp_client_pool() = default; void set_server_port(unsigned short server_port) { _server_port = server_port; } void set_thread_num(int num) { _thread_num = num; } void set_connection_callback(const mn::ConnectionCallback& cb) { _on_connection = cb; } void set_message_callback(const mn::MessageCallback& cb) { _on_message = cb; } void set_write_complete_callback(const mn::WriteCompleteCallback& cb) { _on_write_complete = cb; } void init() { _base_loop = new mn::EventLoop; // all the loops in the thread pool will stop if the base loop quits _io_thread_pool.reset(new mn::EventLoopThreadPool(_base_loop)); if (_thread_num) _io_thread_pool->setThreadNum(_thread_num); } void start() { _io_thread_pool->start(); _base_loop->loop(); } void stop() { if (_stopping || _stopped) return; _stopping = true; _base_loop->runInLoop(boost::bind(&tcp_client_pool::do_stop, this)); } /// data structure access section public: void erase(const std::string& peer_ip_port) { std::lock_guard<std::mutex> guard(_tcp_client_pool_mutex); _tcp_client_pool.erase(peer_ip_port); } size_t size() const { std::lock_guard<std::mutex> guard(_tcp_client_pool_mutex); return _tcp_client_pool.size(); } bool empty() const { std::lock_guard<std::mutex> guard(_tcp_client_pool_mutex); return _tcp_client_pool.empty(); } /// network functionality section public: /* * Thread safe * */ void connect(const std::string& target_ip) noexcept { _base_loop->runInLoop(boost::bind(&tcp_client_pool::do_connect, this, target_ip)); } /* * Thread safe * */ void disconnect(const std::string& target_ip) noexcept { _base_loop->runInLoop(boost::bind(&tcp_client_pool::do_disconnect, this, target_ip)); } /* * Thread safe * */ void refresh(const std::string& target_ip) noexcept { _base_loop->runInLoop(boost::bind(&tcp_client_pool::do_refresh, this, target_ip)); } /* * Thread safe * */ void disconnect_all() noexcept { _base_loop->runInLoop(boost::bind(&tcp_client_pool::do_disconnect_all, this)); } /* * Thread safe * */ void refresh_all() noexcept { _base_loop->runInLoop(boost::bind(&tcp_client_pool::do_refresh_all, this)); } void destroy() { _destroyed_cv.notify_one(); } protected: void do_stop() { LOG(INFO) << "stopping client pool, please wait..."; // client side half-close, which means the write channel is closed, // but the socket file descriptor is not closed by system call close(2) yet. // it's still possible to receive data from the socket after disconnect is called, // until the server side closes the socket file descriptor by close(2) do_disconnect_all(); // wait until all connections raised by TcpClient are disconnected, and then // we can safely destroy all the connections std::unique_lock<std::mutex> lock(_destroyed_mutex); // TODO : avoid hard coding _destroyed_cv.wait_for(lock, std::chrono::seconds(30), [this]() { return _tcp_client_pool.empty(); }); if (!_tcp_client_pool.empty()) { LOG(INFO) << "force disconnect " << _tcp_client_pool.size() << " connections"; _tcp_client_pool.clear(); } // quit all sub loops and threads _io_thread_pool.reset(); // quit the loop and exit client pool thread _base_loop->quit(); LOG(INFO) << "inner client pool stopped"; _stopped = true; } void do_connect(const std::string& target_ip) { if (_stopping) { LOG(INFO) << "sorry, have a rest"; return; } // DLOG(INFO) << "try establish a connection " << system::context::local_ip << " -> " << target_ip; mn::InetAddress server_address(target_ip, _server_port); std::string name = std::string("tcp_client_") + std::to_string(_tcp_client_pool.size()); mn::TcpClient* client = new mn::TcpClient(_io_thread_pool->getNextLoop(), server_address, name); client->setConnectionCallback(_on_connection); client->setMessageCallback(_on_message); client->setWriteCompleteCallback(_on_write_complete); client->connect(); std::string peer_ip_port = server_address.toIpPort(); // DLOG(INFO) << "save the TcpClient for server : " << peer_ip_port; std::lock_guard<std::mutex> guard(_tcp_client_pool_mutex); _tcp_client_pool.insert(peer_ip_port, client); } void do_disconnect(const std::string& target_ip) { std::lock_guard<std::mutex> guard(_tcp_client_pool_mutex); auto it = _tcp_client_pool.find(target_ip); if (it != _tcp_client_pool.end()) { it->second->disconnect(); } } void do_refresh(const std::string& target_ip) { std::lock_guard<std::mutex> guard(_tcp_client_pool_mutex); auto it = _tcp_client_pool.find(target_ip); if (it != _tcp_client_pool.end()) { it->second->disconnect(); it->second->connect(); } } void do_disconnect_all() { std::lock_guard<std::mutex> guard(_tcp_client_pool_mutex); typedef typename tcp_client_container::reference reference; std::for_each(_tcp_client_pool.begin(), _tcp_client_pool.end(), [this](reference v) { v.second->disconnect(); }); } void do_refresh_all() { std::lock_guard<std::mutex> guard(_tcp_client_pool_mutex); typedef typename tcp_client_container::reference reference; std::for_each(_tcp_client_pool.begin(), _tcp_client_pool.end(), [this](reference v) { v.second->disconnect(); v.second->connect(); }); } private: std::atomic<bool> _stopping; std::atomic<bool> _stopped; int _thread_num; unsigned short _server_port; mn::EventLoop* _base_loop; std::shared_ptr<mn::EventLoopThreadPool> _io_thread_pool; mn::ConnectionCallback _on_connection; mn::MessageCallback _on_message; mn::WriteCompleteCallback _on_write_complete; mutable std::mutex _tcp_client_pool_mutex; tcp_client_container _tcp_client_pool; mutable std::mutex _destroyed_mutex; std::condition_variable _destroyed_cv; }; } // net } // pioneer #endif /* NET_POOLS_H_ */
30.872024
116
0.647643
a6a721d5fc8743e3920870a75b5500e178b254e5
5,883
c
C
solvers/bns/src/bnsError.c
lcw/libparanumal
9c0f46b25ad6fe127ff49fc6cf75cf6cb4944322
[ "MIT" ]
null
null
null
solvers/bns/src/bnsError.c
lcw/libparanumal
9c0f46b25ad6fe127ff49fc6cf75cf6cb4944322
[ "MIT" ]
null
null
null
solvers/bns/src/bnsError.c
lcw/libparanumal
9c0f46b25ad6fe127ff49fc6cf75cf6cb4944322
[ "MIT" ]
1
2019-11-24T17:23:29.000Z
2019-11-24T17:23:29.000Z
/* The MIT License (MIT) Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "bns.h" // TW: this needs to be tidied up // currently maximum void bnsError(bns_t *bns, dfloat time, setupAide &options){ bns->o_q.copyTo(bns->q); mesh_t *mesh = bns->mesh; // dfloat time = 0.0; // if(options.compareArgs("TIME INTEGRATOR","MRSAAB")) // time = bns->startTime + bns->dt*tstep*pow(2,(mesh->MRABNlevels-1)); // else // time = bns->startTime + tstep*bns->dt; if(bns->probeFlag){ // int rank; // MPI_Comm_rank(mesh->comm, &rank); // // printf("Rank: %d has %d probes elements\n", rank, mesh->probeN); // if(mesh->probeN){ // char fname[BUFSIZ]; // sprintf(fname, "ProbeData_%d_%.f_%05d_%04d_%02d.dat", mesh->N, bns->Re, mesh->Nelements, rank, bns->Ntscale); // FILE *fp; // fp = fopen(fname, "a"); // fprintf(fp, "%2d %.4e %4e ", mesh->N, bns->Re, time); // for(int p=0; p<mesh->probeN; p++){ // int pid = mesh->probeIds[p]; // int e = mesh->probeElementIds[p]; // dfloat srho = 0.0; // dfloat su = 0.0; // dfloat sv = 0.0; // for(int n=0; n<mesh->Np; n++){ // dfloat rho = bns->q[bns->Nfields*(n + e*mesh->Np) + 0]; // dfloat um = bns->q[bns->Nfields*(n + e*mesh->Np) + 1]*bns->sqrtRT/rho; // dfloat vm = bns->q[bns->Nfields*(n + e*mesh->Np) + 2]*bns->sqrtRT/rho; // // srho += mesh->probeI[p*mesh->Np+n]*rho*bns->RT; // srho += mesh->probeI[p*mesh->Np+n]*rho; // su += mesh->probeI[p*mesh->Np+n]*um; // sv += mesh->probeI[p*mesh->Np+n]*vm; // } // fprintf(fp, "%02d %04d %.8e %.8e %.8e ",pid, e, srho, su, sv); // } // fprintf(fp, "\n"); // fclose(fp); // } } if(bns->outputForceStep) bnsForces(bns,time,options); if(options.compareArgs("ABSORBING LAYER","PML")){ dfloat maxQ1 = 0, minQ1 = 1e9 , minQ3 = 1e9; int fid = 0; // for(dlong e=0;e<mesh->Nelements;++e){ for(int n=0;n<mesh->Np;++n){ dfloat q1=0, x=0. , y=0., z=0.; const dlong id = n+e*mesh->Np*bns->Nfields; maxQ1 = mymax(maxQ1, fabs(bns->q[id + fid*mesh->Np])); minQ1 = mymin(minQ1, fabs(bns->q[id + fid*mesh->Np])); } } // compute maximum over all processes dfloat globalMaxQ1, globalMinQ1; MPI_Allreduce(&maxQ1, &globalMaxQ1, 1, MPI_DFLOAT, MPI_MAX, mesh->comm); MPI_Allreduce(&minQ1, &globalMinQ1, 1, MPI_DFLOAT, MPI_MIN, mesh->comm); if(mesh->rank==0) printf("%g %g %g (time,min(density),max(density)\n", time, globalMinQ1, globalMaxQ1); if(isnan(globalMinQ1) || isnan(globalMaxQ1)) exit(EXIT_FAILURE); } else{ // // Coutte Flow exact solution for U velocity // dfloat maxerr = 0, maxQ1 = 0, minQ1 = 1e9; // int fid = 1; // dfloat Uref = bns->Ma*bns->sqrtRT; // dfloat nu = bns->sqrtRT*bns->sqrtRT/bns->tauInv; // for(int e=0;e<mesh->Nelements;++e){ // for(int n=0;n<mesh->Np;++n){ // dfloat q1=0; // int id = n+e*mesh->Np; // dfloat x = mesh->x[id]; // dfloat y = mesh->y[id]; // // U = sqrt(RT)*Q2/Q1; // dfloat u = bns->sqrtRT*bns->q[id*bns->Nfields + 1]/bns->q[id*bns->Nfields+0]; // dfloat uex = y ; // for(int k=1; k<=10; k++) // { // dfloat lamda = k*M_PI; // // dfloat coef = -bns->RT*bns->tauInv/2. + sqrt(pow((bns->RT*bns->tauInv),2) /4.0 - (lamda*lamda*bns->RT*bns->RT)); // dfloat coef = -bns->tauInv/2. + bns->tauInv/2* sqrt(1.- 4.*pow(1./ bns->tauInv, 2)* bns->RT* lamda*lamda); // uex += 2.*pow(-1,k)/(lamda)*exp(coef*time)*sin(lamda*y); // // // uex += 2.*pow(-1,k)/(lamda)*exp(-nu*lamda*lamda*time)*sin(lamda*y); // !!!!! // } // maxerr = mymax(maxerr, fabs(u-uex)); // bns->q[id*bns->Nfields+2] = fabs(u-uex); // maxQ1 = mymax(maxQ1, fabs(bns->q[id*bns->Nfields])); // minQ1 = mymin(minQ1, fabs(bns->q[id*bns->Nfields])); // } // } // // compute maximum over all processes // dfloat globalMaxQ1, globalMinQ1, globalMaxErr; // MPI_Allreduce(&maxQ1, &globalMaxQ1, 1, MPI_DFLOAT, MPI_MAX, mesh->comm); // MPI_Allreduce(&minQ1, &globalMinQ1, 1, MPI_DFLOAT, MPI_MIN, mesh->comm); // MPI_Allreduce(&maxerr, &globalMaxErr, 1, MPI_DFLOAT, MPI_MAX, mesh->comm); // int rank; // MPI_Comm_rank(mesh->comm, &rank); // if(rank==0){ // printf("%g %g %g %g (time,min(density),max(density),max(error)\n", time, globalMinQ1, globalMaxQ1, globalMaxErr); // } // if(isnan(globalMaxErr)) // exit(EXIT_FAILURE); } }
32.324176
127
0.574027
a6b96660c448af712602eb9fb804f4cec99b9713
416
h
C
HXSafeTimer/HXSafeTimer.h
yiyucanglang/HXKitComponent
766d874dc06ed8365b0d02b20e0f1dcb6a01cf76
[ "MIT" ]
null
null
null
HXSafeTimer/HXSafeTimer.h
yiyucanglang/HXKitComponent
766d874dc06ed8365b0d02b20e0f1dcb6a01cf76
[ "MIT" ]
null
null
null
HXSafeTimer/HXSafeTimer.h
yiyucanglang/HXKitComponent
766d874dc06ed8365b0d02b20e0f1dcb6a01cf76
[ "MIT" ]
null
null
null
// // HXSafeTimer.h // ParentDemo // // Created by James on 2019/5/15. // Copyright © 2019 DaHuanXiong. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface HXSafeTimer : NSObject + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo; @end NS_ASSUME_NONNULL_END
21.894737
159
0.769231
e694fe9d41ad491ec5a6f4d375399fa015aa3035
226
w
C
examples/proc_rec_fac.w
BakerSmithA/while2wasm
6d60c51b7ecdeaf98ca8c79f7bd47bc469493487
[ "MIT" ]
null
null
null
examples/proc_rec_fac.w
BakerSmithA/while2wasm
6d60c51b7ecdeaf98ca8c79f7bd47bc469493487
[ "MIT" ]
null
null
null
examples/proc_rec_fac.w
BakerSmithA/while2wasm
6d60c51b7ecdeaf98ca8c79f7bd47bc469493487
[ "MIT" ]
null
null
null
begin var n := 6; var r := 1; proc fac is ( if !n=1 then ( r := r * n; n := n - 1; call fac ) else ( skip ) ); call fac; export r end
15.066667
27
0.309735
61fccb0219d9eaaa427d8118b7c8be7ae8f98876
3,970
c
C
drivers/keyboard/keyboard.c
coldnine/alpha
03586b834f8b16861364126647c42ae1b2b7c0ca
[ "MIT" ]
8
2018-05-09T11:27:17.000Z
2022-01-28T11:37:06.000Z
drivers/keyboard/keyboard.c
coldnine/proxima
03586b834f8b16861364126647c42ae1b2b7c0ca
[ "MIT" ]
null
null
null
drivers/keyboard/keyboard.c
coldnine/proxima
03586b834f8b16861364126647c42ae1b2b7c0ca
[ "MIT" ]
1
2018-01-05T09:44:57.000Z
2018-01-05T09:44:57.000Z
#include "../keyboard.h" #define SC_MAX 57 bool can_type = false; enum KEYCODE { BACKSPACE_PRESSED = 0x0e, ENTER_PRESSED = 0x1c, LSHIFT_PRESSED = 0x2a, LSHIFT_RELEASED = 0xaa, RSHIFT_PRESSED = 0x36, RSHIFT_RELEASED = 0xb6, CAPSLOCK_PRESSED = 0x3a, CAPSLOCK_RELEASED = 0xba, SPACEBAR_PRESSED = 0x39, SPACEBAR_RELEASED = 0xb9, ALT_PRESSED = 0x38, ALT_RELEASED = 0xb8, CTRL_PRESSED = 0x1d, CTRL_RELEASED = 0x9d }; static char keycache[256]; struct { bool lshift; bool rshift; bool capslock; bool spacebar; bool ctrl; bool alt; } kbd_pressed; const char *sc_name[] = { "ERROR", "Esc", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "Backspace", "Tab", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "Enter", "Lctrl", "A", "S", "D", "F", "G", "H", "J", "K", "L", ";", "'", "`", "LShift", "\\", "Z", "X", "C", "V", "B", "N", "M", ",", ".", "/", "RShift", "Keypad *", "LAlt", "Spacebar" }; const char sc_uppercase[] = { '?', '?', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '?', '?', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', '?', '?', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', '\'', '`', '?', '\\', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', '?', '?', '?', ' ' }; const char sc_lowercase[] = { '?', '?', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '?', '?', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '?', '?', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', '`', '?', '\\', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', '?', '?', '?', ' ' }; bool should_use_uppercase() { return (kbd_pressed.lshift | kbd_pressed.rshift) ^ kbd_pressed.capslock; } static void clear_keycache() { for (int i = 0; i < 256; i++) { keycache[i] = 0x00; } } static void append_key_to_cache(char letter) { char *key = keycache; while (*key) { key++; } *key = letter; } void backspace() { char *key = keycache; while (*key) { key++; } if (key != keycache) { *(--key) = 0x00; backwards_cursor(); update_cursor(cursor_row, cursor_col); } } static void keyboard_callback(registers_t regs) { // PIC leaves scancode in port 0x60 u8 scancode = port_byte_in(0x60); char letter; switch (scancode) { // shift case LSHIFT_PRESSED: kbd_pressed.lshift = true; break; case LSHIFT_RELEASED: kbd_pressed.lshift = false; break; case RSHIFT_PRESSED: kbd_pressed.rshift = true; break; case RSHIFT_RELEASED: kbd_pressed.rshift = false; break; // space bar case SPACEBAR_PRESSED: print_char(' '); update_cursor(cursor_row, cursor_col); append_key_to_cache(' '); kbd_pressed.spacebar = true; break; case SPACEBAR_RELEASED: kbd_pressed.spacebar = false; break; // caps lock case CAPSLOCK_PRESSED: kbd_pressed.capslock = !kbd_pressed.capslock; break; // ctrl case CTRL_PRESSED: kbd_pressed.ctrl = true; break; case CTRL_RELEASED: kbd_pressed.ctrl = false; break; // alt case ALT_PRESSED: kbd_pressed.alt = true; break; case ALT_RELEASED: kbd_pressed.alt = false; break; case BACKSPACE_PRESSED: backspace(); break; // enter case ENTER_PRESSED: printf("\n"); int result = execute_command(keycache); clear_keycache(); break; default: if (can_type && scancode < SC_MAX) { letter = should_use_uppercase() ? sc_uppercase[(int)scancode] : sc_lowercase[(int)scancode]; append_key_to_cache(letter); print_char(letter); update_cursor(cursor_row, cursor_col); } break; } } void init_keyboard() { memset(&kbd_pressed, false, sizeof(kbd_pressed)); clear_keycache(); register_interrupt_handler(IRQ1, (isr_t)keyboard_callback); }
21.576087
100
0.522418
f8097c9085dad92e6006dee08755d5874ec103a2
1,370
c
C
gempak/source/cgemlib/crg/crgsarec.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
42
2015-06-03T15:26:21.000Z
2022-02-28T22:36:03.000Z
gempak/source/cgemlib/crg/crgsarec.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
60
2015-05-11T21:36:08.000Z
2022-03-29T16:22:42.000Z
gempak/source/cgemlib/crg/crgsarec.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
27
2016-06-06T21:55:14.000Z
2022-03-18T18:23:28.000Z
#include "crgcmn.h" void crg_sarec ( int elnum, int assocRec, int *iret ) /************************************************************************ * crg_sarec * * * * This function sets up a one-way linkage between two range records * * for an element. * * * * void crg_clear ( elnum, assocRec, iret ) * * * * Input parameters: * * elnum int Element number * * assocRec int Range record to be linked to * * * * Output parameters: * * *iret int Return code * * -2 = Element is out of bounds * * * * Log: * * J. Wu/SAIC 07/07 initial coding * ***********************************************************************/ { *iret = 0; if ( elnum < 0 || elnum >= MAX_EDITABLE_ELEMS ) { *iret = -2; } else { range[elnum].assocRec = assocRec; } }
39.142857
73
0.277372
fd47f93be6c19d10f838a4014566bdb8dfff5ca6
302
h
C
Example/SlideOutMenu/ExampleAppDelegate.h
holiday/SlideOutMenu
332bcec25a6a9c90444d63d59d18c5c7c532fd0c
[ "MIT" ]
null
null
null
Example/SlideOutMenu/ExampleAppDelegate.h
holiday/SlideOutMenu
332bcec25a6a9c90444d63d59d18c5c7c532fd0c
[ "MIT" ]
null
null
null
Example/SlideOutMenu/ExampleAppDelegate.h
holiday/SlideOutMenu
332bcec25a6a9c90444d63d59d18c5c7c532fd0c
[ "MIT" ]
null
null
null
// // SlidableAppDelegate.h // SlideOutMenu // // Created by CocoaPods on 12/17/2014. // Copyright (c) 2014 rashaad ramdeen. All rights reserved. // #import <UIKit/UIKit.h> @interface ExampleAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
18.875
67
0.731788
74e0769f9d798b796673ea5e0e7f00d3a3b4b6e4
1,154
h
C
Headers/Frameworks/Flexo/FFShareDestinationVideoResolutionMenuMakerPublishing.h
CommandPost/FinalCutProFrameworks
d98b00ff0c84af80942d71514e9238d624aca50a
[ "MIT" ]
3
2020-11-19T10:04:02.000Z
2021-10-02T17:25:21.000Z
Headers/Frameworks/Flexo/FFShareDestinationVideoResolutionMenuMakerPublishing.h
CommandPost/FinalCutProFrameworks
d98b00ff0c84af80942d71514e9238d624aca50a
[ "MIT" ]
null
null
null
Headers/Frameworks/Flexo/FFShareDestinationVideoResolutionMenuMakerPublishing.h
CommandPost/FinalCutProFrameworks
d98b00ff0c84af80942d71514e9238d624aca50a
[ "MIT" ]
null
null
null
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 11 2021 20:53:35). // // Copyright (C) 1997-2019 Steve Nygard. // #import <Flexo/FFShareDestinationVideoResolutionMenuMaker.h> __attribute__((visibility("hidden"))) @interface FFShareDestinationVideoResolutionMenuMakerPublishing : FFShareDestinationVideoResolutionMenuMaker { } - (id)enabledVideoResolutions; - (id)enabledVideoResolution; - (void)addMenuItemForCurrentlyEnabledVideoResolution; - (id)menuItemTitleWithVideoResolution:(struct CGSize)arg1; - (void)addMenuItemForVideoResolution:(id)arg1 withDisplaySize:(struct CGSize)arg2; - (id)potentialVideoResolutionConverter; - (struct CGSize)convertPotentialToActualVideoResolution:(struct CGSize)arg1; - (id)optimalVideoResolutionDeterminer; - (struct CGSize)optimalVideoResolution; - (BOOL)isHighResolutionSource; - (BOOL)shouldIncludeMenuItemWithDisplaySize:(struct CGSize)arg1; - (void)addMenuItemsForVideoResolutions:(id)arg1; - (id)videoResolutions; - (void)populateMenuWithHeterogeneousAspectRatios; - (void)populateMenuWithHomogeneousAspectRatios; - (BOOL)hasHomogeneousAspectRatios; - (void)populateMenu; @end
33.941176
108
0.817158
dd61cff5c94e9429b885411f789f0f54badd47ca
757
h
C
kongxia/Views/Home/rent/page/ZZRentPageNavigationView.h
zuwome/kongxia
87f6f33410da1fedd315089c9a92917b5226125d
[ "MIT" ]
null
null
null
kongxia/Views/Home/rent/page/ZZRentPageNavigationView.h
zuwome/kongxia
87f6f33410da1fedd315089c9a92917b5226125d
[ "MIT" ]
1
2022-01-08T05:58:03.000Z
2022-01-08T05:58:03.000Z
kongxia/Views/Home/rent/page/ZZRentPageNavigationView.h
zuwome/kongxia
87f6f33410da1fedd315089c9a92917b5226125d
[ "MIT" ]
null
null
null
// // ZZRentPageNavigationView.h // zuwome // // Created by angBiu on 16/8/2. // Copyright © 2016年 zz. All rights reserved. // #import <UIKit/UIKit.h> /** * 他人页导航栏 */ @interface ZZRentPageNavigationView : UIView @property (nonatomic, strong) UIView *bgView; @property (nonatomic, strong) UIImageView *leftImgView; @property (nonatomic, strong) UIImageView *rightImgView; @property (nonatomic, strong) UIImageView *codeImgView; @property (nonatomic, strong) UILabel *titleLabel; @property (nonatomic, weak) UIViewController *ctl; @property (nonatomic, strong) ZZUser *user; @property (nonatomic, strong) UIButton *codeBtn; @property (nonatomic, copy) dispatch_block_t touchLeftBtn; @property (nonatomic, copy) dispatch_block_t touchRightBtn; @end
27.035714
59
0.754293
1c0bfc5c3a664439c06df54ba694835845b05807
1,050
c
C
src/string/hexdump.c
robsware/kadimus
642c247218700099defbdedff22e021ff385afba
[ "MIT" ]
428
2015-03-14T22:42:20.000Z
2020-04-19T03:56:06.000Z
src/string/hexdump.c
robsware/kadimus
642c247218700099defbdedff22e021ff385afba
[ "MIT" ]
13
2015-03-30T18:48:25.000Z
2020-04-12T20:59:53.000Z
src/string/hexdump.c
robsware/kadimus
642c247218700099defbdedff22e021ff385afba
[ "MIT" ]
131
2015-03-17T16:12:45.000Z
2020-03-17T10:47:01.000Z
#include "hexdump.h" #include <string.h> #include <stdio.h> static const unsigned char hextable[]="0123456789abcdef"; void hexdump(void *data, size_t len, int squeez) { char hex[69], *prev = NULL; unsigned ch; size_t i = 0, total, hexoffset, choffset; int asterisk = 0; while (i < len) { hexoffset = 11; choffset = 52; sprintf(hex, "%08x:", (unsigned int)i); memset(hex + 9, ' ', 43); total = i + 16; if (total > len) { total = len; } else if (squeez && prev) { if (memcmp(prev, (char *)data + i, 16) == 0x0) { prev = (char *)data + i; i += 16; if (!asterisk) { puts("*"); asterisk = 1; } continue; } else { asterisk = 0; } } prev = (char *)data + i; while (i < total) { ch = ((unsigned char *)data)[i]; hex[choffset++] = (ch > ' ' && ch <= '~') ? ch : '.'; hex[hexoffset++] = hextable[ch / 16]; hex[hexoffset++] = hextable[ch % 16]; if (i % 2) hexoffset++; i++; } hex[choffset] = 0x0; puts(hex); } printf("%08x\n", (unsigned int)i); }
16.666667
57
0.528571
c1f8824320566c229539f2cb073ddd6388fa5230
394
c
C
2. Decimal to Octal.c
Nikhil-1920/Number-System-Conversion
e46139b70e0104a6af5642599e0efe90c05dbedd
[ "MIT" ]
null
null
null
2. Decimal to Octal.c
Nikhil-1920/Number-System-Conversion
e46139b70e0104a6af5642599e0efe90c05dbedd
[ "MIT" ]
null
null
null
2. Decimal to Octal.c
Nikhil-1920/Number-System-Conversion
e46139b70e0104a6af5642599e0efe90c05dbedd
[ "MIT" ]
null
null
null
// Decimal to octal conversion #include <stdio.h> int main(void) { int i = 0, j = 0, num, octal[20]; printf("\nEnter decimal number: "); scanf("%d", &num); while(num > 0) { octal[i] = num % 8; i++; num /= 8; } printf("Octal number is: "); for(j = i - 1; j >= 0; j--) printf("%d", octal[j]); printf("\n\n"); return 0; }
18.761905
39
0.454315
ea113ec5b15c09949804881db9ba04cd05cd4718
804
h
C
System/Library/PrivateFrameworks/HomeUI.framework/HUItemTableViewScrollDestination.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
12
2019-06-02T02:42:41.000Z
2021-04-13T07:22:20.000Z
System/Library/PrivateFrameworks/HomeUI.framework/HUItemTableViewScrollDestination.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/HomeUI.framework/HUItemTableViewScrollDestination.h
lechium/iPhoneOS_12.1.1_Headers
aac688b174273dfcbade13bab104461f463db772
[ "MIT" ]
3
2019-06-11T02:46:10.000Z
2019-12-21T14:58:16.000Z
/* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:49:41 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/HomeUI.framework/HomeUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ @class HFItem; @interface HUItemTableViewScrollDestination : NSObject { BOOL _animated; HFItem* _item; } @property (nonatomic,readonly) HFItem * item; //@synthesize item=_item - In the implementation block @property (getter=isAnimated,nonatomic,readonly) BOOL animated; //@synthesize animated=_animated - In the implementation block -(id)initWithItem:(id)arg1 animated:(BOOL)arg2 ; -(HFItem *)item; -(BOOL)isAnimated; @end
30.923077
139
0.721393
7cbfcad65ece86ae71659480bec4a41c569c58df
36,817
h
C
original/IntelliKeys/WindowsOld/Control Panel/REALbasic Plugin and bundle/QT6/Interfaces & Libraries/QTDevWin/CIncludes/NSL.h
ATMakersBill/OpenIKeys
629f88a35322245c623f59f387cc39a2444f02c4
[ "MIT" ]
11
2017-10-24T16:46:14.000Z
2021-02-20T13:11:35.000Z
original/IntelliKeys/WindowsOld/Control Panel/REALbasic Plugin and bundle/QT6/Interfaces & Libraries/QTDevWin/CIncludes/NSL.h
ATMakersBill/OpenIKeys
629f88a35322245c623f59f387cc39a2444f02c4
[ "MIT" ]
7
2017-11-03T22:30:12.000Z
2021-01-15T02:51:07.000Z
original/IntelliKeys/WindowsOld/Control Panel/REALbasic Plugin and bundle/QT6/Interfaces & Libraries/QTDevWin/CIncludes/NSL.h
ATMakersBill/OpenIKeys
629f88a35322245c623f59f387cc39a2444f02c4
[ "MIT" ]
4
2018-02-23T09:58:50.000Z
2019-03-06T02:46:55.000Z
/* File: NSL.h Contains: Interface to API for using the NSL Manager Version: Technology: Mac OS 8.5 Release: QuickTime 6.0.2 Copyright: (c) 1985-2001 by Apple Computer, Inc., all rights reserved Bugs?: For bug reports, consult the following page on the World Wide Web: http://developer.apple.com/bugreporter/ */ #ifndef __NSL__ #define __NSL__ #ifndef __CODEFRAGMENTS__ #include <CodeFragments.h> #endif #ifndef __EVENTS__ #include <Events.h> #endif #ifndef __THREADS__ #include <Threads.h> #endif #ifndef __MACERRORS__ #include <MacErrors.h> #endif #if PRAGMA_ONCE #pragma once #endif #ifdef __cplusplus extern "C" { #endif #if PRAGMA_IMPORT #pragma import on #endif #if PRAGMA_STRUCT_ALIGN #pragma options align=mac68k #elif PRAGMA_STRUCT_PACKPUSH #pragma pack(push, 2) #elif PRAGMA_STRUCT_PACK #pragma pack(2) #endif enum { kNSLMinSystemVersion = 0x0900, /* equivalent to 9.0*/ kNSLMinOTVersion = 0x0130 /* equivalent to 1.3*/ }; enum { kNSLDefaultListSize = 256 /* default list size for service and protocol lists*/ }; enum { kNSLURLDelimiter = ',' /* delimits URL's within memory buffers*/ }; #define kNSLErrorNoErr {noErr, kNSLNoContext} /* an initializer for the NSLError struct */ enum { kNSLNoContext = 0 /* the default context for NSLError structs*/ }; struct NSLError { OSStatus theErr; UInt32 theContext; }; typedef struct NSLError NSLError; typedef NSLError * NSLErrorPtr; enum { /* Constants to use with NSLPrepareRequest*/ /* kNSLDuplicateSearchInProgress is not strictly an error. The client is free to ignore*/ /* this result, and nothing bad will happen if it does. It is*/ /* informational only.*/ kNSLDuplicateSearchInProgress = 100, kNSLUserCanceled = userCanceledErr, /* User hit cancel from the NSLStandardGetURL dialog */ /* Invalid enumeratorRef */ kNSLInvalidEnumeratorRef = 0 /* this is not an error; it is the equiv to a NULL ptr*/ }; typedef UInt16 NSLSearchState; enum { /* State codes for notifiers.*/ kNSLSearchStateBufferFull = 1, kNSLSearchStateOnGoing = 2, kNSLSearchStateComplete = 3, kNSLSearchStateStalled = 4, kNSLWaitingForContinue = 5 }; typedef UInt32 NSLEventCode; enum { /* Event codes*/ kNSLServicesLookupDataEvent = 6, kNSLNeighborhoodLookupDataEvent = 7, kNSLNewDataEvent = 8, kNSLContinueLookupEvent = 9 }; typedef UInt32 NSLClientRef; typedef UInt32 NSLRequestRef; typedef UInt32 NSLOneBasedIndex; typedef char * NSLPath; typedef char * NSLServiceType; typedef Handle NSLServicesList; typedef unsigned char * NSLNeighborhood; /* cstring which is a comma delimited list of protocols which can be used to create a NSLProtocolList internally */ typedef UInt32 NSLDialogOptionFlags; enum { kNSLDefaultNSLDlogOptions = 0x00000000, /* use defaults for all the options */ kNSLNoURLTEField = 0x00000001 /* don't show url text field for manual entry */ }; struct NSLDialogOptions { UInt16 version; NSLDialogOptionFlags dialogOptionFlags; /* option flags for affecting the dialog's behavior */ Str255 windowTitle; Str255 actionButtonLabel; /* label of the default button (or null string for default) */ Str255 cancelButtonLabel; /* label of the cancel button (or null string for default) */ Str255 message; /* custom message prompt (or null string for default) */ }; typedef struct NSLDialogOptions NSLDialogOptions; /* the async information block for client<->manager interaction*/ struct NSLClientAsyncInfo { void * clientContextPtr; /* set by the client for its own use*/ void * mgrContextPtr; /* set by NSL mgr; ptr to request object ptr*/ char * resultBuffer; long bufferLen; long maxBufferSize; UInt32 startTime; /* when the search starts, to use with maxSearchTime to determine time-out condition*/ UInt32 intStartTime; /* used with alertInterval*/ UInt32 maxSearchTime; /* total time for search, in ticks (0 == no time limit)*/ UInt32 alertInterval; /* call client's notifier or return, every this many ticks ( 0 == don't use this param)*/ UInt32 totalItems; /* total number of tuples currently in buffer*/ UInt32 alertThreshold; /* call client's notifier or return, every this many items found ( 0 == don't use this param)*/ NSLSearchState searchState; NSLError searchResult; NSLEventCode searchDataType; /* this is a data type code which allows the client's asyncNotifier to properly*/ /* handle the data in resultBuffer.*/ }; typedef struct NSLClientAsyncInfo NSLClientAsyncInfo; typedef NSLClientAsyncInfo * NSLClientAsyncInfoPtr; /* the async information block plugin<->manager interaction*/ struct NSLPluginAsyncInfo { void * mgrContextPtr; /* set by NSL mgr; ptr to request object ptr*/ void * pluginContextPtr; /* set/used by individual plugins*/ void * pluginPtr; /* ptr to the plugin object waiting for continue lookup call*/ char * resultBuffer; /* set by plugin to point at data*/ long bufferLen; long maxBufferSize; UInt32 maxSearchTime; /* total time for search, in ticks (0 == no time limit)*/ UInt32 reserved1; UInt32 reserved2; UInt32 reserved3; NSLClientRef clientRef; NSLRequestRef requestRef; NSLSearchState searchState; OSStatus searchResult; }; typedef struct NSLPluginAsyncInfo NSLPluginAsyncInfo; typedef NSLPluginAsyncInfo * NSLPluginAsyncInfoPtr; /* the mgr asynchronous notifier routine.*/ typedef CALLBACK_API( void , NSLMgrNotifyProcPtr )(NSLPluginAsyncInfo *thePluginAsyncInfo); /* the client asynchronous notifier routine.*/ typedef CALLBACK_API( void , NSLClientNotifyProcPtr )(NSLClientAsyncInfo *theClientAsyncInfo); typedef STACK_UPP_TYPE(NSLMgrNotifyProcPtr) NSLMgrNotifyUPP; typedef STACK_UPP_TYPE(NSLClientNotifyProcPtr) NSLClientNotifyUPP; #if OPAQUE_UPP_TYPES EXTERN_API(NSLMgrNotifyUPP) NewNSLMgrNotifyUPP (NSLMgrNotifyProcPtr userRoutine); EXTERN_API(NSLClientNotifyUPP) NewNSLClientNotifyUPP (NSLClientNotifyProcPtr userRoutine); EXTERN_API(void) DisposeNSLMgrNotifyUPP (NSLMgrNotifyUPP userUPP); EXTERN_API(void) DisposeNSLClientNotifyUPP (NSLClientNotifyUPP userUPP); EXTERN_API(void) InvokeNSLMgrNotifyUPP (NSLPluginAsyncInfo * thePluginAsyncInfo, NSLMgrNotifyUPP userUPP); EXTERN_API(void) InvokeNSLClientNotifyUPP (NSLClientAsyncInfo * theClientAsyncInfo, NSLClientNotifyUPP userUPP); #else enum { uppNSLMgrNotifyProcInfo = 0x000000C0 }; /* pascal no_return_value Func(4_bytes) */ enum { uppNSLClientNotifyProcInfo = 0x000000C0 }; /* pascal no_return_value Func(4_bytes) */ #define NewNSLMgrNotifyUPP(userRoutine) (NSLMgrNotifyUPP)NewRoutineDescriptor((ProcPtr)(userRoutine), uppNSLMgrNotifyProcInfo, GetCurrentArchitecture()) #define NewNSLClientNotifyUPP(userRoutine) (NSLClientNotifyUPP)NewRoutineDescriptor((ProcPtr)(userRoutine), uppNSLClientNotifyProcInfo, GetCurrentArchitecture()) #define DisposeNSLMgrNotifyUPP(userUPP) DisposeRoutineDescriptor(userUPP) #define DisposeNSLClientNotifyUPP(userUPP) DisposeRoutineDescriptor(userUPP) #define InvokeNSLMgrNotifyUPP(thePluginAsyncInfo, userUPP) CALL_ONE_PARAMETER_UPP((userUPP), uppNSLMgrNotifyProcInfo, (thePluginAsyncInfo)) #define InvokeNSLClientNotifyUPP(theClientAsyncInfo, userUPP) CALL_ONE_PARAMETER_UPP((userUPP), uppNSLClientNotifyProcInfo, (theClientAsyncInfo)) #endif /* support for pre-Carbon UPP routines: NewXXXProc and CallXXXProc */ #define NewNSLMgrNotifyProc(userRoutine) NewNSLMgrNotifyUPP(userRoutine) #define NewNSLClientNotifyProc(userRoutine) NewNSLClientNotifyUPP(userRoutine) #define CallNSLMgrNotifyProc(userRoutine, thePluginAsyncInfo) InvokeNSLMgrNotifyUPP(thePluginAsyncInfo, userRoutine) #define CallNSLClientNotifyProc(userRoutine, theClientAsyncInfo) InvokeNSLClientNotifyUPP(theClientAsyncInfo, userRoutine) /* this struct is a format for dealing with our internal data representation. Typed data will be contiguous chunk of memory, with the first 4 bytes being a data "descriptor". */ struct NSLTypedData { unsigned long dataType; unsigned long lengthOfData; /* void* theData; */ }; typedef struct NSLTypedData NSLTypedData; typedef NSLTypedData * NSLTypedDataPtr; #define kNSLDataType 'NSL_' /* This is just a header at the beginning of a handle that stores our list of service types. Each service type is a pascal string, so each service type starts after the end of the previous one. */ struct NSLServicesListHeader { unsigned long numServices; unsigned long logicalLen; /* length of all usable data in handle*/ /* Ptr firstService; */ }; typedef struct NSLServicesListHeader NSLServicesListHeader; typedef NSLServicesListHeader * NSLServicesListHeaderPtr; /* some defs for common protocols*/ #define kSLPProtocolType "SLP" #define kDNSProtocolType "DNS" #define kLDAPProtocolType "LDAP" #define kNBPProtocolType "NBP" /* general information from a plug-in. Includes supported protocols, data types and services, as well as an info/comment string describing the function of the plug-in in human-readable form. The offsets point to the beginning of each list of data returned, and the protocol data offset is the startOfData member of the struct */ struct NSLPluginData { long reserved1; long reserved2; long reserved3; Boolean supportsRegistration; Boolean isPurgeable; UInt16 totalLen; /* length of everything, including header*/ UInt16 dataTypeOffset; UInt16 serviceListOffset; UInt16 protocolListOffset; UInt16 commentStringOffset; /* char* startOfData; */ /* protocol data is first on the list*/ }; typedef struct NSLPluginData NSLPluginData; typedef NSLPluginData * NSLPluginDataPtr; /* ----------------------------------------------------------------------------- Finding out if the library is present and getting its version ----------------------------------------------------------------------------- */ EXTERN_API( UInt32 ) NSLLibraryVersion (void); #ifdef __cplusplus inline pascal Boolean NSLLibraryPresent() { return NSLLibraryVersion != (void*)kUnresolvedCFragSymbolAddress; } #else #define NSLLibraryPresent() ((NSLLibraryVersion != (void*)kUnresolvedCFragSymbolAddress)) #endif typedef CALLBACK_API( Boolean , NSLURLFilterProcPtr )(char *url, Str255 displayString)/* optional filter function */; /* you can provide for calls to NSLStandardGetURL*/ typedef CALLBACK_API( void , NSLEventProcPtr )(EventRecord *newEvent, void *userContext)/* optional callback routine for getting Events while the dialog is up */; typedef STACK_UPP_TYPE(NSLURLFilterProcPtr) NSLURLFilterUPP; typedef STACK_UPP_TYPE(NSLEventProcPtr) NSLEventUPP; #if OPAQUE_UPP_TYPES EXTERN_API(NSLURLFilterUPP) NewNSLURLFilterUPP (NSLURLFilterProcPtr userRoutine); EXTERN_API(NSLEventUPP) NewNSLEventUPP (NSLEventProcPtr userRoutine); EXTERN_API(void) DisposeNSLURLFilterUPP (NSLURLFilterUPP userUPP); EXTERN_API(void) DisposeNSLEventUPP (NSLEventUPP userUPP); EXTERN_API(Boolean) InvokeNSLURLFilterUPP (char * url, Str255 displayString, NSLURLFilterUPP userUPP); EXTERN_API(void) InvokeNSLEventUPP (EventRecord * newEvent, void * userContext, NSLEventUPP userUPP); #else enum { uppNSLURLFilterProcInfo = 0x000003D0 }; /* pascal 1_byte Func(4_bytes, 4_bytes) */ enum { uppNSLEventProcInfo = 0x000003C0 }; /* pascal no_return_value Func(4_bytes, 4_bytes) */ #define NewNSLURLFilterUPP(userRoutine) (NSLURLFilterUPP)NewRoutineDescriptor((ProcPtr)(userRoutine), uppNSLURLFilterProcInfo, GetCurrentArchitecture()) #define NewNSLEventUPP(userRoutine) (NSLEventUPP)NewRoutineDescriptor((ProcPtr)(userRoutine), uppNSLEventProcInfo, GetCurrentArchitecture()) #define DisposeNSLURLFilterUPP(userUPP) DisposeRoutineDescriptor(userUPP) #define DisposeNSLEventUPP(userUPP) DisposeRoutineDescriptor(userUPP) #define InvokeNSLURLFilterUPP(url, displayString, userUPP) (Boolean)CALL_TWO_PARAMETER_UPP((userUPP), uppNSLURLFilterProcInfo, (url), (displayString)) #define InvokeNSLEventUPP(newEvent, userContext, userUPP) CALL_TWO_PARAMETER_UPP((userUPP), uppNSLEventProcInfo, (newEvent), (userContext)) #endif /* support for pre-Carbon UPP routines: NewXXXProc and CallXXXProc */ #define NewNSLURLFilterProc(userRoutine) NewNSLURLFilterUPP(userRoutine) #define NewNSLEventProc(userRoutine) NewNSLEventUPP(userRoutine) #define CallNSLURLFilterProc(userRoutine, url, displayString) InvokeNSLURLFilterUPP(url, displayString, userRoutine) #define CallNSLEventProc(userRoutine, newEvent, userContext) InvokeNSLEventUPP(newEvent, userContext, userRoutine) /* ----------------------------------------------------------------------------- High level API calls: the following two calls are ALL an application needs to register/deregister its service. If you use these, you don't need to make any of the other calls to NSLAPI (including NSLOpenNavigationAPI) ----------------------------------------------------------------------------- */ /* <--- error code from registration */ /* ---> urlToRegister is a null terminated url that has only legal characters defined for URLs. Use HexEncodeText to encode*/ /* portions of the url that have illegal characters */ /* ---> neighborhoodToRegisterIn is an optional parameter for explicitly defining a neighborhood to register in. If parameter is NULL, then the plugins will determine where to register the service */ EXTERN_API( NSLError ) NSLStandardRegisterURL (NSLPath urlToRegister, NSLNeighborhood neighborhoodToRegisterIn) /* can be NULL */; /* <--- error code from registration */ /* ---> urlToRegister is a null terminated url that has only legal characters defined for URLs. Use HexEncodeText to encode*/ /* portions of the url that have illegal characters */ /* ---> neighborhoodToDeregisterIn is an optional parameter for explicitly defining a neighborhood to register in. If parameter is NULL, then the plugins will determine where to register the service */ EXTERN_API( NSLError ) NSLStandardDeregisterURL (NSLPath urlToDeregister, NSLNeighborhood neighborhoodToDeregisterIn) /* can be NULL */; /* <--- function returns OSStatus of the operation. noErr will be returned if valid, kNSLUserCanceled will be returned if the user cancels */ /* ---> dialogOptions */ /* ---> eventProc */ /* ---> eventProcContextPtr */ /* ---> filterProc */ /* ---> serviceTypeList */ /* <--- userSelectedURL */ /* NSLDialogOptions* dialogOptions */ /* dialogOptions is a user defined structure defining the look, feel and operation of NSLStandardGetURL dialog default behavior can be achieved by passing in a pointer to a structure that has been filled out by a previous call to NSLGetDefaultDialogOptions or by passing in NULL. */ /* NSLEventUPP eventProc */ /* the eventProc is a callback NSLURLFilterUPP that will get called with Events that the dialog doesn't handle. If you pass in nil, you won't get update events while the NSLStandardGetURL dialog is open. */ /* void* eventProcContextPtr */ /* you can provide a pointer to some contextual data that you want to have sent to your eventProc filter*/ /* NSLURLFilterProcPtr filterProc */ /* the filter param is a callback NSLURLFilterUPP that will get called (if not nil) for each url that is going to be displayed in the dialog's result list. A result of false will not include the url for the user to select from. You also have the option of handling the way the url looks in the dialog listing by copying the preferred name into the displayString parameter. (If left alone, NSLStandardGetURL dialog will strip the service type portion off the url). */ /* char* serviceTypeList */ /* the serviceTypeList parameter is a null terminated string that will directly affect the contents of the services popup in the dialog. The structure of this string is a set of tuples as follows: Name of ServiceType as to be represented in the popup followed by a comma delimted list of service descriptors (ie http,https) that will used in the search of that type. Each comma delimited tuple is delimited by semi-colons. */ /* For example: If you want to search for services of type http (web), https (secure web), and ftp, you could pass in the string "Web Servers,http,https;FTP Servers,ftp". This would result in a popup list with two items ("Web Servers" and "FTP Servers") and searches performed on them will provide results of type http and https for the first, and ftp for the second. */ /* Results list Icons: NSLStandardGetURL provides icons in its listings for the following types: "http", "https", "ftp", "afp", "lpr", "LaserWriter", "AFPServer" any other types will get a generic icon. However, you can provide icons if you wish by including an '#ics8' resource id at the end of your comma delimited list. The dialog will then use that icon if found in its results list. This icon will be used for all types in a tuple. For example: The param "Web Servers,http,https;Telnet Servers,telnet;NFS Servers,nfs,129" would result in lists of http and https services to be shown with their default icons, telnet servers would be shown with the default misc. icon and nfs servers would be shown with your icon at resource id 129. */ /* char** url */ /* pass in the address of a char* and it will point to the resulting url. If the user cancels (the function returns false), the pointer will be set to nil. If the function returns true (user selected a url), then you must call NSLFreeURL on the pointer when you are done with it. */ /* Call this to have the user select a url based service from a dialog. Function takes on input an optional filter proc, a serviceTypeList, and an address to a Ptr. Function sets the value of the Ptr to a newly created c-style null terminated string containing the user's choice of URL. */ EXTERN_API( OSStatus ) NSLStandardGetURL (NSLDialogOptions * dialogOptions, /* can be NULL */ NSLEventUPP eventProc, /* can be NULL */ void * eventProcContextPtr, /* can be NULL */ NSLURLFilterUPP filterProc, /* can be NULL */ char * serviceTypeList, char ** userSelectedURL); /*-----------------------------------------------------------------------------*/ EXTERN_API( OSStatus ) NSLHexEncodeText (const char * rawText, UInt16 rawTextLen, char * newTextBuffer, UInt16 * newTextBufferLen, Boolean * textChanged); EXTERN_API( OSStatus ) NSLHexDecodeText (const char * encodedText, UInt16 encodedTextLen, char * decodedTextBuffer, UInt16 * decodedTextBufferLen, Boolean * textChanged); EXTERN_API( OSStatus ) NSLGetDefaultDialogOptions (NSLDialogOptions * dialogOptions); /* <--- function returns null (useful for setting variable at same time as freeing it */ /* ---> url is memory created by a call to NSLStandardGetURL */ EXTERN_API( char *) NSLFreeURL (char * url); /* ----------------------------------------------------------------------------- Basic API Utility calls: sufficient to create, and parse data structures ----------------------------------------------------------------------------- */ EXTERN_API( NSLServicesList ) NSLMakeNewServicesList (const char * initialServiceList); EXTERN_API( NSLError ) NSLAddServiceToServicesList (NSLServicesList serviceList, NSLServiceType serviceType); EXTERN_API( void ) NSLDisposeServicesList (NSLServicesList theList); /* The name reflects the name of the Neighborhood, i.e. "apple.com." or "AppleTalk Zone One". The protocolList is a comma delimited list of protocols that the Neighborhood might exist in. If the user passes in NULL, then all protocols will be queried. The result must be disposed of by the user by calling NSLFreeNeighborhood. */ EXTERN_API( NSLNeighborhood ) NSLMakeNewNeighborhood (const char * name, const char * protocolList) /* can be NULL */; /* creates an exact copy of an existing neighborhood */ EXTERN_API( NSLNeighborhood ) NSLCopyNeighborhood (NSLNeighborhood neighborhood); EXTERN_API( NSLNeighborhood ) NSLFreeNeighborhood (NSLNeighborhood neighborhood); EXTERN_API( void ) NSLGetNameFromNeighborhood (NSLNeighborhood neighborhood, char ** name, long * length); /* create a block of formatted data, pointed to by newDataPtr. This will be used in calls (typically request-related calls) for plug-ins that handle the NSL data type. */ EXTERN_API( OSStatus ) NSLMakeServicesRequestPB (NSLServicesList serviceList, NSLTypedDataPtr * newDataPtr); /* releases any storage created with MakeXXXPB calls, associated with TypedData.*/ EXTERN_API( NSLTypedDataPtr ) NSLFreeTypedDataPtr (NSLTypedDataPtr nslTypeData); /* utility function that returns whether a url was found, a pointer to the beginning of the url, and the length of the URL. */ EXTERN_API( Boolean ) NSLGetNextUrl (NSLClientAsyncInfoPtr infoPtr, char ** urlPtr, long * urlLength); /* utility function that returns whether a Neighborhood was found, a pointer to the beginning of the Neighborhood, and the length of the Neighborhood. */ EXTERN_API( Boolean ) NSLGetNextNeighborhood (NSLClientAsyncInfoPtr infoPtr, NSLNeighborhood * neighborhood, long * neighborhoodLength); /* NSLErrorToString: convert a numeric error code to its string equivalent. Caller must have allocated sufficient space to store both strings. (Max 255 chars each) The errorString parameter will return a textual explanation of what is wrong, while the solutionString returns a possible solution to get around the problem */ EXTERN_API( OSStatus ) NSLErrorToString (NSLError theErr, char * errorString, char * solutionString); /* ----------------------------------------------------------------------------- Basic API calls: sufficient to create simple requests, and receive answers ----------------------------------------------------------------------------- */ EXTERN_API( OSStatus ) NSLOpenNavigationAPI (NSLClientRef * newRef); EXTERN_API( void ) NSLCloseNavigationAPI (NSLClientRef theClient); /* NSLPrepareRequest: creates an NSLRequestRef, sets up some internal data notifier is an NSLClientNotifyUPP that will be called when data is available, when the lookup has completed, or if an error occurs. When the notifier is called, the cookie will be the NSLRequestRef. If notifier is NULL, then the NSLManager will assume that the request is made synchronously. This should only be used while in a separate thread, so that the client app can still process events, etc. contextPtr is a void* which is passed as the contextPtr argument when the notifier is called. upon exit: 1) ref will contain a pointer to a NSLRequestRef which must be passed to all other functions which require a NSLRequestRef. 2) infoPtr will point to a newly created ClientAsycnInfoPtr which will be disposed by the manager when the search is completed NOTE: Only one search can be running at a time per clientRef. */ EXTERN_API( NSLError ) NSLPrepareRequest (NSLClientNotifyUPP notifier, void * contextPtr, NSLClientRef theClient, NSLRequestRef * ref, char * bufPtr, unsigned long bufLen, NSLClientAsyncInfoPtr * infoPtr); /* NSLStartNeighborhoodLookup: looking for neighborhoods associated with or neighboring a particular neighborhood Passing in NULL for neighborhood will generate a list of a default neighborhood(s) */ EXTERN_API( NSLError ) NSLStartNeighborhoodLookup (NSLRequestRef ref, NSLNeighborhood neighborhood, NSLClientAsyncInfo * asyncInfo); /* NSLStartServicesLookup: starts looking for entities if the specified type in the specified neighborhood */ EXTERN_API( NSLError ) NSLStartServicesLookup (NSLRequestRef ref, NSLNeighborhood neighborhood, NSLTypedDataPtr requestData, NSLClientAsyncInfo * asyncInfo); /* NSLContinueLookup: continues a paused/outstanding lookup*/ EXTERN_API( NSLError ) NSLContinueLookup (NSLClientAsyncInfo * asyncInfo); /* NSLCancelRequest: cancels an ongoing search*/ EXTERN_API( NSLError ) NSLCancelRequest (NSLRequestRef ref); /* NSLDeleteRequest: deletes info associated with this ref. The ClientAsyncInfoPtr will no longer be valid This must be called when the client is no longer using this requestRef. */ EXTERN_API( NSLError ) NSLDeleteRequest (NSLRequestRef ref); /* ----------------------------------------------------------------------------- Utility API calls: use these accessors to manipulate NSL's typed data ----------------------------------------------------------------------------- */ /* NSLParseServicesRequestPB provides the inverse of NSLMakeRequestPB, filling out the offsets found within newDataPtr*/ /* <--- returns an OSStatus if any errors occur parsing the data */ /* <--- newDataPtr is the construct passed to the plugin */ /* ---> serviceListPtr is the address of a pointer which will be set to point at the portion of the newDataPtr that holds the serviceList to be searched */ /* ---> serviceListLen is the length of the serviceListPtr data pointed to by serviceListPtr */ EXTERN_API( OSStatus ) NSLParseServicesRequestPB (NSLTypedDataPtr newDataPtr, char ** serviceListPtr, UInt16 * serviceListLen); /* NSLParseServiceRegistrationPB provides for breaking apart a registration request from a client to a plugin*/ /* <--- returns an OSStatus if any errors occur parsing the data */ /* <--- newDataPtr is the construct passed to the plugin */ /* ---> neighborhoodPtr gets set to point at the portion of the newDataPtr that contains the neighborhood */ /* ---> neighborhoodLen is the length of the neighborhood pointed to by neighborhoodPtr */ /* ---> urlPtr is the address of a pointer which will be set to point at the portion of the newDataPtr that holds the url to be registered */ /* ---> urlLen is the length of the url data pointed to by urlPtr */ EXTERN_API( OSStatus ) NSLParseServiceRegistrationPB (NSLTypedDataPtr newDataPtr, NSLNeighborhood * neighborhoodPtr, UInt16 * neighborhoodLen, char ** urlPtr, UInt16 * urlLen); /* NSLGetErrorStringsFromResource makes a basic assumption! errorString and solutionString both point to valid memory of at least 256 bytes! */ /* <--- returns an OSStatus if any errors occur */ /* ---> theErr is an OSStatus to be matched against a resource list of errors */ /* ---> fileSpecPtr is a FSSpecPtr to the resource containing the list of errors */ /* ---> errorResID is the resourceID of the NSLI resource of the list of errors */ /* <--> errorString is a pointer to valid memory of at least 256 bytes which will be filled out by the error portion of the error string */ /* <--> solutionString is a pointer to valid memory of at least 256 bytes which will be filled out by the solution portion of the error string */ EXTERN_API( OSStatus ) NSLGetErrorStringsFromResource (OSStatus theErr, const FSSpec * fileSpecPtr, SInt16 errorResID, char * errorString, char * solutionString); /* <--- Returns true if given service is in the given service list */ /* ---> serviceList is a valid NSLServicesList containing information about services to be searched */ /* ---> svcToFind is an NSLServiceType of a particular service to check if it is in the serviceList */ EXTERN_API( Boolean ) NSLServiceIsInServiceList (NSLServicesList serviceList, NSLServiceType svcToFind); /* <--- returns an OSStatus if any errors occur parsing the data */ /* ---> svcString is the address of a pointer which will be set to point at the portion of theURL that holds the serviceType of theURL */ /* ---> svcLen is the length of the serviceType pointed to by svcString */ EXTERN_API( OSStatus ) NSLGetServiceFromURL (char * theURL, char ** svcString, UInt16 * svcLen); /* <--- returns the length of a Neighborhood data structure */ /* ---> neighborhood is a valid NSLNeighborhood */ EXTERN_API( long ) NSLGetNeighborhoodLength (NSLNeighborhood neighborhood); /* ------------------------------------------------------------------------------------- Utility API calls: use these routines to separate plugin threads from client threads ------------------------------------------------------------------------------------- */ /* this routine works the same as the Thread manager's routine NewThread, except */ /* that the thread is added to the NSL manager's thread list. */ EXTERN_API( OSErr ) NSLNewThread (ThreadStyle threadStyle, ThreadEntryProcPtr threadEntry, void * threadParam, Size stackSize, ThreadOptions options, void ** threadResult, ThreadID * threadMade); /* this routine works the same as the Thread manager's routine DisposeThread, except */ /* that the thread is removed from the NSL manager's thread list. */ EXTERN_API( OSErr ) NSLDisposeThread (ThreadID threadToDump, void * threadResult, Boolean recycleThread); #if OLDROUTINENAMES typedef NSLClientAsyncInfo ClientAsyncInfo; typedef NSLPluginAsyncInfo PluginAsyncInfo; typedef NSLTypedData TypedData; typedef NSLPluginData PluginData; typedef NSLClientAsyncInfoPtr ClientAsyncInfoPtr; typedef NSLPluginAsyncInfoPtr PluginAsyncInfoPtr; typedef NSLTypedDataPtr TypedDataPtr; typedef NSLPluginDataPtr PluginDataPtr; #endif /* OLDROUTINENAMES */ #if PRAGMA_STRUCT_ALIGN #pragma options align=reset #elif PRAGMA_STRUCT_PACKPUSH #pragma pack(pop) #elif PRAGMA_STRUCT_PACK #pragma pack() #endif #ifdef PRAGMA_IMPORT_OFF #pragma import off #elif PRAGMA_IMPORT #pragma import reset #endif #ifdef __cplusplus } #endif #endif /* __NSL__ */
56.038052
186
0.593856
f676819e2ffa2261d6576f3b1210f0893ee2e409
6,824
c
C
legacy/cfunccall/src/csrc/cfunctions.c
Clonkk/nimjl
4f4dbcd01845adecbc4c18df228c7e3ab291e14f
[ "MIT" ]
39
2020-06-16T16:55:40.000Z
2022-02-14T05:24:43.000Z
legacy/cfunccall/src/csrc/cfunctions.c
Clonkk/nimjl
4f4dbcd01845adecbc4c18df228c7e3ab291e14f
[ "MIT" ]
11
2021-03-10T09:34:29.000Z
2021-11-04T17:20:10.000Z
legacy/cfunccall/src/csrc/cfunctions.c
Clonkk/nimjl
4f4dbcd01845adecbc4c18df228c7e3ab291e14f
[ "MIT" ]
1
2021-11-01T12:32:38.000Z
2021-11-01T12:32:38.000Z
/* _GNU_SOURCE is only needed for for the non-Windows part of the * `find_julia_bindir` function. */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined(_WIN32) || defined(_WIN64) #define _OS_WINDOWS_ #endif #ifdef _OS_WINDOWS_ #include <windows.h> #else #include <dlfcn.h> /* `libgen.h` is only needed for for the `find_julia_bindir` function. */ #include <libgen.h> #endif /* Load a minimal subset of the functions from julia.h dynamically. /* We could get the definitions of these structs from * `#include "julia.h"`, but we only need to declare them and * including julia.h would interfere with masquerading the `jl_*` * functions as pointers. */ typedef struct _jl_value_t jl_value_t; typedef struct _jl_sym_t jl_sym_t; typedef struct _jl_module_t jl_module_t; /* Declare pointers to the functions we need to load from libjulia. * Obviously these signatures must match the corresponding functions * in the julia.h that libjulia was built from. */ static const char* (*jl_ver_string)(void); static void (*jl_init)(void); static void (*jl_init_with_image)(const char*, const char*); static int (*jl_is_initialized)(void); static void (*jl_atexit_hook)(int); static jl_value_t *(*jl_eval_string)(const char *); static jl_sym_t *(*jl_symbol)(const char *); static jl_module_t **p_jl_main_module; #define jl_main_module (*p_jl_main_module) static jl_value_t *(*jl_get_global)(jl_module_t *, jl_sym_t *); static void *(*jl_unbox_voidpointer)(jl_value_t *); static const char *(*jl_string_ptr)(jl_value_t *); static jl_value_t *(*jl_exception_occurred)(void); static int julia_functions_loaded = 0; #ifdef _OS_WINDOWS_ #define dlsym_ GetProcAddress #else #define dlsym_ dlsym #endif /* Helper function to extract function pointers from the dynamically * loaded libjulia. */ #ifdef _OS_WINDOWS_ static void *load_function(HMODULE libjulia, const char *name, int *success) #else static void *load_function(void *libjulia, const char *name, int *success) #endif { void *p = dlsym_(libjulia, name); /* Unfortunately Julia renames `jl_init` to `jl_init__threading` if * Julia is compiled with threading support, so we have to check * which of these is available, or otherwise query Julia in some * other way (https://github.com/JuliaLang/julia/issues/28824). */ if (!p && strcmp(name, "jl_init") == 0) { p = dlsym_(libjulia, "jl_init__threading"); } /* Likewise for `jl_init_with_image`. */ if (!p && strcmp(name, "jl_init_with_image") == 0) { p = dlsym_(libjulia, "jl_init_with_image__threading"); } if (!p) { fprintf(stderr, "%s not found in libjulia.\n", name); *success = 0; } return p; } /* Open libjulia and extract pointers to the needed functions. */ static int load_julia_functions() { if (julia_functions_loaded) return 1; #ifdef _OS_WINDOWS_ /* libjulia.dll needs to be in the same directory as the * executable or in PATH. */ const char *library_name = "libjulia.dll"; HMODULE libjulia = LoadLibrary(library_name); #else /* libjulia.so needs to be in LD_LIBRARY_PATH. It could also be in * rpath (but that kind of defeats the purpose of dynamically * loading libjulia) or an absolute path could be given, computed * from other information. */ #ifdef __APPLE__ const char *library_name = "libjulia.dylib"; #else const char *library_name = "libjulia.so"; #endif void *libjulia = dlopen(library_name, RTLD_LAZY | RTLD_GLOBAL); #endif if (!libjulia) { fprintf(stderr, "Failed to load libjulia.\n"); return 0; } int success = 1; jl_ver_string = load_function(libjulia, "jl_ver_string", &success); jl_init = load_function(libjulia, "jl_init", &success); jl_init_with_image = load_function(libjulia, "jl_init_with_image", &success); jl_is_initialized = load_function(libjulia, "jl_is_initialized", &success); jl_atexit_hook = load_function(libjulia, "jl_atexit_hook", &success); jl_eval_string = load_function(libjulia, "jl_eval_string", &success); jl_symbol = load_function(libjulia, "jl_symbol", &success); p_jl_main_module = load_function(libjulia, "jl_main_module", &success); jl_get_global = load_function(libjulia, "jl_get_global", &success); jl_unbox_voidpointer = load_function(libjulia, "jl_unbox_voidpointer", &success); jl_string_ptr = load_function(libjulia, "jl_string_ptr", &success); jl_exception_occurred = load_function(libjulia, "jl_exception_occurred", &success); if (success) julia_functions_loaded = 1; return success; } /* Helper function for loading of a custom system image. It is * unfortunate that this is needed since Julia should know much better * itself where things are located than we realistically can know. See * the comment where this function is called from `julia_initialize` * for further discussion. */ static char *find_julia_bindir() { char *bindir = NULL; #ifdef _OS_WINDOWS_ HMODULE handle; if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR)(uintptr_t)(jl_init), &handle)) { TCHAR *path = malloc(MAX_PATH * sizeof(*path)); DWORD n = GetModuleFileNameA(handle, path, MAX_PATH); if (n > 0) { /* Poor man's dirname() on Windows. A better solution * might involve _splitpath_s. */ while (--n > 0) { if (path[n - 1] == '/' || path[n - 1] == '\\') { path[n] = (TCHAR)0; break; } } bindir = (char *)path; } } #else Dl_info dlinfo; if (dladdr((void *)jl_init, &dlinfo) != 0 && dlinfo.dli_fname) { char *file_path = strdup(dlinfo.dli_fname); (void)asprintf(&bindir, "%s/../%s", dirname(file_path), "bin"); free(file_path); } #endif return bindir; } /* Helper function to retrieve pointers to cfunctions on the Julia side. */ void *get_cfunction_pointer(const char *name) { void *p = 0; jl_value_t *boxed_pointer = jl_get_global(jl_main_module, jl_symbol(name)); if (boxed_pointer != 0) { p = jl_unbox_voidpointer(boxed_pointer); } if (!p) { fprintf(stderr, "cfunction pointer %s not available.\n", name); } return p; } void nimjl_init(int code) { if(!load_julia_functions()) { printf("Error loading functions\n"); return; } jl_init(); return; } void nimjl_atexit_hook(int code) { jl_atexit_hook(code); } jl_value_t *nimjl_eval_string(char *code) { return jl_eval_string(code); } void * nimjl_unbox_voidpointer(jl_value_t * p) { return jl_unbox_voidpointer(p); }
31.159817
113
0.683763
09fb36073c5b529ac0a3cae6300b140dd38cc7ee
302
h
C
FileGrabber/Log.h
jsjtsty/FileGrabber
5f64c2d58eb7cec158df0133ece55837f55a3114
[ "Apache-2.0" ]
null
null
null
FileGrabber/Log.h
jsjtsty/FileGrabber
5f64c2d58eb7cec158df0133ece55837f55a3114
[ "Apache-2.0" ]
null
null
null
FileGrabber/Log.h
jsjtsty/FileGrabber
5f64c2d58eb7cec158df0133ece55837f55a3114
[ "Apache-2.0" ]
1
2020-06-28T03:57:55.000Z
2020-06-28T03:57:55.000Z
#pragma once #include <string> class Log { public: static Log* getInstance(); void i(const std::wstring& msg); void w(const std::wstring& msg); void e(const std::wstring& msg); void v(const std::wstring& msg); void d(const std::wstring& msg); private: Log(); }; #define LOG Log::getInstance()
16.777778
33
0.678808
1bdb9f898977c8af2d9f6473638cd9f78c882e72
5,472
c
C
ide/pythonembed.c
LMiceOrg/lmice
154421a0d21e0bfc193d3410233e68e6df1ece16
[ "MIT" ]
1
2019-03-23T06:23:24.000Z
2019-03-23T06:23:24.000Z
ide/pythonembed.c
LMiceOrg/lmice
154421a0d21e0bfc193d3410233e68e6df1ece16
[ "MIT" ]
null
null
null
ide/pythonembed.c
LMiceOrg/lmice
154421a0d21e0bfc193d3410233e68e6df1ece16
[ "MIT" ]
null
null
null
/**! # Embeded python a python helper module for stock/future exchange, backtesting and simulation The top most module names "lmice", includes several helper classes and to instance DataSource objects, DataProcess objects, Builder objects, ...etc. The DataSource submodules represent formal stock/future/reporting data, and also represent informal data, web data and user-defined documents. The supported scenarios include . The DataProcess submodules represent how to deal with data source, mapping, convertion, filtering, cleaning, calculation, transformation and reporting. The Builder submodules represent the control flow of financial engineering system. */ #include "pythonembed.h" #include <stdio.h> #include <string.h> #include <sys/unistd.h> #include "lmice_trace.h" //static PyMemberDef ChinaL1Msg_members[] = { // ChinaL1Msg_Prop_Def(m_inst, T_STRING, "instrument") // ChinaL1Msg_Prop_Def(m_time, T_LONG, "micro time") // ChinaL1Msg_Prop_Def(m_bid, T_DOUBLE, "bid price") // ChinaL1Msg_Prop_Def(m_offer, T_DOUBLE, "bid price") // ChinaL1Msg_Prop_Def(m_bid_quantity, T_INT, "bid quantity") // ChinaL1Msg_Prop_Def(m_offer_quantity, T_INT, "offer quantity") // ChinaL1Msg_Prop_Def(m_volume, T_INT, "volume") // ChinaL1Msg_Prop_Def(m_notional, T_DOUBLE, "notional") // ChinaL1Msg_Prop_Def(m_limit_up, T_DOUBLE, "limit up") // ChinaL1Msg_Prop_Def(m_limit_down, T_DOUBLE, "limit down") // {NULL, 0, 0, 0, NULL} /* Sentinel */ //}; //static PyObject* //guava_load(PyObject *self, PyObject *args, PyObject* kw) //{ // static char* kw_list[]={"name", NULL}; // char* str; // Py_ssize_t len; // int ret; // (void)self; // ret = PyArg_ParseTupleAndKeywords(args, kw, "s#", kw_list, &str, &len); // if(!ret) // return NULL; // FILE* fp; // struct stat st; // ret = stat(str, &st); // if(ret == 0 && (st.st_mode & S_IRUSR) ) // { // fp = fopen(str, "rb"); // if(fp) // return PyLong_FromSize_t(len); // //return Py_BuildValue("i", len); //} //static PyMethodDef EmbedLmiceModuleMethods[] = { // {"guava_load", guava_load, METH_VARARGS|METH_KEYWORDS, // "Load guava2 data from name(file)."}, // {NULL, NULL, 0, NULL} //}; PyObject *g_py_stdout = NULL; PyObject *g_py_stderr = NULL; PyObject* stdio_redirect(PyObject* self, PyObject* args) { /**! PyObject * io; LS_RedirectIO* obj; io = LS_RedirectIO_Type.tp_new(&LS_RedirectIO_Type, self, args); obj = (LS_RedirectIO*)io; */ if(g_py_stdout == NULL) { PyObject* mod = NULL; PyObject* o=NULL; PyObject* oe=NULL; PyObject* arg=NULL; PyObject* arg1=NULL; mod = PyImport_AddModule("sys"); g_py_stdout = PyObject_GetAttrString(mod, "stdout"); g_py_stderr = PyObject_GetAttrString(mod, "stderr"); arg = PyTuple_New(1); arg1 = PyInt_FromLong(LMICE_TRACE_INFO); PyTuple_SET_ITEM(arg, 0, arg1); o = LS_RedirectIO_Type.tp_new(&LS_RedirectIO_Type, Py_None, Py_None); LS_RedirectIO_Type.tp_init(o, arg, Py_None); Py_XDECREF(arg1); arg1 = PyInt_FromLong(LMICE_TRACE_ERROR); PyTuple_SET_ITEM(arg, 0, arg1); oe = LS_RedirectIO_Type.tp_new(&LS_RedirectIO_Type, Py_None, Py_None); LS_RedirectIO_Type.tp_init(oe, arg, Py_None); PyObject_SetAttrString(mod, "stdout", o); PyObject_SetAttrString(mod, "stderr", oe); Py_XDECREF(mod); Py_XDECREF(o); Py_XDECREF(oe); Py_XDECREF(arg); Py_XDECREF(arg1); } return Py_True; } PyObject* stdio_reset(PyObject* self, PyObject* args) { if(g_py_stdout) { PyObject* mod = NULL; mod = PyImport_AddModule("sys"); PyObject_SetAttrString(mod, "stdout", g_py_stdout); PyObject_SetAttrString(mod, "stderr", g_py_stderr); Py_XDECREF(mod); Py_XDECREF(g_py_stdout); Py_XDECREF(g_py_stderr); g_py_stdout=NULL; g_py_stderr=NULL; } return Py_True; } static PyMethodDef lmice_methods[] = { {"ioredirect", stdio_redirect, METH_NOARGS, "Redirect stdout and stderr"}, {"ioreset", stdio_reset, METH_NOARGS, "Reset stdout and stderr"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; extern PyTypeObject ChinaL1Source_Type; PyMODINIT_FUNC init_lmice_module(void) { PyObject* m; m = Py_InitModule3("lmice", lmice_methods, "LMICE module is a helper for stock/future exchange, backtesting and simulation."); if (m == NULL) return; PyModule_AddStringConstant(m, "__file__", "lmice.c"); PyModule_AddStringConstant(m, "__package__", "lmice"); init_chinal1source_object(m); LS_InstrumentFilter_register(m); LS_RedirectIO_register(m); init_windowproxy_module(m); PyObject* obj = PyModule_GetDict(m); lmice_critical_print("lmice dict:%s\n", PyString_AS_STRING( PyObject_Str(obj) ) ); } void update_sys_path(const char* path) { PyObject* mod =NULL; PyObject* o=NULL; PyObject* arg=NULL; mod = PyImport_AddModule("sys"); o = PyObject_GetAttrString(mod, "path"); if(PyList_Check(o)) { arg = PyString_FromString(path); PyList_Insert(o, 0, arg); } Py_XDECREF(o); Py_XDECREF(arg); }
26.563107
106
0.64364
736e3d3f3bdac67d7bf21dce784521668e9d5057
250
h
C
Pentagon_iOS/Pentagon_iOS/PTMusicServiceViewController.h
liuyuewu/vinci
5f730293fd5e849e9f17322bc3c8601136f5938d
[ "MIT" ]
null
null
null
Pentagon_iOS/Pentagon_iOS/PTMusicServiceViewController.h
liuyuewu/vinci
5f730293fd5e849e9f17322bc3c8601136f5938d
[ "MIT" ]
null
null
null
Pentagon_iOS/Pentagon_iOS/PTMusicServiceViewController.h
liuyuewu/vinci
5f730293fd5e849e9f17322bc3c8601136f5938d
[ "MIT" ]
1
2021-01-07T02:48:48.000Z
2021-01-07T02:48:48.000Z
// // PTMusicServiceViewController.h // Pentagon_iOS // // Created by vinci on 2017/6/23. // Copyright © 2017年 vinci. All rights reserved. // #import "PTBaseViewController.h" @interface PTMusicServiceViewController : PTBaseViewController @end
17.857143
62
0.748
73e351d4e888e39d57cb31f8bba8a7b39e944782
1,103
h
C
src/ofApp.h
davidaronson13/ofxAssimpModelLoader-RPI-Example
5200724ccb215b5f29bcc13558cd962719d64f5c
[ "MIT" ]
null
null
null
src/ofApp.h
davidaronson13/ofxAssimpModelLoader-RPI-Example
5200724ccb215b5f29bcc13558cd962719d64f5c
[ "MIT" ]
null
null
null
src/ofApp.h
davidaronson13/ofxAssimpModelLoader-RPI-Example
5200724ccb215b5f29bcc13558cd962719d64f5c
[ "MIT" ]
null
null
null
#pragma once #include "ofMain.h" #include "ofxAssimpModelLoader.h" #include "ofVboMesh.h" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); private: void initializeModelVariables(int aModel); void inline updateRotation(void); char actualModelNumber; string text1; int numberOfLinesInText; int contador; ofxAssimpModelLoader model; #define RENDER_MODE_FILL 0 #define RENDER_MODE_POINTS 1 #define RENDER_MODE_WIREFRAME 2 char actualRenderMode; #define ROTATION_STEP 5 int actualXRotation; int actualYRotation; int actualZRotation; #define SCALE_STEP 0.05 double animationTime; ofTexture tex; ofLight light; };
19.350877
47
0.737081
ad7e9abfccbc8b89422395849082b3302f06b550
1,507
h
C
PrivateFrameworks/PhotoPrintProduct/KHThemePreviewInfo.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
17
2018-11-13T04:02:58.000Z
2022-01-20T09:27:13.000Z
PrivateFrameworks/PhotoPrintProduct/KHThemePreviewInfo.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
3
2018-04-06T02:02:27.000Z
2018-10-02T01:12:10.000Z
PrivateFrameworks/PhotoPrintProduct/KHThemePreviewInfo.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
1
2018-09-28T13:54:23.000Z
2018-09-28T13:54:23.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" #import "KHThemePreviewInfoProtocol.h" @class NSArray, NSMutableSet, NSNumber, NSString; @interface KHThemePreviewInfo : NSObject <KHThemePreviewInfoProtocol> { NSString *_name; NSString *_themePreviewIdentifier; NSString *_themeIdentifier; NSMutableSet *_keywords; NSMutableSet *_languages; NSArray *_productCodes; NSNumber *_catalogVersion; } + (id)infoKey; @property(retain, nonatomic) NSNumber *catalogVersion; // @synthesize catalogVersion=_catalogVersion; @property(retain, nonatomic) NSArray *productCodes; // @synthesize productCodes=_productCodes; @property(retain, nonatomic) NSMutableSet *languages; // @synthesize languages=_languages; @property(retain, nonatomic) NSMutableSet *keywords; // @synthesize keywords=_keywords; @property(retain, nonatomic) NSString *themeIdentifier; // @synthesize themeIdentifier=_themeIdentifier; @property(retain, nonatomic) NSString *themePreviewIdentifier; // @synthesize themePreviewIdentifier=_themePreviewIdentifier; @property(retain, nonatomic) NSString *name; // @synthesize name=_name; - (void).cxx_destruct; - (id)initFromDictionary:(id)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
35.046512
125
0.772395
1afb73a0620846908d5dda1bc2743abdde1c3cf0
9,965
h
C
src/Gui/jkGUIRend.h
MacSourcePorts/OpenJKDF2
4e129d1429ff549fbf95945d5675865a154aabde
[ "0BSD" ]
null
null
null
src/Gui/jkGUIRend.h
MacSourcePorts/OpenJKDF2
4e129d1429ff549fbf95945d5675865a154aabde
[ "0BSD" ]
null
null
null
src/Gui/jkGUIRend.h
MacSourcePorts/OpenJKDF2
4e129d1429ff549fbf95945d5675865a154aabde
[ "0BSD" ]
null
null
null
#ifndef _JKGUIREND_H #define _JKGUIREND_H #include <stdint.h> #include "types.h" #include "Primitives/rdRect.h" #define jkGuiRend_CopyVBuffer_ADDR (0x0050F4B0) #define jkGuiRend_SetPalette_ADDR (0x0050F4F0) #define jkGuiRend_DrawRect_ADDR (0x0050F510) #define jkGuiRend_UpdateDrawMenu_ADDR (0x0050F700) #define jkGuiRend_Paint_ADDR (0x0050F780) #define jkGuiRend_SetElementIdk_ADDR (0x0050F870) #define jkGuiRend_MenuSetLastElement_ADDR (0x0050F880) #define jkGuiRend_SetDisplayingStruct_ADDR (0x0050F890) #define jkGuiRend_DisplayAndReturnClicked_ADDR (0x0050F8A0) #define jkGuiRend_sub_50FAD0_ADDR (0x0050FAD0) #define jkGuiRend_gui_sets_handler_framebufs_ADDR (0x0050FC00) #define jkGuiRend_Menuidk_ADDR (0x0050FD50) #define jkGuiRend_sub_50FDB0_ADDR (0x0050FDB0) #define jkGuiRend_Initialize_ADDR (0x0050FDF0) #define jkGuiRend_Shutdown_ADDR (0x0050FE00) #define jkGuiRend_Open_ADDR (0x0050FE10) #define jkGuiRend_Close_ADDR (0x0050FE40) #define jkGuiRend_MenuGetClickableById_ADDR (0x0050FE60) #define jkGuiRend_PlayWav_ADDR (0x0050FE90) #define jkGuiRend_SetCursorVisible_ADDR (0x005100A0) #define jkGuiRend_UpdateCursor_ADDR (0x00510110) #define jkGuiRend_UpdateSurface_ADDR (0x00510180) #define jkGuiRend_DrawAndFlip_ADDR (0x005101C0) #define jkGuiRend_Invalidate_ADDR (0x005101D0) #define jkGuiRend_DarrayNewStr_ADDR (0x005101F0) #define jkGuiRend_DarrayReallocStr_ADDR (0x00510210) #define jkGuiRend_AddStringEntry_ADDR (0x00510270) #define jkGuiRend_SetClickableString_ADDR (0x005102C0) #define jkGuiRend_GetString_ADDR (0x005102E0) #define jkGuiRend_GetId_ADDR (0x00510300) #define jkGuiRend_GetStringEntry_ADDR (0x00510320) #define jkGuiRend_DarrayFree_ADDR (0x00510340) #define jkGuiRend_DarrayFreeEntry_ADDR (0x00510390) #define jkGuiRend_sub_5103E0_ADDR (0x005103E0) #define jkGuiRend_ElementHasHoverSound_ADDR (0x00510410) #define jkGuiRend_UpdateAndDrawClickable_ADDR (0x00510460) #define jkGuiRend_InvokeButtonDown_ADDR (0x00510650) #define jkGuiRend_InvokeButtonUp_ADDR (0x005106A0) #define jkGuiRend_PlayClickSound_ADDR (0x005106F0) #define jkGuiRend_RenderFocused_ADDR (0x00510710) #define jkGuiRend_RenderIdk2_ADDR (0x00510770) #define jkGuiRend_RenderAll_ADDR (0x00510840) #define jkGuiRend_ClickableMouseover_ADDR (0x00510910) #define jkGuiRend_MouseMovedCallback_ADDR (0x005109B0) #define jkGuiRend_SetVisibleAndDraw_ADDR (0x00510B50) #define jkGuiRend_ClickableHover_ADDR (0x00510B80) #define jkGuiRend_sub_510C60_ADDR (0x00510C60) #define jkGuiRend_ClickSound_ADDR (0x00510CF0) #define jkGuiRend_HoverOn_ADDR (0x00510D20) #define jkGuiRend_ListBoxButtonDown_ADDR (0x00510D50) #define jkGuiRend_ListBoxDraw_ADDR (0x00511000) #define jkGuiRend_CheckBoxDraw_ADDR (0x00511260) #define jkGuiRend_DrawClickableAndUpdatebool_ADDR (0x00511350) #define jkGuiRend_WindowHandler_ADDR (0x00511380) #define jkGuiRend_UpdateMouse_ADDR (0x005117B0) #define jkGuiRend_FlipAndDraw_ADDR (0x00511800) #define jkGuiRend_GetMousePos_ADDR (0x00511870) #define jkGuiRend_ResetMouseLatestMs_ADDR (0x005118C0) #define jkGuiRend_InvalidateGdi_ADDR (0x005118D0) #define jkGuiRend_SliderButtonDown_ADDR (0x005118F0) #define jkGuiRend_SliderDraw_ADDR (0x00511B60) #define jkGuiRend_TextBoxButtonDown_ADDR (0x00511E10) #define jkGuiRend_TextBoxDraw_ADDR (0x00512080) #define jkGuiRend_TextDraw_ADDR (0x00512200) #define jkGuiRend_PicButtonButtonDown_ADDR (0x00512250) #define jkGuiRend_PicButtonDraw_ADDR (0x005122C0) #define jkGuiRend_TextButtonButtonDown_ADDR (0x00512370) #define jkGuiRend_TextButtonDraw_ADDR (0x005123C0) typedef struct stdFont stdFont; typedef struct jkGuiStringEntry jkGuiStringEntry; typedef struct jkGuiElement jkGuiElement; typedef struct jkGuiMenu jkGuiMenu; typedef struct jkGuiTexInfo jkGuiTexInfo; typedef struct stdBitmap stdBitmap; typedef struct stdVBuffer stdVBuffer; typedef struct Darray Darray; enum jkGuiElementType_t { ELEMENT_TEXTBUTTON = 0, ELEMENT_PICBUTTON = 1, ELEMENT_TEXT = 2, ELEMENT_CHECKBOX = 3, ELEMENT_LISTBOX = 4, ELEMENT_TEXTBOX = 5, ELEMENT_SLIDER = 6, ELEMENT_CUSTOM = 7, ELEMENT_8 = 8, ELEMENT_END = 9, }; //#define jkGuiRend_palette ((uint8_t*)0x855EC8) //#define jkGuiRend_idk2 (*(int*)0x8561C8) //#define jkGuiRend_idk (*(int*)0x8561CC) //#define jkGuiRend_activeMenu (*(jkGuiMenu**)0x8561E0) //#define jkGuiRend_menuBuffer (*(stdVBuffer**)0x8561E4) //#define jkGuiRend_texture_dword_8561E8 (*(stdVBuffer**)0x8561E8) //#define jkGuiRend_thing_five (*(int*)0x8561EC) //#define jkGuiRend_thing_four (*(int*)0x8561F0) //#define jkGuiRend_bIsSurfaceValid (*(int*)0x8561F4) //#define jkGuiRend_bInitted (*(int*)0x008561F8) //#define jkGuiRend_bOpen (*(int*)0x008561FC) //#define jkGuiRend_HandlerIsSet (*(int*)0x00856200) //#define jkGuiRend_fillColor (*(int*)0x00856204) //#define jkGuiRend_paletteChecksum (*(int*)0x00856208) //#define jkGuiRend_dword_85620C (*(int*)0x0085620C) //#define jkGuiRend_lastKeyScancode (*(int*)0x00856210) //#define jkGuiRend_mouseX (*(int*)0x00856214) //#define jkGuiRend_mouseY (*(int*)0x00856218) //#define jkGuiRend_bShiftDown (*(int*)0x0085621C) //#define jkGuiRend_mouseXLatest (*(int*)0x00856220) //#define jkGuiRend_mouseYLatest (*(int*)0x00856224) //#define jkGuiRend_mouseLatestMs (*(int*)0x00856228) //#define jkGuiRend_hCursor (*(HCURSOR*)0x0085622C) //#define jkGuiRend_CursorVisible (*(int*)0x54F6BC) //#define jkGuiRend_elementHandlers ((jkGuiElementHandlers*)0x54F6D0) extern int jkGuiRend_thing_five; extern int jkGuiRend_thing_four; void jkGuiRend_CopyVBuffer(jkGuiMenu *menu, rdRect *rect); void jkGuiRend_SetPalette(uint8_t* pal); void jkGuiRend_DrawRect(stdVBuffer *vbuf, rdRect *rect, __int16 color); void jkGuiRend_UpdateDrawMenu(jkGuiMenu *menu); void jkGuiRend_Paint(jkGuiMenu *menu); void jkGuiRend_SetElementIdk(jkGuiElement *element, int idk); void jkGuiRend_MenuSetLastElement(jkGuiMenu *menu, jkGuiElement *element); void jkGuiRend_SetDisplayingStruct(jkGuiMenu *menu, jkGuiElement *element); int jkGuiRend_DisplayAndReturnClicked(jkGuiMenu *menu); void jkGuiRend_sub_50FAD0(jkGuiMenu *menu); void jkGuiRend_gui_sets_handler_framebufs(jkGuiMenu *menu); int jkGuiRend_Menuidk(); void jkGuiRend_sub_50FDB0(); void jkGuiRend_Initialize(); void jkGuiRend_Shutdown(); void jkGuiRend_Open(stdVBuffer *menuBuffer, stdVBuffer *otherBuf, int fillColor); void jkGuiRend_Close(); jkGuiElement* jkGuiRend_MenuGetClickableById(jkGuiMenu *menu, int id); void jkGuiRend_PlayWav(char *fpath); void jkGuiRend_SetCursorVisible(int visible); void jkGuiRend_UpdateCursor(); void jkGuiRend_UpdateSurface(); void jkGuiRend_DrawAndFlip(); void jkGuiRend_Invalidate(); int jkGuiRend_DarrayNewStr(Darray *array, int num, int initVal); int jkGuiRend_DarrayReallocStr(Darray *array, wchar_t *wStr, intptr_t id); int jkGuiRend_AddStringEntry(Darray *a1, const char *str, intptr_t id); void jkGuiRend_SetClickableString(jkGuiElement *element, Darray *array); wchar_t* jkGuiRend_GetString(Darray *array, int idx); intptr_t jkGuiRend_GetId(Darray *array, int idx); jkGuiStringEntry* jkGuiRend_GetStringEntry(Darray *array, int idx); void jkGuiRend_DarrayFree(Darray *array); void jkGuiRend_DarrayFreeEntry(Darray *array); int jkGuiRend_sub_5103E0(jkGuiElement *element); int jkGuiRend_ElementHasHoverSound(jkGuiElement *element); void jkGuiRend_UpdateAndDrawClickable(jkGuiElement *clickable, jkGuiMenu *menu, int forceRedraw); int jkGuiRend_InvokeButtonDown(jkGuiElement *element, jkGuiMenu *menu, int a3, int a4); int jkGuiRend_InvokeButtonUp(jkGuiElement *clickable, jkGuiMenu *menu, int mouseX, int mouseY, int a5); int jkGuiRend_PlayClickSound(jkGuiElement *element, jkGuiMenu *menu, int a, int b, int c); void jkGuiRend_RenderFocused(jkGuiMenu *menu, jkGuiElement *element); void jkGuiRend_RenderIdk2(jkGuiMenu *menu); void jkGuiRend_RenderIdk2_alt(jkGuiMenu *menu); void jkGuiRend_RenderAll(jkGuiMenu *menu); void jkGuiRend_ClickableMouseover(jkGuiMenu *menu, jkGuiElement *element); void jkGuiRend_MouseMovedCallback(jkGuiMenu *menu, int x, int y); void jkGuiRend_SetVisibleAndDraw(jkGuiElement *clickable, jkGuiMenu *menu, int bVisible); void jkGuiRend_ClickableHover(jkGuiMenu *menu, jkGuiElement *element, int a3); void jkGuiRend_sub_510C60(jkGuiElement *element); int jkGuiRend_ClickSound(jkGuiElement *element, jkGuiMenu *menu, int mouseX, int mouseY, int a5); void jkGuiRend_HoverOn(jkGuiElement *element, jkGuiMenu *menu, int a3); int jkGuiRend_ListBoxButtonDown(jkGuiElement *element, jkGuiMenu *menu, int mouseY, int mouseX); void jkGuiRend_ListBoxDraw(jkGuiElement *element_, jkGuiMenu *menu, stdVBuffer *vbuf, int a4); void jkGuiRend_CheckBoxDraw(jkGuiElement *element, jkGuiMenu *menu, stdVBuffer *vbuf, int redraw); int jkGuiRend_DrawClickableAndUpdatebool(jkGuiElement *element, jkGuiMenu *menu, int a, int b, int c); int jkGuiRend_WindowHandler(HWND hWnd, unsigned int a2, int wParam, unsigned int lParam, void* unused); void jkGuiRend_UpdateMouse(); void jkGuiRend_FlipAndDraw(jkGuiMenu *menu, rdRect *drawRect); void jkGuiRend_GetMousePos(int *pX, int *pY); void jkGuiRend_ResetMouseLatestMs(); void jkGuiRend_InvalidateGdi(); int jkGuiRend_SliderButtonDown(jkGuiElement *element, jkGuiMenu *menu, int a3, signed int a4); void jkGuiRend_SliderDraw(jkGuiElement *element, jkGuiMenu *menu, stdVBuffer *vbuf, int redraw); int jkGuiRend_TextBoxButtonDown(jkGuiElement *element, jkGuiMenu *menu, int a3, int a4); void jkGuiRend_TextBoxDraw(jkGuiElement *element, jkGuiMenu *menu, stdVBuffer *vbuf, int redraw); void jkGuiRend_TextDraw(jkGuiElement *element, jkGuiMenu *menu, stdVBuffer *outBuf, int redraw); int jkGuiRend_PicButtonButtonDown(jkGuiElement *element, jkGuiMenu *menu, int a, int b); void jkGuiRend_PicButtonDraw(jkGuiElement *element, jkGuiMenu *menu, stdVBuffer *vbuf, int redraw); int jkGuiRend_TextButtonButtonDown(jkGuiElement *element, jkGuiMenu *menu, int a3, int b); void jkGuiRend_TextButtonDraw(jkGuiElement *element, jkGuiMenu *menu, stdVBuffer *vbuf, int redraw); #endif // _JKGUIREND_H
49.08867
103
0.831711
09457e68303cb7a86ef40fd6f984110b3386e68a
163
h
C
ios/app/ViewController.h
FireSt-dead/cross.mobile
98a20215971cd9dbcaa2b1d263d2f1315972b0c9
[ "Apache-2.0" ]
null
null
null
ios/app/ViewController.h
FireSt-dead/cross.mobile
98a20215971cd9dbcaa2b1d263d2f1315972b0c9
[ "Apache-2.0" ]
null
null
null
ios/app/ViewController.h
FireSt-dead/cross.mobile
98a20215971cd9dbcaa2b1d263d2f1315972b0c9
[ "Apache-2.0" ]
null
null
null
// // ViewController.h // app // // Created by Panayot Cankov on 10/13/16. // // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
10.1875
44
0.656442
ab00fc94d35f0fff941acda330f426c5616feda9
2,521
c
C
main/jonj_ticks.c
jonj-src/jonj
da754bb2cb87a761ba11a09a5f0a02be4eb7ff35
[ "PHP-3.01" ]
null
null
null
main/jonj_ticks.c
jonj-src/jonj
da754bb2cb87a761ba11a09a5f0a02be4eb7ff35
[ "PHP-3.01" ]
null
null
null
main/jonj_ticks.c
jonj-src/jonj
da754bb2cb87a761ba11a09a5f0a02be4eb7ff35
[ "PHP-3.01" ]
null
null
null
/* +----------------------------------------------------------------------+ | JONJ Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The JONJ Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the JONJ license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.jonj.tk/license/3_01.txt | | If you did not receive a copy of the JONJ license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@jonj.tk so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Stig Bakken <ssb@jonj.tk> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include "jonj.h" #include "jonj_ticks.h" int jonj_startup_ticks(TSRMLS_D) { zend_llist_init(&PG(tick_functions), sizeof(void(*)(int)), NULL, 1); return SUCCESS; } void jonj_deactivate_ticks(TSRMLS_D) { zend_llist_clean(&PG(tick_functions)); } void jonj_shutdown_ticks(TSRMLS_D) { zend_llist_destroy(&PG(tick_functions)); } static int jonj_compare_tick_functions(void *elem1, void *elem2) { void(*func1)(int); void(*func2)(int); memcpy(&func1, elem1, sizeof(void(*)(int))); memcpy(&func2, elem2, sizeof(void(*)(int))); return (func1 == func2); } JONJAPI void jonj_add_tick_function(void (*func)(int)) { TSRMLS_FETCH(); zend_llist_add_element(&PG(tick_functions), (void *)&func); } JONJAPI void jonj_remove_tick_function(void (*func)(int)) { TSRMLS_FETCH(); zend_llist_del_element(&PG(tick_functions), (void *)func, (int(*)(void*, void*))jonj_compare_tick_functions); } static void jonj_tick_iterator(void *data, void *arg TSRMLS_DC) { void (*func)(int); memcpy(&func, data, sizeof(void(*)(int))); func(*((int *)arg)); } void jonj_run_ticks(int count) { TSRMLS_FETCH(); zend_llist_apply_with_argument(&PG(tick_functions), (llist_apply_with_arg_func_t) jonj_tick_iterator, &count TSRMLS_CC); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
28.977011
121
0.535502
799bbee5336dc204911e800977e3bd54a36a216b
206
h
C
iOS/10.0.2/protocols/_SFDialogViewDelegate.h
onmyway133/Runtime-Headers
e9b80e7ab9103f37ad421ad6b8b58ee06369d21f
[ "MIT" ]
30
2016-10-09T20:13:00.000Z
2022-01-24T04:14:57.000Z
iOS/10.0.2/protocols/_SFDialogViewDelegate.h
onmyway133/Runtime-Headers
e9b80e7ab9103f37ad421ad6b8b58ee06369d21f
[ "MIT" ]
null
null
null
iOS/10.0.2/protocols/_SFDialogViewDelegate.h
onmyway133/Runtime-Headers
e9b80e7ab9103f37ad421ad6b8b58ee06369d21f
[ "MIT" ]
7
2017-08-29T14:41:25.000Z
2022-01-19T17:14:54.000Z
/* Generated by RuntimeBrowser. */ @protocol _SFDialogViewDelegate <NSObject> @optional - (void)dialogView:(_SFDialogView *)arg1 didSelectPrimaryAction:(bool)arg2 withPromptText:(NSString *)arg3; @end
18.727273
107
0.776699
66094f3b604e6973bfacebf83b21b0ef157c1b7e
5,332
c
C
src/adt/bitmap.c
data-man/libfsm
90eb0e0794f4eee2e65584549104023f224fed89
[ "BSD-2-Clause" ]
766
2017-02-01T21:47:09.000Z
2022-03-30T23:14:02.000Z
src/adt/bitmap.c
data-man/libfsm
90eb0e0794f4eee2e65584549104023f224fed89
[ "BSD-2-Clause" ]
174
2017-02-02T18:11:46.000Z
2022-02-24T23:06:17.000Z
src/adt/bitmap.c
data-man/libfsm
90eb0e0794f4eee2e65584549104023f224fed89
[ "BSD-2-Clause" ]
52
2017-02-01T21:45:45.000Z
2022-01-25T09:21:30.000Z
/* * Copyright 2008-2017 Katherine Flavel * * See LICENCE for the full copyright terms. */ #include <assert.h> #include <stddef.h> #include <stdio.h> #include <limits.h> #include <ctype.h> #include <print/esc.h> #include <adt/bitmap.h> int bm_get(const struct bm *bm, size_t i) { assert(bm != NULL); assert(i <= UCHAR_MAX); return bm->map[i / CHAR_BIT] & (1 << i % CHAR_BIT); } void bm_set(struct bm *bm, size_t i) { assert(bm != NULL); assert(i <= UCHAR_MAX); bm->map[i / CHAR_BIT] |= (1 << i % CHAR_BIT); } size_t bm_next(const struct bm *bm, int i, int value) { size_t n; assert(bm != NULL); assert(i / CHAR_BIT < UCHAR_MAX); /* this could be faster by incrementing per element instead of per bit */ for (n = i + 1; n <= UCHAR_MAX; n++) { /* ...and this could be faster by using peter wegner's method */ if (!(bm->map[n / CHAR_BIT] & (1 << n % CHAR_BIT)) == !value) { return n; } } return UCHAR_MAX + 1; } unsigned int bm_count(const struct bm *bm) { unsigned char c; unsigned int count; size_t n; assert(bm != NULL); count = 0; /* this could be faster using richard hamming's method */ for (n = 0; n < sizeof bm->map; n++) { /* counting bits set for an element, peter wegner's method */ for (c = bm->map[n]; c != 0; c &= c - 1) { count++; } } return count; } void bm_clear(struct bm *bm) { static const struct bm bm_empty; assert(bm != NULL); *bm = bm_empty; } void bm_invert(struct bm *bm) { size_t n; assert(bm != NULL); for (n = 0; n < sizeof bm->map; n++) { bm->map[n] = ~bm->map[n]; } } int bm_print(FILE *f, const struct fsm_options *opt, const struct bm *bm, int boxed, escputc *escputc) { unsigned int count; int hi, lo; int r, n; enum { MODE_INVERT, MODE_SINGLE, MODE_ANY, MODE_MANY } mode; assert(f != NULL); assert(bm != NULL); assert(escputc != NULL); count = bm_count(bm); if (count == 1 && !boxed) { mode = MODE_SINGLE; } else if (bm_next(bm, UCHAR_MAX, 1) != UCHAR_MAX + 1) { mode = MODE_MANY; } else if (count == UCHAR_MAX + 1 && !boxed) { mode = MODE_ANY; } else if (count <= UCHAR_MAX / 2) { mode = MODE_MANY; } else { mode = MODE_INVERT; } /* TODO: would prefer to show ranges before other characters. * maybe best to do that by splitting the bitmap, and using two passes */ /* XXX: all literal characters here really should go through escputc */ if (mode == MODE_ANY) { return fputs("/./", f); } n = 0; r = fprintf(f, "%s%s", mode == MODE_SINGLE ? "" : "[", mode != MODE_INVERT ? "" : "^"); if (r == -1) { return -1; } n += r; hi = -1; for (;;) { /* start of range */ lo = bm_next(bm, hi, mode != MODE_INVERT); if (lo > UCHAR_MAX) { break; } /* end of range */ hi = bm_next(bm, lo, mode == MODE_INVERT); if (hi > UCHAR_MAX && lo < UCHAR_MAX) { hi = UCHAR_MAX; } if (!isalnum((unsigned char) lo) && isalnum((unsigned char) hi)) { r = escputc(f, opt, lo); if (r == -1) { return -1; } n += r; hi = lo; continue; } /* bring down endpoint, if it's past the end of the class */ if (isalnum((unsigned char) lo)) { size_t i; const struct { int (*is)(int); int end; } a[] = { { isdigit, '9' }, { isupper, 'Z' }, { islower, 'z' } }; /* XXX: assumes ASCII */ for (i = 0; i < sizeof a / sizeof *a; i++) { if (a[i].is((unsigned char) lo)) { if (!a[i].is((unsigned char) hi)) { hi = a[i].end + 1; } break; } } assert(i < sizeof a / sizeof *a); } assert(hi > lo); switch (hi - lo) { case 1: case 2: case 3: r = escputc(f, opt, lo); if (r == -1) { return -1; } n += r; hi = lo; break; default: r = escputc(f, opt, lo); if (r == -1) { return -1; } n += r; r = putc('-', f); if (r == EOF) { return -1; } n += 1; r = escputc(f, opt, hi - 1); if (r == -1) { return -1; } n += r; break; } } r = fprintf(f, "%s", mode == MODE_SINGLE ? "" : "]"); if (r == -1) { return -1; } n += r; return n; } int bm_snprint(const struct bm *bm, const struct fsm_options *opt, char *s, size_t n, int boxed, escputc *escputc) { FILE *f; int r; assert(bm != NULL); assert(escputc != NULL); if (n == 0) { return 0; } assert(s != NULL); /* * I didn't want two sets of escputc functions (for strings and files), * so I've nominated to use FILE * as the common interface, * in order to keep just one kind of escputc. * * I also didn't want to duplicate the contents of bm_print(), * so here I'm opting to print to a temporary file, rewind, * and read it back for string output. This is not ideal. */ f = tmpfile(); if (f == NULL) { return -1; } r = bm_print(f, opt, bm, boxed, escputc); if (r == -1) { goto error; } assert(r >= 0); if (n > (size_t) r + 1) { n = (size_t) r + 1; } rewind(f); if (n - 1 != fread(s, 1, n - 1, f)) { /* short read or unexpected zero */ goto error; } /* expected zero could also be an error, but we don't mind if it is * (although setting errno is bad form) */ #ifndef NDEBUG assert(fgetc(f) == EOF); if (ferror(f)) { goto error; } assert(feof(f)); #endif s[n - 1] = '\0'; if (EOF == fclose(f)) { return -1; } return r; error: (void) fclose(f); return -1; }
16.50774
74
0.557389
61ca9d0d9c0893fb2eb53011c353e640aeed9672
1,963
c
C
Datalogger/I2CDevices/mcp23018.c
stvnrhodes/calsol
d120f375b686bf979115c82b6db29ba5791c28c2
[ "Apache-2.0" ]
1
2022-02-08T14:10:41.000Z
2022-02-08T14:10:41.000Z
calsol-datalogger.X/I2CDevices/mcp23018.c
CalSol/datalogger-pic24
23fe125f6a60ca74c0691f606bf4365b20d1aa24
[ "BSD-3-Clause" ]
null
null
null
calsol-datalogger.X/I2CDevices/mcp23018.c
CalSol/datalogger-pic24
23fe125f6a60ca74c0691f606bf4365b20d1aa24
[ "BSD-3-Clause" ]
null
null
null
/* * File: mcp23018.c * Author: Ducky * * Created on January 30, 2011, 5:05 PM * * Revision History * Date Author Change * 21 Jul 2011 Ducky Added this change history box, * changed chip to MCP23018 (although code is similar), * did some refactoring. * * @file * MCP23018 GPIO expander library. */ #include "i2c-hardware.h" #include "mcp23018.h" /** * Initializes the MCP23018 I2C Interface. */ void MCP23018_Init() { I2C_Init(); I2C_SetSpeed(I2C_SPEED_400KHZ); } /** * Puts the 7-bit device address plus R/W bit on the I2C bus. * This function blocks until the transmission completes. * * @param[in] addr 3-bit MCP23018 address set by A2, A1, A0 pins in the lowest 3 bits. * @param[in] rw Read or /Write (1 for read, 0 for write). * @return The ACK bit from the device. * @retval 0 Device has sent an acknowledge. * @retval 1 Device has not sent an acknowledge. */ inline uint8_t MCP23018_SendControlByte(uint8_t addr, uint8_t rw) { MCP23018_Init(); return I2C_Send7BitAddress(MCP23018_I2C_ADDR | addr, rw); } uint8_t MCP23018_SingleRegisterWrite(uint8_t addr, uint8_t reg, uint8_t data) { MCP23018_Init(); if (!I2C_SendStart()) { return 0; } if (MCP23018_SendControlByte(addr, I2C_RW_WRITE)) { I2C_SendStop(); return 0; } if (I2C_SendByte(reg)) { I2C_SendStop(); return 0; } if (I2C_SendByte(data)) { I2C_SendStop(); return 0; } I2C_SendStop(); return 1; } uint8_t MCP23018_SingleRegisterRead(uint8_t addr, uint8_t reg, uint8_t *data) { MCP23018_Init(); if (!I2C_SendStart()) { return 0; } if (MCP23018_SendControlByte(addr, I2C_RW_WRITE)) { I2C_SendStop(); return 0; } if (I2C_SendByte(reg)) { I2C_SendStop(); return 0; } I2C_SendRepeatedStart(); if (MCP23018_SendControlByte(addr, I2C_RW_READ)) { I2C_SendStop(); return 0; } if (I2C_ReadByte(I2C_SEND_NACK, data)) { I2C_SendStop(); return 1; } else { I2C1CONbits.I2CEN = 0; return 0; } }
19.245098
86
0.687723
e8a1fd5208cf2cf95a67cb85485aa6cb38b88c47
1,298
h
C
plugins/1bs_bitdrive/DistrhoPluginInfo.h
linuxmao-org/shiru-plugins
08853f99140012234649e67e5647906fda74f6cc
[ "WTFPL" ]
11
2019-06-15T06:36:36.000Z
2022-02-22T04:49:22.000Z
plugins/1bs_bitdrive/DistrhoPluginInfo.h
nyxkn/shiru-plugins
8088c04b94afb498cec6a14bd03c448936bf31e9
[ "WTFPL" ]
6
2019-06-15T14:04:49.000Z
2019-11-27T15:35:13.000Z
plugins/1bs_bitdrive/DistrhoPluginInfo.h
nyxkn/shiru-plugins
8088c04b94afb498cec6a14bd03c448936bf31e9
[ "WTFPL" ]
2
2020-12-30T00:21:35.000Z
2021-07-04T18:32:46.000Z
#pragma once #define DISTRHO_PLUGIN_BRAND "Shiru" #define DISTRHO_PLUGIN_NAME "1bitstudio - bitdrive" #define DISTRHO_PLUGIN_URI "https://github.com/linuxmao-org/shiru-plugins/1bs_bitdrive" #define DISTRHO_PLUGIN_HOMEPAGE "https://github.com/linuxmao-org/shiru-plugins/1bs_bitdrive" #define DISTRHO_PLUGIN_UNIQUE_ID '1','b','b','d' #define DISTRHO_PLUGIN_VERSION 0,12,0 #define DISTRHO_PLUGIN_LABEL "1bitstudio - bitdrive" #define DISTRHO_PLUGIN_LICENSE "http://spdx.org/licenses/WTFPL" #define DISTRHO_PLUGIN_MAKER "Shiru" #define DISTRHO_PLUGIN_DESCRIPTION "v0.12 02.06.19 [LinuxMAO]" #define DISTRHO_PLUGIN_NUM_INPUTS 2 #define DISTRHO_PLUGIN_NUM_OUTPUTS 2 #define DISTRHO_PLUGIN_IS_SYNTH 0 #define DISTRHO_PLUGIN_HAS_UI 0 #define DISTRHO_PLUGIN_HAS_EMBED_UI 0 #define DISTRHO_PLUGIN_HAS_EXTERNAL_UI 0 #define DISTRHO_PLUGIN_IS_RT_SAFE 1 #define DISTRHO_PLUGIN_WANT_PROGRAMS 0 #define DISTRHO_PLUGIN_WANT_STATE 0 #define DISTRHO_PLUGIN_WANT_FULL_STATE 0 #define DISTRHO_PLUGIN_NUM_PROGRAMS 0 enum { /* parameter IDs */ pIdBypass, pIdInputGain, pIdThreshold, pIdOutputGain, Parameter_Count }; enum { /* state IDs */ State_Count };
33.282051
99
0.725732
797f6cd125f1476422bcd89adfc12549914eb09c
760
h
C
decode.h
shilei-massclouds/xemu
9554b00a5752772d3c0846e881e1f30f9f915d4a
[ "MIT" ]
null
null
null
decode.h
shilei-massclouds/xemu
9554b00a5752772d3c0846e881e1f30f9f915d4a
[ "MIT" ]
null
null
null
decode.h
shilei-massclouds/xemu
9554b00a5752772d3c0846e881e1f30f9f915d4a
[ "MIT" ]
null
null
null
/* * Decode */ #ifndef DECODE_H #define DECODE_H #include <stdint.h> #include "operation.h" uint64_t decode(uint64_t pc, uint32_t inst, op_t *op, uint32_t *rd, uint32_t *rs1, uint32_t *rs2, uint64_t *imm, uint32_t *csr_addr, uint32_t *opcode); void dec32(uint64_t pc, uint32_t inst, op_t *op, uint32_t *rd, uint32_t *rs1, uint32_t *rs2, uint64_t *imm, uint32_t *csr_addr, uint32_t *opcode); void dec16(uint64_t pc, uint16_t inst, op_t *op, uint32_t *rd, uint32_t *rs1, uint32_t *rs2, uint64_t *imm, uint32_t *csr_addr, uint32_t *opcode); #endif /* DECODE_H */
16.521739
27
0.543421
053fe9c2858df52b8c6c818c14d2facb5632730e
2,139
h
C
src/ccpp_fields_idx.h
akubaryk/ccpp-framework
d32b965b11882a42d9db522dc13823b7720b63aa
[ "Apache-2.0" ]
null
null
null
src/ccpp_fields_idx.h
akubaryk/ccpp-framework
d32b965b11882a42d9db522dc13823b7720b63aa
[ "Apache-2.0" ]
null
null
null
src/ccpp_fields_idx.h
akubaryk/ccpp-framework
d32b965b11882a42d9db522dc13823b7720b63aa
[ "Apache-2.0" ]
null
null
null
/* * This work (Common Community Physics Package), identified by NOAA, NCAR, * CU/CIRES, is free of known copyright restrictions and is placed in the * public domain. * * 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 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 ccpp_fields_idx.h * * Routines and functions to generate and lookup * fields/variables needed for the physics routines. * * @ingroup Physics * @{ **/ #ifndef CCPP_FIELD_IDX_H #define CCPP_FIELD_IDX_H #ifdef __cplusplus extern "C" { #endif #define CCPP_FIELD_IDX_MAX 1500 #define CCPP_FIELD_IDX_GROW 2 struct ccpp_field { int n; /**< Location within nodes array **/ char *name; /**< Name of the field **/ }; struct ccpp_field_idx { int sorted; /**< Sorted flag. 0=unsorted, 1=sorted **/ int n; /**< Current number of used nodes **/ int max; /**< Maximum nodes allocated **/ struct ccpp_field **fields; /**< Array of fields **/ }; /** CCPP field index initialization routine. **/ int ccpp_field_idx_init(void **); /** CCPP field index finalization routine. **/ int ccpp_field_idx_finalize(void **); /** CCPP field index add/insert a field. **/ int ccpp_field_idx_add(const char *, void **); /** CCPP field index find a field location. **/ int ccpp_field_idx_find(const char *, void **); /** CCPP field index sorting routine. **/ static int ccpp_field_idx_sort(void **); /** CCPP field index array extension. **/ static int ccpp_field_idx_grow(void **); /** CCPP field index maximum number of fields. **/ int ccpp_field_idx_max(void **); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* CCPP_FIELD_IDX_H */ /** * @} **/
26.407407
77
0.661524
baaba95fe3034b644bfcec6e912aefb6cab3e3af
395
c
C
Exam Preparation/String Copy/main.c
wrench1815/C-Programs-repo
874ce59c21a9ea04c74f94b232284e0f75170b26
[ "CC0-1.0" ]
null
null
null
Exam Preparation/String Copy/main.c
wrench1815/C-Programs-repo
874ce59c21a9ea04c74f94b232284e0f75170b26
[ "CC0-1.0" ]
null
null
null
Exam Preparation/String Copy/main.c
wrench1815/C-Programs-repo
874ce59c21a9ea04c74f94b232284e0f75170b26
[ "CC0-1.0" ]
null
null
null
#include <stdio.h> #include <stdlib.h> void stringcpy(char *, char *); int main() { char s1[99], s2[99]; printf("Enter Source String\n"); gets(s1); stringcpy(s2, s1); printf("Source String :- %s\n", s1); printf("Target String :- %s\n", s2); return 0; } void stringcpy(char*b, char*a) { while (*a != '\0') { *b = *a; b++; a++; } *b = '\0'; }
12.741935
38
0.498734