repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
patil215/v8
src/objects/slots-inl.h
<reponame>patil215/v8 // Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_OBJECTS_SLOTS_INL_H_ #define V8_OBJECTS_SLOTS_INL_H_ #include "src/objects/slots.h" #include "src/base/atomic-utils.h" #include "src/memcopy.h" #include "src/objects.h" #include "src/objects/heap-object-inl.h" #include "src/objects/maybe-object.h" #ifdef V8_COMPRESS_POINTERS #include "src/ptr-compr-inl.h" #endif namespace v8 { namespace internal { // // FullObjectSlot implementation. // FullObjectSlot::FullObjectSlot(Object* object) : SlotBase(reinterpret_cast<Address>(&object->ptr_)) {} bool FullObjectSlot::contains_value(Address raw_value) const { return base::AsAtomicPointer::Relaxed_Load(location()) == raw_value; } const Object FullObjectSlot::operator*() const { return Object(*location()); } void FullObjectSlot::store(Object value) const { *location() = value->ptr(); } Object FullObjectSlot::Acquire_Load() const { return Object(base::AsAtomicPointer::Acquire_Load(location())); } Object FullObjectSlot::Relaxed_Load() const { return Object(base::AsAtomicPointer::Relaxed_Load(location())); } void FullObjectSlot::Relaxed_Store(Object value) const { base::AsAtomicPointer::Relaxed_Store(location(), value->ptr()); } void FullObjectSlot::Release_Store(Object value) const { base::AsAtomicPointer::Release_Store(location(), value->ptr()); } Object FullObjectSlot::Release_CompareAndSwap(Object old, Object target) const { Address result = base::AsAtomicPointer::Release_CompareAndSwap( location(), old->ptr(), target->ptr()); return Object(result); } // // FullMaybeObjectSlot implementation. // const MaybeObject FullMaybeObjectSlot::operator*() const { return MaybeObject(*location()); } void FullMaybeObjectSlot::store(MaybeObject value) const { *location() = value.ptr(); } MaybeObject FullMaybeObjectSlot::Relaxed_Load() const { return MaybeObject(AsAtomicTagged::Relaxed_Load(location())); } void FullMaybeObjectSlot::Relaxed_Store(MaybeObject value) const { AsAtomicTagged::Relaxed_Store(location(), value->ptr()); } void FullMaybeObjectSlot::Release_CompareAndSwap(MaybeObject old, MaybeObject target) const { AsAtomicTagged::Release_CompareAndSwap(location(), old.ptr(), target.ptr()); } // // FullHeapObjectSlot implementation. // const HeapObjectReference FullHeapObjectSlot::operator*() const { return HeapObjectReference(*location()); } void FullHeapObjectSlot::store(HeapObjectReference value) const { *location() = value.ptr(); } HeapObject FullHeapObjectSlot::ToHeapObject() const { DCHECK((*location() & kHeapObjectTagMask) == kHeapObjectTag); return HeapObject::cast(Object(*location())); } void FullHeapObjectSlot::StoreHeapObject(HeapObject value) const { *location() = value->ptr(); } // // Utils. // // Sets |counter| number of kTaggedSize-sized values starting at |start| slot. inline void MemsetTagged(ObjectSlot start, Object value, size_t counter) { // TODO(ishell): revisit this implementation, maybe use "rep stosl" STATIC_ASSERT(kTaggedSize == kSystemPointerSize); Address raw_value = value.ptr(); #ifdef V8_COMPRESS_POINTERS raw_value = CompressTagged(raw_value); #endif MemsetPointer(start.location(), raw_value, counter); } // Sets |counter| number of kSystemPointerSize-sized values starting at |start| // slot. inline void MemsetPointer(FullObjectSlot start, Object value, size_t counter) { MemsetPointer(start.location(), value.ptr(), counter); } } // namespace internal } // namespace v8 #endif // V8_OBJECTS_SLOTS_INL_H_
patil215/v8
src/ptr-compr-inl.h
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_PTR_COMPR_INL_H_ #define V8_PTR_COMPR_INL_H_ #if V8_TARGET_ARCH_64_BIT #include "src/objects/heap-object-inl.h" #include "src/ptr-compr.h" namespace v8 { namespace internal { // Compresses full-pointer representation of a tagged value to on-heap // representation. V8_INLINE Tagged_t CompressTagged(Address tagged) { return static_cast<Tagged_t>(static_cast<uint32_t>(tagged)); } // Calculates isolate root value from any on-heap address. V8_INLINE Address GetRootFromOnHeapAddress(Address addr) { return RoundDown(addr + kPtrComprIsolateRootBias, kPtrComprIsolateRootAlignment); } // Decompresses weak or strong heap object pointer or forwarding pointer, // preserving both weak- and smi- tags. V8_INLINE Address DecompressTaggedPointer(Address on_heap_addr, Tagged_t raw_value) { static_assert(kTaggedSize == kSystemPointerSize, "has to be updated"); static_assert(!std::is_same<int32_t, Tagged_t>::value, "remove cast below"); int32_t value = static_cast<int32_t>(raw_value); Address root = GetRootFromOnHeapAddress(on_heap_addr); // Current compression scheme requires value to be sign-extended to inptr_t // before adding the |root|. return root + static_cast<Address>(static_cast<intptr_t>(value)); } // Decompresses any tagged value, preserving both weak- and smi- tags. V8_INLINE Address DecompressTaggedAny(Address on_heap_addr, Tagged_t raw_value) { static_assert(kTaggedSize == kSystemPointerSize, "has to be updated"); static_assert(!std::is_same<int32_t, Tagged_t>::value, "remove cast below"); int32_t value = static_cast<int32_t>(raw_value); // |root_mask| is 0 if the |value| was a smi or -1 otherwise. Address root_mask = -static_cast<Address>(value & kSmiTagMask); Address root_or_zero = root_mask & GetRootFromOnHeapAddress(on_heap_addr); // Current compression scheme requires value to be sign-extended to inptr_t // before adding the |root_or_zero|. return root_or_zero + static_cast<Address>(static_cast<intptr_t>(value)); } STATIC_ASSERT(kPtrComprHeapReservationSize == Internals::kPtrComprHeapReservationSize); STATIC_ASSERT(kPtrComprIsolateRootBias == Internals::kPtrComprIsolateRootBias); STATIC_ASSERT(kPtrComprIsolateRootAlignment == Internals::kPtrComprIsolateRootAlignment); // // CompressedObjectSlot implementation. // CompressedObjectSlot::CompressedObjectSlot(Object* object) : SlotBase(reinterpret_cast<Address>(&object->ptr_)) {} Object CompressedObjectSlot::operator*() const { Tagged_t value = *location(); return Object(DecompressTaggedAny(address(), value)); } void CompressedObjectSlot::store(Object value) const { *location() = CompressTagged(value->ptr()); } Object CompressedObjectSlot::Acquire_Load() const { AtomicTagged_t value = AsAtomicTagged::Acquire_Load(location()); return Object(DecompressTaggedAny(address(), value)); } Object CompressedObjectSlot::Relaxed_Load() const { AtomicTagged_t value = AsAtomicTagged::Relaxed_Load(location()); return Object(DecompressTaggedAny(address(), value)); } void CompressedObjectSlot::Relaxed_Store(Object value) const { Tagged_t ptr = CompressTagged(value->ptr()); AsAtomicTagged::Relaxed_Store(location(), ptr); } void CompressedObjectSlot::Release_Store(Object value) const { Tagged_t ptr = CompressTagged(value->ptr()); AsAtomicTagged::Release_Store(location(), ptr); } Object CompressedObjectSlot::Release_CompareAndSwap(Object old, Object target) const { Tagged_t old_ptr = CompressTagged(old->ptr()); Tagged_t target_ptr = CompressTagged(target->ptr()); Tagged_t result = AsAtomicTagged::Release_CompareAndSwap(location(), old_ptr, target_ptr); return Object(DecompressTaggedAny(address(), result)); } // // CompressedMapWordSlot implementation. // bool CompressedMapWordSlot::contains_value(Address raw_value) const { AtomicTagged_t value = AsAtomicTagged::Relaxed_Load(location()); return static_cast<uint32_t>(value) == static_cast<uint32_t>(static_cast<Tagged_t>(raw_value)); } Object CompressedMapWordSlot::operator*() const { Tagged_t value = *location(); return Object(DecompressTaggedPointer(address(), value)); } void CompressedMapWordSlot::store(Object value) const { *location() = CompressTagged(value.ptr()); } Object CompressedMapWordSlot::Relaxed_Load() const { AtomicTagged_t value = AsAtomicTagged::Relaxed_Load(location()); return Object(DecompressTaggedPointer(address(), value)); } void CompressedMapWordSlot::Relaxed_Store(Object value) const { Tagged_t ptr = CompressTagged(value.ptr()); AsAtomicTagged::Relaxed_Store(location(), ptr); } Object CompressedMapWordSlot::Acquire_Load() const { AtomicTagged_t value = AsAtomicTagged::Acquire_Load(location()); return Object(DecompressTaggedPointer(address(), value)); } void CompressedMapWordSlot::Release_Store(Object value) const { Tagged_t ptr = CompressTagged(value->ptr()); AsAtomicTagged::Release_Store(location(), ptr); } Object CompressedMapWordSlot::Release_CompareAndSwap(Object old, Object target) const { Tagged_t old_ptr = CompressTagged(old->ptr()); Tagged_t target_ptr = CompressTagged(target->ptr()); Tagged_t result = AsAtomicTagged::Release_CompareAndSwap(location(), old_ptr, target_ptr); return Object(DecompressTaggedPointer(address(), result)); } // // CompressedMaybeObjectSlot implementation. // MaybeObject CompressedMaybeObjectSlot::operator*() const { Tagged_t value = *location(); return MaybeObject(DecompressTaggedAny(address(), value)); } void CompressedMaybeObjectSlot::store(MaybeObject value) const { *location() = CompressTagged(value->ptr()); } MaybeObject CompressedMaybeObjectSlot::Relaxed_Load() const { AtomicTagged_t value = AsAtomicTagged::Relaxed_Load(location()); return MaybeObject(DecompressTaggedAny(address(), value)); } void CompressedMaybeObjectSlot::Relaxed_Store(MaybeObject value) const { Tagged_t ptr = CompressTagged(value->ptr()); AsAtomicTagged::Relaxed_Store(location(), ptr); } void CompressedMaybeObjectSlot::Release_CompareAndSwap( MaybeObject old, MaybeObject target) const { Tagged_t old_ptr = CompressTagged(old->ptr()); Tagged_t target_ptr = CompressTagged(target->ptr()); AsAtomicTagged::Release_CompareAndSwap(location(), old_ptr, target_ptr); } // // CompressedHeapObjectSlot implementation. // HeapObjectReference CompressedHeapObjectSlot::operator*() const { Tagged_t value = *location(); return HeapObjectReference(DecompressTaggedPointer(address(), value)); } void CompressedHeapObjectSlot::store(HeapObjectReference value) const { *location() = CompressTagged(value.ptr()); } HeapObject CompressedHeapObjectSlot::ToHeapObject() const { Tagged_t value = *location(); DCHECK_EQ(value & kHeapObjectTagMask, kHeapObjectTag); return HeapObject::cast(Object(DecompressTaggedPointer(address(), value))); } void CompressedHeapObjectSlot::StoreHeapObject(HeapObject value) const { *location() = CompressTagged(value->ptr()); } } // namespace internal } // namespace v8 #endif // V8_TARGET_ARCH_64_BIT #endif // V8_PTR_COMPR_INL_H_
patil215/v8
src/objects/builtin-function-id.h
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_OBJECTS_BUILTIN_FUNCTION_ID_H_ #define V8_OBJECTS_BUILTIN_FUNCTION_ID_H_ #include <stdint.h> namespace v8 { namespace internal { // List of builtin functions we want to identify to improve code // generation. // // Each entry has a name of a global object property holding an object // optionally followed by ".prototype", a name of a builtin function // on the object (the one the id is set for), and a label. // // Installation of ids for the selected builtin functions is handled // by the bootstrapper. #define FUNCTIONS_WITH_ID_LIST(V) \ V(Array, isArray, ArrayIsArray) \ V(Array.prototype, concat, ArrayConcat) \ V(Array.prototype, every, ArrayEvery) \ V(Array.prototype, fill, ArrayFill) \ V(Array.prototype, filter, ArrayFilter) \ V(Array.prototype, findIndex, ArrayFindIndex) \ V(Array.prototype, forEach, ArrayForEach) \ V(Array.prototype, includes, ArrayIncludes) \ V(Array.prototype, indexOf, ArrayIndexOf) \ V(Array.prototype, join, ArrayJoin) \ V(Array.prototype, lastIndexOf, ArrayLastIndexOf) \ V(Array.prototype, map, ArrayMap) \ V(Array.prototype, pop, ArrayPop) \ V(Array.prototype, push, ArrayPush) \ V(Array.prototype, reverse, ArrayReverse) \ V(Array.prototype, shift, ArrayShift) \ V(Array.prototype, slice, ArraySlice) \ V(Array.prototype, some, ArraySome) \ V(Array.prototype, splice, ArraySplice) \ V(Array.prototype, unshift, ArrayUnshift) \ V(Date, now, DateNow) \ V(Date.prototype, getDate, DateGetDate) \ V(Date.prototype, getDay, DateGetDay) \ V(Date.prototype, getFullYear, DateGetFullYear) \ V(Date.prototype, getHours, DateGetHours) \ V(Date.prototype, getMilliseconds, DateGetMilliseconds) \ V(Date.prototype, getMinutes, DateGetMinutes) \ V(Date.prototype, getMonth, DateGetMonth) \ V(Date.prototype, getSeconds, DateGetSeconds) \ V(Date.prototype, getTime, DateGetTime) \ V(Function.prototype, apply, FunctionApply) \ V(Function.prototype, bind, FunctionBind) \ V(Function.prototype, call, FunctionCall) \ V(Object, assign, ObjectAssign) \ V(Object, create, ObjectCreate) \ V(Object, is, ObjectIs) \ V(Object.prototype, hasOwnProperty, ObjectHasOwnProperty) \ V(Object.prototype, isPrototypeOf, ObjectIsPrototypeOf) \ V(Object.prototype, toString, ObjectToString) \ V(RegExp.prototype, compile, RegExpCompile) \ V(RegExp.prototype, exec, RegExpExec) \ V(RegExp.prototype, test, RegExpTest) \ V(RegExp.prototype, toString, RegExpToString) \ V(String.prototype, charCodeAt, StringCharCodeAt) \ V(String.prototype, charAt, StringCharAt) \ V(String.prototype, codePointAt, StringCodePointAt) \ V(String.prototype, concat, StringConcat) \ V(String.prototype, endsWith, StringEndsWith) \ V(String.prototype, includes, StringIncludes) \ V(String.prototype, indexOf, StringIndexOf) \ V(String.prototype, lastIndexOf, StringLastIndexOf) \ V(String.prototype, repeat, StringRepeat) \ V(String.prototype, slice, StringSlice) \ V(String.prototype, startsWith, StringStartsWith) \ V(String.prototype, substr, StringSubstr) \ V(String.prototype, substring, StringSubstring) \ V(String.prototype, toLowerCase, StringToLowerCase) \ V(String.prototype, toString, StringToString) \ V(String.prototype, toUpperCase, StringToUpperCase) \ V(String.prototype, trim, StringTrim) \ V(String.prototype, trimLeft, StringTrimStart) \ V(String.prototype, trimRight, StringTrimEnd) \ V(String.prototype, valueOf, StringValueOf) \ V(String, fromCharCode, StringFromCharCode) \ V(String, fromCodePoint, StringFromCodePoint) \ V(String, raw, StringRaw) \ V(Math, random, MathRandom) \ V(Math, floor, MathFloor) \ V(Math, round, MathRound) \ V(Math, ceil, MathCeil) \ V(Math, abs, MathAbs) \ V(Math, log, MathLog) \ V(Math, log1p, MathLog1p) \ V(Math, log2, MathLog2) \ V(Math, log10, MathLog10) \ V(Math, cbrt, MathCbrt) \ V(Math, exp, MathExp) \ V(Math, expm1, MathExpm1) \ V(Math, sqrt, MathSqrt) \ V(Math, pow, MathPow) \ V(Math, max, MathMax) \ V(Math, min, MathMin) \ V(Math, cos, MathCos) \ V(Math, cosh, MathCosh) \ V(Math, sign, MathSign) \ V(Math, sin, MathSin) \ V(Math, sinh, MathSinh) \ V(Math, tan, MathTan) \ V(Math, tanh, MathTanh) \ V(Math, acos, MathAcos) \ V(Math, acosh, MathAcosh) \ V(Math, asin, MathAsin) \ V(Math, asinh, MathAsinh) \ V(Math, atan, MathAtan) \ V(Math, atan2, MathAtan2) \ V(Math, checkReturnedType, MathCheckReturnedType) \ V(Math, atanh, MathAtanh) \ V(Math, imul, MathImul) \ V(Math, clz32, MathClz32) \ V(Math, fround, MathFround) \ V(Math, trunc, MathTrunc) \ V(Number, isFinite, NumberIsFinite) \ V(Number, isInteger, NumberIsInteger) \ V(Number, isNaN, NumberIsNaN) \ V(Number, isSafeInteger, NumberIsSafeInteger) \ V(Number, parseFloat, NumberParseFloat) \ V(Number, parseInt, NumberParseInt) \ V(Number.prototype, toString, NumberToString) \ V(Map.prototype, clear, MapClear) \ V(Map.prototype, delete, MapDelete) \ V(Map.prototype, entries, MapEntries) \ V(Map.prototype, forEach, MapForEach) \ V(Map.prototype, has, MapHas) \ V(Map.prototype, keys, MapKeys) \ V(Map.prototype, get, MapGet) \ V(Map.prototype, set, MapSet) \ V(Map.prototype, values, MapValues) \ V(Set.prototype, add, SetAdd) \ V(Set.prototype, clear, SetClear) \ V(Set.prototype, delete, SetDelete) \ V(Set.prototype, entries, SetEntries) \ V(Set.prototype, forEach, SetForEach) \ V(Set.prototype, has, SetHas) \ V(Set.prototype, values, SetValues) \ V(WeakMap.prototype, delete, WeakMapDelete) \ V(WeakMap.prototype, has, WeakMapHas) \ V(WeakMap.prototype, set, WeakMapSet) \ V(WeakSet.prototype, add, WeakSetAdd) \ V(WeakSet.prototype, delete, WeakSetDelete) \ V(WeakSet.prototype, has, WeakSetHas) #define ATOMIC_FUNCTIONS_WITH_ID_LIST(V) \ V(Atomics, load, AtomicsLoad) \ V(Atomics, store, AtomicsStore) \ V(Atomics, exchange, AtomicsExchange) \ V(Atomics, compareExchange, AtomicsCompareExchange) \ V(Atomics, add, AtomicsAdd) \ V(Atomics, sub, AtomicsSub) \ V(Atomics, and, AtomicsAnd) \ V(Atomics, or, AtomicsOr) \ V(Atomics, xor, AtomicsXor) enum class BuiltinFunctionId : uint8_t { kArrayConstructor, #define DECL_FUNCTION_ID(ignored1, ignore2, name) k##name, FUNCTIONS_WITH_ID_LIST(DECL_FUNCTION_ID) ATOMIC_FUNCTIONS_WITH_ID_LIST(DECL_FUNCTION_ID) #undef DECL_FUNCTION_ID // These are manually assigned to special getters during bootstrapping. kArrayBufferByteLength, kArrayBufferIsView, kArrayEntries, kArrayKeys, kArrayValues, kArrayIteratorNext, kBigIntConstructor, kMapSize, kSetSize, kMapIteratorNext, kSetIteratorNext, kDataViewBuffer, kDataViewByteLength, kDataViewByteOffset, kFunctionHasInstance, kGlobalDecodeURI, kGlobalDecodeURIComponent, kGlobalEncodeURI, kGlobalEncodeURIComponent, kGlobalEscape, kGlobalUnescape, kGlobalIsFinite, kGlobalIsNaN, kNumberConstructor, kPromiseAll, kPromisePrototypeCatch, kPromisePrototypeFinally, kPromisePrototypeThen, kPromiseRace, kPromiseReject, kPromiseResolve, kSymbolConstructor, kSymbolPrototypeToString, kSymbolPrototypeValueOf, kTypedArrayByteLength, kTypedArrayByteOffset, kTypedArrayEntries, kTypedArrayKeys, kTypedArrayLength, kTypedArrayToStringTag, kTypedArrayValues, kSharedArrayBufferByteLength, kStringConstructor, kStringIterator, kStringIteratorNext, kStringToLowerCaseIntl, kStringToUpperCaseIntl, kInvalidBuiltinFunctionId = static_cast<uint8_t>(-1), }; } // namespace internal } // namespace v8 #endif // V8_OBJECTS_BUILTIN_FUNCTION_ID_H_
patil215/v8
src/torque/declaration-visitor.h
// Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_TORQUE_DECLARATION_VISITOR_H_ #define V8_TORQUE_DECLARATION_VISITOR_H_ #include <set> #include <string> #include "src/base/macros.h" #include "src/torque/declarations.h" #include "src/torque/file-visitor.h" #include "src/torque/global-context.h" #include "src/torque/types.h" #include "src/torque/utils.h" namespace v8 { namespace internal { namespace torque { class DeclarationVisitor : public FileVisitor { public: void Visit(Ast* ast) { CurrentScope::Scope current_namespace(GlobalContext::GetDefaultNamespace()); for (Declaration* child : ast->declarations()) Visit(child); } void Visit(Declaration* decl); Namespace* GetOrCreateNamespace(const std::string& name) { std::vector<Namespace*> existing_namespaces = FilterDeclarables<Namespace>( Declarations::TryLookupShallow(QualifiedName(name))); if (existing_namespaces.empty()) { return Declarations::DeclareNamespace(name); } DCHECK_EQ(1, existing_namespaces.size()); return existing_namespaces.front(); } void Visit(NamespaceDeclaration* decl) { CurrentScope::Scope current_scope(GetOrCreateNamespace(decl->name)); for (Declaration* child : decl->declarations) Visit(child); } void Visit(TypeDeclaration* decl); void DeclareMethods(AggregateType* container, const std::vector<Declaration*>& methods); void Visit(StructDeclaration* decl); void Visit(ClassDeclaration* decl); void Visit(TypeAliasDeclaration* decl) { const Type* type = Declarations::GetType(decl->type); type->AddAlias(decl->name); Declarations::DeclareType(decl->name, type, true); } Builtin* CreateBuiltin(BuiltinDeclaration* decl, std::string external_name, std::string readable_name, Signature signature, base::Optional<Statement*> body); void Visit(ExternalBuiltinDeclaration* decl, const Signature& signature, base::Optional<Statement*> body) { Declarations::Declare( decl->name, CreateBuiltin(decl, decl->name, decl->name, signature, base::nullopt)); } void Visit(ExternalRuntimeDeclaration* decl, const Signature& sig, base::Optional<Statement*> body); void Visit(ExternalMacroDeclaration* decl, const Signature& sig, base::Optional<Statement*> body); void Visit(TorqueBuiltinDeclaration* decl, const Signature& signature, base::Optional<Statement*> body); void Visit(TorqueMacroDeclaration* decl, const Signature& signature, base::Optional<Statement*> body); void Visit(IntrinsicDeclaration* decl, const Signature& signature, base::Optional<Statement*> body); void Visit(CallableNode* decl, const Signature& signature, base::Optional<Statement*> body); void Visit(ConstDeclaration* decl); void Visit(StandardDeclaration* decl); void Visit(GenericDeclaration* decl); void Visit(SpecializationDeclaration* decl); void Visit(ExternConstDeclaration* decl); void Visit(CppIncludeDeclaration* decl); Signature MakeSpecializedSignature(const SpecializationKey& key); Callable* SpecializeImplicit(const SpecializationKey& key); Callable* Specialize(const SpecializationKey& key, CallableNode* declaration, base::Optional<const CallableNodeSignature*> signature, base::Optional<Statement*> body); void FinalizeStructsAndClasses(); private: void DeclareSpecializedTypes(const SpecializationKey& key); void FinalizeStructFieldsAndMethods(StructType* struct_type, StructDeclaration* struct_declaration); void FinalizeClassFieldsAndMethods(ClassType* class_type, ClassDeclaration* class_declaration); std::vector<std::tuple<Scope*, StructDeclaration*, StructType*>> struct_declarations_; std::vector<std::tuple<Scope*, ClassDeclaration*, ClassType*>> class_declarations_; }; } // namespace torque } // namespace internal } // namespace v8 #endif // V8_TORQUE_DECLARATION_VISITOR_H_
patil215/v8
src/builtins/builtins-typed-array-gen.h
<reponame>patil215/v8 // Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_BUILTINS_BUILTINS_TYPED_ARRAY_GEN_H_ #define V8_BUILTINS_BUILTINS_TYPED_ARRAY_GEN_H_ #include "src/code-stub-assembler.h" #include "torque-generated/builtins-typed-array-from-dsl-gen.h" namespace v8 { namespace internal { class TypedArrayBuiltinsAssembler : public CodeStubAssembler { public: using ElementsInfo = TypedArrayBuiltinsFromDSLAssembler::TypedArrayElementsInfo; explicit TypedArrayBuiltinsAssembler(compiler::CodeAssemblerState* state) : CodeStubAssembler(state) {} template <class... TArgs> TNode<JSTypedArray> TypedArraySpeciesCreate(const char* method_name, TNode<Context> context, TNode<JSTypedArray> exemplar, TArgs... args); TNode<JSTypedArray> TypedArraySpeciesCreateByLength( TNode<Context> context, TNode<JSTypedArray> exemplar, TNode<Smi> len, const char* method_name); void GenerateTypedArrayPrototypeIterationMethod(TNode<Context> context, TNode<Object> receiver, const char* method_name, IterationKind iteration_kind); void SetupTypedArray(TNode<JSTypedArray> holder, TNode<Smi> length, TNode<UintPtrT> byte_offset, TNode<UintPtrT> byte_length); void AttachBuffer(TNode<JSTypedArray> holder, TNode<JSArrayBuffer> buffer, TNode<Map> map, TNode<Smi> length, TNode<UintPtrT> byte_offset); TNode<JSArrayBuffer> AllocateEmptyOnHeapBuffer(TNode<Context> context, TNode<JSTypedArray> holder, TNode<UintPtrT> byte_length); TNode<FixedTypedArrayBase> AllocateOnHeapElements(TNode<Map> map, TNode<IntPtrT> byte_length, TNode<Number> length); TNode<Map> LoadMapForType(TNode<JSTypedArray> array); TNode<BoolT> IsMockArrayBufferAllocatorFlag(); TNode<UintPtrT> CalculateExternalPointer(TNode<UintPtrT> backing_store, TNode<UintPtrT> byte_offset); Node* LoadDataPtr(Node* typed_array); // Returns true if kind is either UINT8_ELEMENTS or UINT8_CLAMPED_ELEMENTS. TNode<Word32T> IsUint8ElementsKind(TNode<Word32T> kind); // Returns true if kind is either BIGINT64_ELEMENTS or BIGUINT64_ELEMENTS. TNode<Word32T> IsBigInt64ElementsKind(TNode<Word32T> kind); // Returns the byte size of an element for a TypedArray elements kind. TNode<IntPtrT> GetTypedArrayElementSize(TNode<Word32T> elements_kind); // Returns information (byte size and map) about a TypedArray's elements. ElementsInfo GetTypedArrayElementsInfo(TNode<JSTypedArray> typed_array); TNode<JSFunction> GetDefaultConstructor(TNode<Context> context, TNode<JSTypedArray> exemplar); TNode<JSTypedArray> TypedArrayCreateByLength(TNode<Context> context, TNode<Object> constructor, TNode<Smi> len, const char* method_name); void ThrowIfLengthLessThan(TNode<Context> context, TNode<JSTypedArray> typed_array, TNode<Smi> min_length); TNode<JSArrayBuffer> GetBuffer(TNode<Context> context, TNode<JSTypedArray> array); TNode<JSTypedArray> ValidateTypedArray(TNode<Context> context, TNode<Object> obj, const char* method_name); // Fast path for setting a TypedArray (source) onto another TypedArray // (target) at an element offset. void SetTypedArraySource(TNode<Context> context, TNode<JSTypedArray> source, TNode<JSTypedArray> target, TNode<IntPtrT> offset, Label* call_runtime, Label* if_source_too_large); void SetJSArraySource(TNode<Context> context, TNode<JSArray> source, TNode<JSTypedArray> target, TNode<IntPtrT> offset, Label* call_runtime, Label* if_source_too_large); void CallCMemmove(TNode<IntPtrT> dest_ptr, TNode<IntPtrT> src_ptr, TNode<IntPtrT> byte_length); void CallCMemcpy(TNode<RawPtrT> dest_ptr, TNode<RawPtrT> src_ptr, TNode<UintPtrT> byte_length); void CallCMemset(TNode<RawPtrT> dest_ptr, TNode<IntPtrT> value, TNode<UintPtrT> length); void CallCCopyFastNumberJSArrayElementsToTypedArray( TNode<Context> context, TNode<JSArray> source, TNode<JSTypedArray> dest, TNode<IntPtrT> source_length, TNode<IntPtrT> offset); void CallCCopyTypedArrayElementsToTypedArray(TNode<JSTypedArray> source, TNode<JSTypedArray> dest, TNode<IntPtrT> source_length, TNode<IntPtrT> offset); void CallCCopyTypedArrayElementsSlice(TNode<JSTypedArray> source, TNode<JSTypedArray> dest, TNode<IntPtrT> start, TNode<IntPtrT> end); typedef std::function<void(ElementsKind, int, int)> TypedArraySwitchCase; void DispatchTypedArrayByElementsKind( TNode<Word32T> elements_kind, const TypedArraySwitchCase& case_function); TNode<BoolT> IsSharedArrayBuffer(TNode<JSArrayBuffer> buffer); }; } // namespace internal } // namespace v8 #endif // V8_BUILTINS_BUILTINS_TYPED_ARRAY_GEN_H_
patil215/v8
src/typer-happy.h
#include <vector> #include <string> #include "src/conversions-inl.h" #include "src/compiler/types.h" #include "src/date.h" #include "src/globals.h" #ifndef V8_TYPER_HAPPY_H_ #define V8_TYPER_HAPPY_H_ namespace v8 { namespace internal { template <typename T> class Check { public: int id; const char * module; const char * name; void (*const checkingFunction)(T); Check(int _id, const char * _module, const char * _name, void (*const _checkingFunction)(T)) : id(_id), module(_module), name(_name), checkingFunction(_checkingFunction) {} }; class TyperHappy { template <class T> static void addCheck(std::vector<Check<T>> * list, const char * module, const char * name, void (*const checkingFunction)(T)) { list->push_back(Check<double> ((int) (list->size()) + 1, module, name, checkingFunction)); } // Creates list of checking functions for anything that can be represented as a double/number type. static std::vector<Check<double>> * createChecksDouble() { std::vector<Check<double>> * checks = new std::vector<Check<double>>(); addCheck(checks, "Math", "random", TyperHappy::checkPlainNumberType); addCheck(checks, "Math", "floor", TyperHappy::checkIntegerMinusZeroNaNUnionType); addCheck(checks, "Math", "ceil", TyperHappy::checkIntegerMinusZeroNaNUnionType); addCheck(checks, "Math", "round", TyperHappy::checkIntegerMinusZeroNaNUnionType); addCheck(checks, "Math", "trunc", TyperHappy::checkIntegerMinusZeroNaNUnionType); addCheck(checks, "Math", "abs", TyperHappy::checkPlainNumberNaNUnionType); addCheck(checks, "Math", "exp", TyperHappy::checkPlainNumberNaNUnionType); addCheck(checks, "Math", "expm1", TyperHappy::checkPlainNumberNaNUnionType); addCheck(checks, "Math", "acos", TyperHappy::checkNumberType); addCheck(checks, "Math", "acosh", TyperHappy::checkNumberType); addCheck(checks, "Math", "asinh", TyperHappy::checkNumberType); addCheck(checks, "Math", "atan", TyperHappy::checkNumberType); addCheck(checks, "Math", "atanh", TyperHappy::checkNumberType); addCheck(checks, "Math", "cbrt", TyperHappy::checkNumberType); addCheck(checks, "Math", "cos", TyperHappy::checkNumberType); addCheck(checks, "Math", "fround", TyperHappy::checkNumberType); addCheck(checks, "Math", "log", TyperHappy::checkNumberType); addCheck(checks, "Math", "log1p", TyperHappy::checkNumberType); addCheck(checks, "Math", "log10", TyperHappy::checkNumberType); addCheck(checks, "Math", "log2", TyperHappy::checkNumberType); addCheck(checks, "Math", "sin", TyperHappy::checkNumberType); addCheck(checks, "Math", "sqrt", TyperHappy::checkNumberType); addCheck(checks, "Math", "tan", TyperHappy::checkNumberType); addCheck(checks, "Math", "sign", TyperHappy::checkMathSignType); addCheck(checks, "Math", "atan2", TyperHappy::checkNumberType); addCheck(checks, "Math", "pow", TyperHappy::checkNumberType); addCheck(checks, "Math", "max", TyperHappy::checkNumberType); addCheck(checks, "Math", "min", TyperHappy::checkNumberType); addCheck(checks, "Math", "imul", TyperHappy::checkSigned32Type); addCheck(checks, "Math", "clz32", TyperHappy::checkMathClz32); addCheck(checks, "Date", "now", TyperHappy::checkDateNow); addCheck(checks, "Date", "getDate", TyperHappy::checkDateGetDate); addCheck(checks, "Date", "getDay", TyperHappy::checkDateGetDay); addCheck(checks, "Date", "getFullYear", TyperHappy::checkDateGetFullYear); addCheck(checks, "Date", "getHours", TyperHappy::checkDateGetHours); addCheck(checks, "Date", "getMilliseconds", TyperHappy::checkDateGetMilliseconds); addCheck(checks, "Date", "getMinutes", TyperHappy::checkDateGetMinutes); addCheck(checks, "Date", "getMonth", TyperHappy::checkDateGetMonth); addCheck(checks, "Date", "getSeconds", TyperHappy::checkDateGetSeconds); addCheck(checks, "Date", "getTime", TyperHappy::checkDateGetTime); // Skipped a few addCheck(checks, "String", "charCodeAt", TyperHappy::checkStringCharcodeAt); addCheck(checks, "String", "codePointAt", TyperHappy::checkStringCodePointAt); // Skipped a few addCheck(checks, "String", "indexOf", TyperHappy::checkStringIndexOf); addCheck(checks, "String", "lastIndexOf", TyperHappy::checkStringLastIndexOf); // Skipped a few addCheck(checks, "Array", "findIndex", TyperHappy::checkArrayFindIndex); // Skip addCheck(checks, "Array", "indexOf", TyperHappy::checkArrayIndexOf); // Skip addCheck(checks, "Array", "lastIndexOf", TyperHappy::checkArrayLastIndexOf); // Skip addCheck(checks, "Array", "push", TyperHappy::checkPositiveSafeIntegerType); // Skip addCheck(checks, "Array", "unshift", TyperHappy::checkPositiveSafeIntegerType); // Skip a lot return checks; } static const std::vector<Check<double>> * checksDouble; public: static double CheckType(double value, double functionId); static double CheckRangeTypeNode(double value, double min, double max) { std::cout << "Checking range. value: " << value << " min: " << min << " max: " << max << "\n"; if (IsMinusZero(value) || isnan(value)) { return value; } CHECK(min <= value && value <= max); return value; } static int functionIdFromName(char* module, char* name); static void checkMathClz32(double value) { CHECK(0 <= value && value <= 32); } static void checkSigned32Type(double value) { CHECK(IsInt32Double(value)); } static void checkMathSignType(double value) { CHECK( (-1.0 <= value && value <= 1.0) || IsMinusZero(value) || isnan(value) ); } static bool isPlainNumberType(double value) { return ((!IsMinusZero(value) && !std::isnan(value)) || IsInt32Double(value) || IsUint32Double(value)); } static void checkPlainNumberType(double value) { // PlainNumber = kIntegral32 | kOtherNumber // Integral32 = kSigned32 | kUnsigned32) // Signed32 = kSigned31 | kOtherUnsigned31 | kOtherSigned32) /*Type::bitset BitsetType::Lub(double value) { DisallowHeapAllocation no_allocation; if (IsMinusZero(value)) return kMinusZero; if (std::isnan(value)) return kNaN; if (IsUint32Double(value) || IsInt32Double(value)) return Lub(value, value); return kOtherNumber; }*/ CHECK(isPlainNumberType(value)); } static void checkNumberType(double value) { // number is everything except bigint, so there's not much we can do here. // Number = Signed32 + Unsigned32 + Double //CHECK(IsInt32Double(value) || IsUint32Double(value)); } static void checkIntegerMinusZeroNaNUnionType(double value) { CHECK(isnan(value) || IsMinusZero(value) || compiler::RangeType::IsInteger(value)); } static bool inRange(double value, double min, double max) { return min <= value && value <= max; } static void checkRangeType(double value, double min, double max) { CHECK(inRange(value, min, max)); } static void checkPlainNumberNaNUnionType(double value) { CHECK(isPlainNumberType(value) || std::isnan(value)); } static void checkDateNow(double value) { checkRangeType(value, -DateCache::kMaxTimeInMs, DateCache::kMaxTimeInMs); } static void checkDateGetDate(double value) { CHECK( 1 <= value && value <= 31.0 || std::isnan(value) ); } static void checkDateGetDay(double value) { CHECK( 0 <= value && value <= 6.0 || std::isnan(value) ); } static void checkDateGetFullYear(double value) { CHECK( IsInt32Double(value) || std::isnan(value) ); } static void checkDateGetHours(double value) { CHECK( 0 <= value && value <= 23.0 || std::isnan(value) ); } static void checkDateGetMilliseconds(double value) { CHECK( 0 <= value && value <= 999.0 || std::isnan(value) ); } static void checkDateGetMinutes(double value) { CHECK( 0 <= value && value <= 59.0 || std::isnan(value) ); } static void checkDateGetMonth(double value) { CHECK( 0 <= value && value <= 11.0 || std::isnan(value) ); } static void checkDateGetSeconds(double value) { checkDateGetMinutes(value); } static void checkDateGetTime(double value) { CHECK( -DateCache::kMaxTimeInMs <= value && value <= DateCache::kMaxTimeInMs || std::isnan(value) ); } static void checkStringCharcodeAt(double value) { CHECK( inRange(value, 0, kMaxUInt16) || std::isnan(value) ); } static void checkStringCodePointAt(double value) { CHECK( inRange(value, 0, String::kMaxCodePoint) // TODO how to check Type::Undefined()?? ); } static void checkStringIndexOf(double value) { CHECK( inRange(value, -1, String::kMaxLength - 1) ); } static void checkStringLastIndexOf(double value) { CHECK( inRange(value, -1, String::kMaxLength - 1) ); } static void checkArrayFindIndex(double value) { CHECK( inRange(value, -1, kMaxSafeInteger) ); } static void checkArrayIndexOf(double value) { CHECK( inRange(value, -1, kMaxSafeInteger) ); } static void checkArrayLastIndexOf(double value) { CHECK( inRange(value, -1, kMaxSafeInteger) ); } static void checkPositiveSafeIntegerType(double value) { CHECK( inRange(value, 0, kMaxSafeInteger) ); } }; } } #endif // V8_TYPER_HAPPY_H_
patil215/v8
src/parsing/preparse-data.h
// Copyright 2017 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_PARSING_PREPARSE_DATA_H_ #define V8_PARSING_PREPARSE_DATA_H_ #include "src/globals.h" #include "src/handles.h" #include "src/maybe-handles.h" #include "src/zone/zone-chunk-list.h" #include "src/zone/zone-containers.h" namespace v8 { namespace internal { template <typename T> class PodArray; class Parser; class PreParser; class PreparseData; class ZonePreparseData; /* Skipping inner functions. Consider the following code: (function eager_outer() { function lazy_inner() { let a; function skip_me() { a; } } return lazy_inner; })(); ... lazy_inner(); ... When parsing the code the first time, eager_outer is parsed and lazy_inner (and everything inside it) is preparsed. When lazy_inner is called, we don't want to parse or preparse skip_me again. Instead, we want to skip over it, since it has already been preparsed once. In order to be able to do this, we need to store the information needed for allocating the variables in lazy_inner when we preparse it, and then later do scope allocation based on that data. We need the following data for each scope in lazy_inner's scope tree: For each Variable: - is_used - maybe_assigned - has_forced_context_allocation For each Scope: - inner_scope_calls_eval_. ProducedPreparseData implements storing the above mentioned data and ConsumedPreparseData implements restoring it (= setting the context allocation status of the variables in a Scope (and its subscopes) based on the data). */ struct PreparseByteDataConstants { #ifdef DEBUG static constexpr int kMagicValue = 0xC0DE0DE; static constexpr size_t kUint32Size = 5; static constexpr size_t kVarint32MinSize = 3; static constexpr size_t kVarint32MaxSize = 7; static constexpr size_t kVarint32EndMarker = 0xF1; static constexpr size_t kUint8Size = 2; static constexpr size_t kQuarterMarker = 0xF2; static constexpr size_t kPlaceholderSize = kUint32Size; #else static constexpr size_t kUint32Size = 4; static constexpr size_t kVarint32MinSize = 1; static constexpr size_t kVarint32MaxSize = 5; static constexpr size_t kUint8Size = 1; static constexpr size_t kPlaceholderSize = 0; #endif static const size_t kSkippableFunctionMinDataSize = 4 * kVarint32MinSize + 1 * kUint8Size; static const size_t kSkippableFunctionMaxDataSize = 4 * kVarint32MaxSize + 1 * kUint8Size; }; class PreparseDataBuilder : public ZoneObject, public PreparseByteDataConstants { public: // Create a PreparseDataBuilder object which will collect data as we // parse. explicit PreparseDataBuilder(Zone* zone, PreparseDataBuilder* parent_builder, std::vector<void*>* children_buffer); ~PreparseDataBuilder() {} PreparseDataBuilder* parent() const { return parent_; } // For gathering the inner function data and splitting it up according to the // laziness boundaries. Each lazy function gets its own // ProducedPreparseData, and so do all lazy functions inside it. class DataGatheringScope { public: explicit DataGatheringScope(PreParser* preparser) : preparser_(preparser), builder_(nullptr) {} void Start(DeclarationScope* function_scope); void SetSkippableFunction(DeclarationScope* function_scope, int num_inner_functions); inline ~DataGatheringScope() { if (builder_ == nullptr) return; Close(); } private: void Close(); PreParser* preparser_; PreparseDataBuilder* builder_; DISALLOW_COPY_AND_ASSIGN(DataGatheringScope); }; class ByteData : public ZoneObject, public PreparseByteDataConstants { public: ByteData() : byte_data_(nullptr), index_(0), free_quarters_in_last_byte_(0) {} ~ByteData() {} void Start(std::vector<uint8_t>* buffer); void Finalize(Zone* zone); Handle<PreparseData> CopyToHeap(Isolate* isolate, int children_length); inline ZonePreparseData* CopyToZone(Zone* zone, int children_length); void Reserve(size_t bytes); void Add(uint8_t byte); int length() const; void WriteVarint32(uint32_t data); void WriteUint8(uint8_t data); void WriteQuarter(uint8_t data); #ifdef DEBUG void WriteUint32(uint32_t data); // For overwriting previously written data at position 0. void SaveCurrentSizeAtFirstUint32(); #endif private: union { struct { // Only used during construction (is_finalized_ == false). std::vector<uint8_t>* byte_data_; int index_; }; // Once the data is finalized, it lives in a Zone, this implies // is_finalized_ == true. Vector<uint8_t> zone_byte_data_; }; uint8_t free_quarters_in_last_byte_; #ifdef DEBUG bool is_finalized_ = false; #endif }; // Saves the information needed for allocating the Scope's (and its // subscopes') variables. void SaveScopeAllocationData(DeclarationScope* scope, Parser* parser); // In some cases, PreParser cannot produce the same Scope structure as // Parser. If it happens, we're unable to produce the data that would enable // skipping the inner functions of that function. void Bailout() { bailed_out_ = true; // We don't need to call Bailout on existing / future children: the only way // to try to retrieve their data is through calling Serialize on the parent, // and if the parent is bailed out, it won't call Serialize on its children. } bool bailed_out() const { return bailed_out_; } #ifdef DEBUG bool ThisOrParentBailedOut() const { if (bailed_out_) return true; if (parent_ == nullptr) return false; return parent_->ThisOrParentBailedOut(); } #endif // DEBUG bool HasInnerFunctions() const; bool HasData() const; bool HasDataForParent() const; static bool ScopeNeedsData(Scope* scope); void AddSkippableFunction(int start_position, int end_position, int num_parameters, int num_inner_functions, LanguageMode language_mode, bool has_data, bool uses_super_property); private: friend class BuilderProducedPreparseData; Handle<PreparseData> Serialize(Isolate* isolate); ZonePreparseData* Serialize(Zone* zone); void FinalizeChildren(Zone* zone); void AddChild(PreparseDataBuilder* child); void SaveDataForScope(Scope* scope); void SaveDataForVariable(Variable* var); void SaveDataForInnerScopes(Scope* scope); bool SaveDataForSkippableFunction(PreparseDataBuilder* builder); void CopyByteData(Zone* zone); PreparseDataBuilder* parent_; ByteData byte_data_; union { ScopedPtrList<PreparseDataBuilder> children_buffer_; Vector<PreparseDataBuilder*> children_; }; DeclarationScope* function_scope_; int num_inner_functions_; int num_inner_with_data_; // Whether we've given up producing the data for this function. bool bailed_out_ : 1; bool has_data_ : 1; #ifdef DEBUG bool finalized_children_ = false; #endif DISALLOW_COPY_AND_ASSIGN(PreparseDataBuilder); }; class ProducedPreparseData : public ZoneObject { public: // If there is data (if the Scope contains skippable inner functions), move // the data into the heap and return a Handle to it; otherwise return a null // MaybeHandle. virtual Handle<PreparseData> Serialize(Isolate* isolate) = 0; // If there is data (if the Scope contains skippable inner functions), return // an off-heap ZonePreparseData representing the data; otherwise // return nullptr. virtual ZonePreparseData* Serialize(Zone* zone) = 0; // Create a ProducedPreparseData which is a proxy for a previous // produced PreparseData in zone. static ProducedPreparseData* For(PreparseDataBuilder* builder, Zone* zone); // Create a ProducedPreparseData which is a proxy for a previous // produced PreparseData on the heap. static ProducedPreparseData* For(Handle<PreparseData> data, Zone* zone); // Create a ProducedPreparseData which is a proxy for a previous // produced PreparseData in zone. static ProducedPreparseData* For(ZonePreparseData* data, Zone* zone); }; class ConsumedPreparseData { public: // Creates a ConsumedPreparseData representing the data of an on-heap // PreparseData |data|. static std::unique_ptr<ConsumedPreparseData> For(Isolate* isolate, Handle<PreparseData> data); // Creates a ConsumedPreparseData representing the data of an off-heap // ZonePreparseData |data|. static std::unique_ptr<ConsumedPreparseData> For(Zone* zone, ZonePreparseData* data); virtual ~ConsumedPreparseData() = default; virtual ProducedPreparseData* GetDataForSkippableFunction( Zone* zone, int start_position, int* end_position, int* num_parameters, int* num_inner_functions, bool* uses_super_property, LanguageMode* language_mode) = 0; // Restores the information needed for allocating the Scope's (and its // subscopes') variables. virtual void RestoreScopeAllocationData(DeclarationScope* scope) = 0; protected: ConsumedPreparseData() = default; private: DISALLOW_COPY_AND_ASSIGN(ConsumedPreparseData); }; } // namespace internal } // namespace v8 #endif // V8_PARSING_PREPARSE_DATA_H_
patil215/v8
src/objects/js-generator.h
<gh_stars>1-10 // Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_OBJECTS_JS_GENERATOR_H_ #define V8_OBJECTS_JS_GENERATOR_H_ #include "src/objects/js-objects.h" #include "src/objects/struct.h" // Has to be the last include (doesn't have include guards): #include "src/objects/object-macros.h" namespace v8 { namespace internal { // Forward declarations. class JSPromise; class JSGeneratorObject : public JSObject { public: // [function]: The function corresponding to this generator object. DECL_ACCESSORS(function, JSFunction) // [context]: The context of the suspended computation. DECL_ACCESSORS(context, Context) // [receiver]: The receiver of the suspended computation. DECL_ACCESSORS(receiver, Object) // [input_or_debug_pos] // For executing generators: the most recent input value. // For suspended generators: debug information (bytecode offset). // There is currently no need to remember the most recent input value for a // suspended generator. DECL_ACCESSORS(input_or_debug_pos, Object) // [resume_mode]: The most recent resume mode. enum ResumeMode { kNext, kReturn, kThrow }; DECL_INT_ACCESSORS(resume_mode) // [continuation] // // A positive value indicates a suspended generator. The special // kGeneratorExecuting and kGeneratorClosed values indicate that a generator // cannot be resumed. inline int continuation() const; inline void set_continuation(int continuation); inline bool is_closed() const; inline bool is_executing() const; inline bool is_suspended() const; // For suspended generators: the source position at which the generator // is suspended. int source_position() const; // [parameters_and_registers]: Saved interpreter register file. DECL_ACCESSORS(parameters_and_registers, FixedArray) DECL_CAST(JSGeneratorObject) // Dispatched behavior. DECL_PRINTER(JSGeneratorObject) DECL_VERIFIER(JSGeneratorObject) // Magic sentinel values for the continuation. static const int kGeneratorExecuting = -2; static const int kGeneratorClosed = -1; // Layout description. #define JS_GENERATOR_FIELDS(V) \ V(kFunctionOffset, kTaggedSize) \ V(kContextOffset, kTaggedSize) \ V(kReceiverOffset, kTaggedSize) \ V(kInputOrDebugPosOffset, kTaggedSize) \ V(kResumeModeOffset, kTaggedSize) \ V(kContinuationOffset, kTaggedSize) \ V(kParametersAndRegistersOffset, kTaggedSize) \ /* Header size. */ \ V(kSize, 0) DEFINE_FIELD_OFFSET_CONSTANTS(JSObject::kHeaderSize, JS_GENERATOR_FIELDS) #undef JS_GENERATOR_FIELDS OBJECT_CONSTRUCTORS(JSGeneratorObject, JSObject); }; class JSAsyncFunctionObject : public JSGeneratorObject { public: DECL_CAST(JSAsyncFunctionObject) // Dispatched behavior. DECL_VERIFIER(JSAsyncFunctionObject) // [promise]: The promise of the async function. DECL_ACCESSORS(promise, JSPromise) // Layout description. #define JS_ASYNC_FUNCTION_FIELDS(V) \ V(kPromiseOffset, kTaggedSize) \ /* Header size. */ \ V(kSize, 0) DEFINE_FIELD_OFFSET_CONSTANTS(JSGeneratorObject::kSize, JS_ASYNC_FUNCTION_FIELDS) #undef JS_ASYNC_FUNCTION_FIELDS OBJECT_CONSTRUCTORS(JSAsyncFunctionObject, JSGeneratorObject); }; class JSAsyncGeneratorObject : public JSGeneratorObject { public: DECL_CAST(JSAsyncGeneratorObject) // Dispatched behavior. DECL_VERIFIER(JSAsyncGeneratorObject) // [queue] // Pointer to the head of a singly linked list of AsyncGeneratorRequest, or // undefined. DECL_ACCESSORS(queue, HeapObject) // [is_awaiting] // Whether or not the generator is currently awaiting. DECL_INT_ACCESSORS(is_awaiting) // Layout description. #define JS_ASYNC_GENERATOR_FIELDS(V) \ V(kQueueOffset, kTaggedSize) \ V(kIsAwaitingOffset, kTaggedSize) \ /* Header size. */ \ V(kSize, 0) DEFINE_FIELD_OFFSET_CONSTANTS(JSGeneratorObject::kSize, JS_ASYNC_GENERATOR_FIELDS) #undef JS_ASYNC_GENERATOR_FIELDS OBJECT_CONSTRUCTORS(JSAsyncGeneratorObject, JSGeneratorObject); }; class AsyncGeneratorRequest : public Struct { public: // Holds an AsyncGeneratorRequest, or Undefined. DECL_ACCESSORS(next, Object) DECL_INT_ACCESSORS(resume_mode) DECL_ACCESSORS(value, Object) DECL_ACCESSORS(promise, Object) // Layout description. #define ASYNC_GENERATOR_REQUEST_FIELDS(V) \ V(kNextOffset, kTaggedSize) \ V(kResumeModeOffset, kTaggedSize) \ V(kValueOffset, kTaggedSize) \ V(kPromiseOffset, kTaggedSize) \ /* Total size. */ \ V(kSize, 0) DEFINE_FIELD_OFFSET_CONSTANTS(Struct::kHeaderSize, ASYNC_GENERATOR_REQUEST_FIELDS) #undef ASYNC_GENERATOR_REQUEST_FIELDS DECL_CAST(AsyncGeneratorRequest) DECL_PRINTER(AsyncGeneratorRequest) DECL_VERIFIER(AsyncGeneratorRequest) OBJECT_CONSTRUCTORS(AsyncGeneratorRequest, Struct); }; } // namespace internal } // namespace v8 #include "src/objects/object-macros-undef.h" #endif // V8_OBJECTS_JS_GENERATOR_H_
patil215/v8
src/hash-seed-inl.h
// Copyright 2019 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_HASH_SEED_INL_H_ #define V8_HASH_SEED_INL_H_ #include <stdint.h> // The #includes below currently lead to cyclic transitive includes, so // HashSeed() ends up being required before it is defined, so we have to // declare it here. This is a workaround; if we needed this permanently then // we should put that line into a "hash-seed.h" header; but we won't need // it for long. // TODO(jkummerow): Get rid of this by breaking circular include dependencies. namespace v8 { namespace internal { class Isolate; inline uint64_t HashSeed(Isolate* isolate); } // namespace internal } // namespace v8 // See comment above for why this isn't at the top of the file. #include "src/objects/fixed-array-inl.h" #include "src/roots-inl.h" namespace v8 { namespace internal { inline uint64_t HashSeed(Isolate* isolate) { uint64_t seed; ReadOnlyRoots(isolate).hash_seed()->copy_out( 0, reinterpret_cast<byte*>(&seed), kInt64Size); DCHECK(FLAG_randomize_hashes || seed == 0); return seed; } } // namespace internal } // namespace v8 #endif // V8_HASH_SEED_INL_H_
patil215/v8
src/cov.h
<gh_stars>0 #ifndef V8_COV_H_ #define V8_COV_H_ void __sanitizer_cov_reset_edgeguards(); #endif
patil215/v8
src/objects/oddball.h
<filename>src/objects/oddball.h // Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_OBJECTS_ODDBALL_H_ #define V8_OBJECTS_ODDBALL_H_ #include "src/objects/heap-object.h" // Has to be the last include (doesn't have include guards): #include "src/objects/object-macros.h" namespace v8 { namespace internal { // The Oddball describes objects null, undefined, true, and false. class Oddball : public HeapObject { public: // [to_number_raw]: Cached raw to_number computed at startup. inline double to_number_raw() const; inline void set_to_number_raw(double value); inline void set_to_number_raw_as_bits(uint64_t bits); // [to_string]: Cached to_string computed at startup. DECL_ACCESSORS(to_string, String) // [to_number]: Cached to_number computed at startup. DECL_ACCESSORS(to_number, Object) // [typeof]: Cached type_of computed at startup. DECL_ACCESSORS(type_of, String) inline byte kind() const; inline void set_kind(byte kind); // ES6 section 7.1.3 ToNumber for Boolean, Null, Undefined. V8_WARN_UNUSED_RESULT static inline Handle<Object> ToNumber( Isolate* isolate, Handle<Oddball> input); DECL_CAST(Oddball) // Dispatched behavior. DECL_VERIFIER(Oddball) // Initialize the fields. static void Initialize(Isolate* isolate, Handle<Oddball> oddball, const char* to_string, Handle<Object> to_number, const char* type_of, byte kind); // Layout description. #define ODDBALL_FIELDS(V) \ V(kToNumberRawOffset, kDoubleSize) \ /* Tagged fields. */ \ V(kTaggedFieldsStartOffset, 0) \ V(kToStringOffset, kTaggedSize) \ V(kToNumberOffset, kTaggedSize) \ V(kTypeOfOffset, kTaggedSize) \ V(kTaggedFieldsEndOffset, 0) \ /* Raw data but still encoded as Smi. */ \ V(kKindOffset, kTaggedSize) \ /* Total size. */ \ V(kSize, 0) DEFINE_FIELD_OFFSET_CONSTANTS(HeapObject::kHeaderSize, ODDBALL_FIELDS) #undef ODDBALL_FIELDS static const byte kFalse = 0; static const byte kTrue = 1; static const byte kNotBooleanMask = static_cast<byte>(~1); static const byte kTheHole = 2; static const byte kNull = 3; static const byte kArgumentsMarker = 4; static const byte kUndefined = 5; static const byte kUninitialized = 6; static const byte kOther = 7; static const byte kException = 8; static const byte kOptimizedOut = 9; static const byte kStaleRegister = 10; static const byte kSelfReferenceMarker = 10; typedef FixedBodyDescriptor<kTaggedFieldsStartOffset, kTaggedFieldsEndOffset, kSize> BodyDescriptor; STATIC_ASSERT(kKindOffset == Internals::kOddballKindOffset); STATIC_ASSERT(kNull == Internals::kNullOddballKind); STATIC_ASSERT(kUndefined == Internals::kUndefinedOddballKind); OBJECT_CONSTRUCTORS(Oddball, HeapObject); }; } // namespace internal } // namespace v8 #include "src/objects/object-macros-undef.h" #endif // V8_OBJECTS_ODDBALL_H_
patil215/v8
test/cctest/heap/heap-utils.h
// Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef HEAP_HEAP_UTILS_H_ #define HEAP_HEAP_UTILS_H_ #include "src/api-inl.h" #include "src/heap/heap.h" namespace v8 { namespace internal { namespace heap { void SealCurrentObjects(Heap* heap); int FixedArrayLenFromSize(int size); // Fill a page with fixed arrays leaving remainder behind. The function does // not create additional fillers and assumes that the space has just been // sealed. std::vector<Handle<FixedArray>> FillOldSpacePageWithFixedArrays(Heap* heap, int remainder); std::vector<Handle<FixedArray>> CreatePadding( Heap* heap, int padding_size, PretenureFlag tenure, int object_size = kMaxRegularHeapObjectSize); void AllocateAllButNBytes( v8::internal::NewSpace* space, int extra_bytes, std::vector<Handle<FixedArray>>* out_handles = nullptr); void FillCurrentPage(v8::internal::NewSpace* space, std::vector<Handle<FixedArray>>* out_handles = nullptr); // Helper function that simulates a full new-space in the heap. bool FillUpOnePage(v8::internal::NewSpace* space, std::vector<Handle<FixedArray>>* out_handles = nullptr); void SimulateFullSpace(v8::internal::NewSpace* space, std::vector<Handle<FixedArray>>* out_handles = nullptr); // Helper function that simulates many incremental marking steps until // marking is completed. void SimulateIncrementalMarking(i::Heap* heap, bool force_completion = true); // Helper function that simulates a full old-space in the heap. void SimulateFullSpace(v8::internal::PagedSpace* space); void AbandonCurrentlyFreeMemory(PagedSpace* space); void GcAndSweep(Heap* heap, AllocationSpace space); void ForceEvacuationCandidate(Page* page); void InvokeScavenge(); void InvokeMarkSweep(); template <typename GlobalOrPersistent> bool InYoungGeneration(v8::Isolate* isolate, const GlobalOrPersistent& global) { v8::HandleScope scope(isolate); auto tmp = global.Get(isolate); return i::Heap::InYoungGeneration(*v8::Utils::OpenHandle(*tmp)); } } // namespace heap } // namespace internal } // namespace v8 #endif // HEAP_HEAP_UTILS_H_
patil215/v8
src/snapshot/deserializer.h
<gh_stars>0 // Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_SNAPSHOT_DESERIALIZER_H_ #define V8_SNAPSHOT_DESERIALIZER_H_ #include <vector> #include "src/objects/allocation-site.h" #include "src/objects/api-callbacks.h" #include "src/objects/code.h" #include "src/objects/js-array.h" #include "src/objects/map.h" #include "src/objects/string.h" #include "src/snapshot/deserializer-allocator.h" #include "src/snapshot/serializer-common.h" #include "src/snapshot/snapshot-source-sink.h" namespace v8 { namespace internal { class HeapObject; class Object; // Used for platforms with embedded constant pools to trigger deserialization // of objects found in code. #if defined(V8_TARGET_ARCH_MIPS) || defined(V8_TARGET_ARCH_MIPS64) || \ defined(V8_TARGET_ARCH_PPC) || defined(V8_TARGET_ARCH_S390) || \ V8_EMBEDDED_CONSTANT_POOL #define V8_CODE_EMBEDS_OBJECT_POINTER 1 #else #define V8_CODE_EMBEDS_OBJECT_POINTER 0 #endif // A Deserializer reads a snapshot and reconstructs the Object graph it defines. class Deserializer : public SerializerDeserializer { public: ~Deserializer() override; void SetRehashability(bool v) { can_rehash_ = v; } protected: // Create a deserializer from a snapshot byte source. template <class Data> Deserializer(Data* data, bool deserializing_user_code) : isolate_(nullptr), source_(data->Payload()), magic_number_(data->GetMagicNumber()), external_reference_table_(nullptr), allocator_(this), deserializing_user_code_(deserializing_user_code), can_rehash_(false) { allocator()->DecodeReservation(data->Reservations()); // We start the indices here at 1, so that we can distinguish between an // actual index and a nullptr in a deserialized object requiring fix-up. off_heap_backing_stores_.push_back(nullptr); } void Initialize(Isolate* isolate); void DeserializeDeferredObjects(); // Create Log events for newly deserialized objects. void LogNewObjectEvents(); void LogScriptEvents(Script script); void LogNewMapEvents(); // This returns the address of an object that has been described in the // snapshot by chunk index and offset. HeapObject GetBackReferencedObject(int space); // Add an object to back an attached reference. The order to add objects must // mirror the order they are added in the serializer. void AddAttachedObject(Handle<HeapObject> attached_object) { attached_objects_.push_back(attached_object); } Isolate* isolate() const { return isolate_; } SnapshotByteSource* source() { return &source_; } const std::vector<AllocationSite>& new_allocation_sites() const { return new_allocation_sites_; } const std::vector<Code>& new_code_objects() const { return new_code_objects_; } const std::vector<Map>& new_maps() const { return new_maps_; } const std::vector<AccessorInfo>& accessor_infos() const { return accessor_infos_; } const std::vector<CallHandlerInfo>& call_handler_infos() const { return call_handler_infos_; } const std::vector<Handle<String>>& new_internalized_strings() const { return new_internalized_strings_; } const std::vector<Handle<Script>>& new_scripts() const { return new_scripts_; } DeserializerAllocator* allocator() { return &allocator_; } bool deserializing_user_code() const { return deserializing_user_code_; } bool can_rehash() const { return can_rehash_; } void Rehash(); // Cached current isolate. Isolate* isolate_; private: void VisitRootPointers(Root root, const char* description, FullObjectSlot start, FullObjectSlot end) override; void Synchronize(VisitorSynchronization::SyncTag tag) override; template <typename TSlot> inline TSlot Write(TSlot dest, MaybeObject value); template <typename TSlot> inline TSlot WriteAddress(TSlot dest, Address value); // Fills in some heap data in an area from start to end (non-inclusive). The // space id is used for the write barrier. The object_address is the address // of the object we are writing into, or nullptr if we are not writing into an // object, i.e. if we are writing a series of tagged values that are not on // the heap. Return false if the object content has been deferred. template <typename TSlot> bool ReadData(TSlot start, TSlot end, int space, Address object_address); // A helper function for ReadData, templatized on the bytecode for efficiency. // Returns the new value of {current}. template <typename TSlot, Bytecode bytecode, int space_number_if_any> inline TSlot ReadDataCase(Isolate* isolate, TSlot current, Address current_object_address, byte data, bool write_barrier_needed); // A helper function for ReadData for reading external references. inline Address ReadExternalReferenceCase(); HeapObject ReadObject(); HeapObject ReadObject(int space_number); void ReadCodeObjectBody(int space_number, Address code_object_address); public: void VisitCodeTarget(Code host, RelocInfo* rinfo); void VisitEmbeddedPointer(Code host, RelocInfo* rinfo); void VisitRuntimeEntry(Code host, RelocInfo* rinfo); void VisitExternalReference(Code host, RelocInfo* rinfo); void VisitInternalReference(Code host, RelocInfo* rinfo); void VisitOffHeapTarget(Code host, RelocInfo* rinfo); private: template <typename TSlot> TSlot ReadRepeatedObject(TSlot current, int repeat_count); // Special handling for serialized code like hooking up internalized strings. HeapObject PostProcessNewObject(HeapObject obj, int space); // Objects from the attached object descriptions in the serialized user code. std::vector<Handle<HeapObject>> attached_objects_; SnapshotByteSource source_; uint32_t magic_number_; ExternalReferenceTable* external_reference_table_; std::vector<Map> new_maps_; std::vector<AllocationSite> new_allocation_sites_; std::vector<Code> new_code_objects_; std::vector<AccessorInfo> accessor_infos_; std::vector<CallHandlerInfo> call_handler_infos_; std::vector<Handle<String>> new_internalized_strings_; std::vector<Handle<Script>> new_scripts_; std::vector<byte*> off_heap_backing_stores_; DeserializerAllocator allocator_; const bool deserializing_user_code_; // TODO(6593): generalize rehashing, and remove this flag. bool can_rehash_; std::vector<HeapObject> to_rehash_; #ifdef DEBUG uint32_t num_api_references_; #endif // DEBUG // For source(), isolate(), and allocator(). friend class DeserializerAllocator; DISALLOW_COPY_AND_ASSIGN(Deserializer); }; // Used to insert a deserialized internalized string into the string table. class StringTableInsertionKey : public StringTableKey { public: explicit StringTableInsertionKey(String string); bool IsMatch(Object string) override; V8_WARN_UNUSED_RESULT Handle<String> AsHandle(Isolate* isolate) override; private: uint32_t ComputeHashField(String string); String string_; DISALLOW_HEAP_ALLOCATION(no_gc) }; } // namespace internal } // namespace v8 #endif // V8_SNAPSHOT_DESERIALIZER_H_
patil215/v8
src/thread-id.h
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_THREAD_ID_H_ #define V8_THREAD_ID_H_ #include "src/base/atomicops.h" namespace v8 { namespace internal { // Platform-independent, reliable thread identifier. class ThreadId { public: // Creates an invalid ThreadId. ThreadId() { base::Relaxed_Store(&id_, kInvalidId); } ThreadId& operator=(const ThreadId& other) V8_NOEXCEPT { base::Relaxed_Store(&id_, base::Relaxed_Load(&other.id_)); return *this; } bool operator==(const ThreadId& other) const { return Equals(other); } // Returns ThreadId for current thread if it exists or invalid id. static ThreadId TryGetCurrent(); // Returns ThreadId for current thread. static ThreadId Current() { return ThreadId(GetCurrentThreadId()); } // Returns invalid ThreadId (guaranteed not to be equal to any thread). static ThreadId Invalid() { return ThreadId(kInvalidId); } // Compares ThreadIds for equality. V8_INLINE bool Equals(const ThreadId& other) const { return base::Relaxed_Load(&id_) == base::Relaxed_Load(&other.id_); } // Checks whether this ThreadId refers to any thread. V8_INLINE bool IsValid() const { return base::Relaxed_Load(&id_) != kInvalidId; } // Converts ThreadId to an integer representation // (required for public API: V8::V8::GetCurrentThreadId). int ToInteger() const { return static_cast<int>(base::Relaxed_Load(&id_)); } // Converts ThreadId to an integer representation // (required for public API: V8::V8::TerminateExecution). static ThreadId FromInteger(int id) { return ThreadId(id); } private: static const int kInvalidId = -1; explicit ThreadId(int id) { base::Relaxed_Store(&id_, id); } static int AllocateThreadId() { int new_id = base::Relaxed_AtomicIncrement(&highest_thread_id_, 1); return new_id; } static int GetCurrentThreadId(); base::Atomic32 id_; static base::Atomic32 highest_thread_id_; }; } // namespace internal } // namespace v8 #endif // V8_THREAD_ID_H_
patil215/v8
src/objects/embedder-data-array-inl.h
<reponame>patil215/v8<filename>src/objects/embedder-data-array-inl.h // Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_OBJECTS_EMBEDDER_DATA_ARRAY_INL_H_ #define V8_OBJECTS_EMBEDDER_DATA_ARRAY_INL_H_ #include "src/objects/embedder-data-array.h" #include "src/objects/instance-type-inl.h" #include "src/objects/maybe-object-inl.h" #include "src/objects/slots.h" // Has to be the last include (doesn't have include guards): #include "src/objects/object-macros.h" namespace v8 { namespace internal { CAST_ACCESSOR(EmbedderDataArray) SMI_ACCESSORS(EmbedderDataArray, length, kLengthOffset) OBJECT_CONSTRUCTORS_IMPL(EmbedderDataArray, HeapObject) Address EmbedderDataArray::slots_start() { return FIELD_ADDR(*this, OffsetOfElementAt(0)); } Address EmbedderDataArray::slots_end() { return FIELD_ADDR(*this, OffsetOfElementAt(length())); } } // namespace internal } // namespace v8 #include "src/objects/object-macros-undef.h" #endif // V8_OBJECTS_EMBEDDER_DATA_ARRAY_INL_H_
stephengaito/cGoTestGenerator
cGoTestGenerator/templates/cGoTests.h
<reponame>stephengaito/cGoTestGenerator // +build cGoTests /// \file /// \brief This ANSI-C Header file provides the ANSI-C based cGoTest testing /// framework. /// /// Package description: /// {{ .BriefDesc }} /// /// This file is automatically (re)generated changes made to this file will /// be lost. #ifndef CGO_TESTS_H #define CGO_TESTS_H #include <stdio.h> #include <string.h> #include <memory.h> /// \brief Log a message to the GoLang testing systems using sprintf. /// #define cGoTestLogf(...) \ do { \ char strBuff[1024]; \ memset(strBuff, 0, 1024); \ sprintf(strBuff, __VA_ARGS__); \ cGoTestLog(strBuff); \ } while (0) /// \brief Log the current line and file to the GoLang testing system. /// #define cGoTestLogLineFile(aLine, aFile) \ cGoTestLogf(" at line: %d in: %s", aLine, aFile) /// \brief Assert the test `test` is true. If `test` is false, log the /// message. /// #define cGoTest(message, test) \ if (!(test)) cGoTestLog(message); /// \brief Assert the test `test` is true. If `test` is false, log the /// message and FAIL all further tests. /// #define cGoTest_MayFail(message, test) \ if (!(test)) return message /// \brief Assert that `aPtr` is not nil. Log a message if `aPtr` is nil. /// Capture the calling line and file. /// #define cGoTest_NotNil(message, aPtr) \ cGoTest_NotNil_LineFile(message, aPtr, __LINE__, __FILE__) /// \brief Assert that `aPtr` is not nil. Log a message if `aPtr` is nil. /// #define cGoTest_NotNil_LineFile(message, aPtr, aLine, aFile) \ if ((aPtr) == 0) { \ cGoTestLog(message); \ cGoTestLogLineFile(aLine, aFile); \ } /// \brief Assert that `aPtr` is not nil. Log a message if `aPtr` is nil. /// Capture the calling line and file. /// #define cGoTest_NotNil_MayFail(message, aPtr) \ cGoTest_NotNil_MayFail_LineFile(message, aPtr, __LINE__, __FILE__) /// \brief Assert that `aPtr` is not nil. Log a message if `aPtr` is nil. /// #define cGoTest_NotNil_MayFail_LineFile(message, aPtr, aLine, aFile) \ if ((aPtr) == 0) { \ cGoTestLog(message); \ cGoTestLogLineFile(aLine, aFile); \ return message; \ } /// \brief Assert that `aPtr` is nil. Log a message if `aPtr` is not nil. /// Capture the calling line and file. /// #define cGoTest_Nil(message, aPtr) \ cGoTest_Nil_LineFile(message, aPtr, __LINE__, __FILE__) /// \brief Assert that `aPtr` is nil. Log a message if `aPtr` is not nil. /// #define cGoTest_Nil_LineFile(message, aPtr, aLine, aFile) \ if ((aPtr) != 0) { \ cGoTestLog(message); \ cGoTestLogLineFile(aLine, aFile); \ } #define cGoUInt unsigned long /// \brief Assert that `aUInt` == `bUInt`. Log a message if they are not /// equal. Capture the calling line and file. /// #define cGoTest_UIntEquals(message, aUInt, bUInt) \ cGoTest_UIntEquals_LineFile(message, aUInt, bUInt, __LINE__, __FILE__) /// \brief Assert that `aUInt` == `bUInt`. Log a message if they are not /// equal. /// #define cGoTest_UIntEquals_LineFile(message, aUInt, bUInt, aLine, aFile) \ if ((aUInt) != (bUInt)) { \ cGoTestLog(message); \ cGoTestLogf(" aUInt: %lu", ((cGoUInt)aUInt)); \ cGoTestLogf(" bUInt: %lu", ((cGoUInt)bUInt)); \ cGoTestLogLineFile(aLine, aFile); \ } /// \brief Assert that `aUInt` != `bUInt`. Log a message if they are /// equal. Capture the calling line and file. /// #define cGoTest_UIntNotEquals(message, aUInt, bUInt) \ cGoTest_UIntNotEquals_LineFile(message, aUInt, bUInt, __LINE__, __FILE__) /// \brief Assert that `aUInt` == `bUInt`. Log a message if they are not /// equal. /// #define cGoTest_UIntNotEquals_LineFile(message, aUInt, bUInt, aLine, aFile) \ if ((aUInt) == (bUInt)) { \ cGoTestLog(message); \ cGoTestLogf(" aUInt: %lu", ((cGoUInt)aUInt)); \ cGoTestLogf(" bUInt: %lu", ((cGoUInt)bUInt)); \ cGoTestLogLineFile(aLine, aFile); \ } #define cGoStr const char* /// \brief Assert that `theStr` contains `aWord`. Log a message if /// `theStr` does not contain `aWord`. /// #define cGoTest_StrContains(message, theStr, aWord) \ cGoTest_StrContains_LineFile(message, theStr, aWord, __LINE__, __FILE__) /// \brief Assert that `theStr` contains `aWord`. Log a message if /// `theStr` does not contain `aWord`. /// #define cGoTest_StrContains_LineFile(message, theStr, aWord, aLine, aFile) \ if (strstr((theStr), (aWord)) == NULL) { \ cGoTestLog(message); \ cGoTestLogf(" theStr: %s", ((cGoStr)theStr)); \ cGoTestLogf(" aWord: %s", ((cGoStr)aWord)); \ cGoTestLogLineFile(aLine, aFile); \ } /// \brief Assert that `theStr` does not contain the `aWord`. Log a /// message if `theStr` does contain the `aWord`. /// #define cGoTest_StrNotContains(message, theStr, aWord) \ cGoTest_StrNotContains_LineFile(message, theStr, aWord, __LINE__, __FILE__) /// \brief Assert that `theStr` does not contain the `aWord`. Log a /// message if `theStr` does contain the `aWord`. /// #define cGoTest_StrNotContains_LineFile(message, theStr, aWord, aLine, aFile) \ if (strstr((theStr), (aWord)) != NULL) { \ cGoTestLog(message); \ cGoTestLogf(" theStr: %s", ((cGoStr)theStr)); \ cGoTestLogf(" aWord: %s", ((cGoStr)aWord)); \ cGoTestLogLineFile(aLine, aFile); \ } /// \brief Assert that `aStr` equals `bStr`. Log a message if they /// are not equal. /// #define cGoTest_StrEquals(message, aStr, bStr) \ cGoTest_StrEquals_LineFile(message, aStr, bStr, __LINE__, __FILE__) /// \brief Assert that `aStr` equals `bStr`. Log a message if they /// are not equal. /// #define cGoTest_StrEquals_LineFile(message, aStr, bStr, aLine, aFile) \ if (strcmp((aStr), (bStr)) != 0) { \ cGoTestLog(message); \ cGoTestLogf(" aStr: %s", ((cGoStr)aStr)); \ cGoTestLogf(" bStr: %s", ((cGoStr)bStr)); \ cGoTestLogLineFile(aLine, aFile); \ } /// \brief Assert that `aStr` does not equal `bStr`. Log a message if they /// are equal. /// #define cGoTest_StrNotEquals(message, aStr, bStr) \ cGoTest_StrNotEquals_LineFile(message, aStr, bStr, __LINE__, __FILE__) /// \brief Assert that `aStr` does not equal `bStr`. Log a message if they /// are equal. /// #define cGoTest_StrNotEquals_LineFile(message, aStr, bStr, aLine, aFile) \ if (strcmp((aStr), (bStr)) == 0) { \ cGoTestLog(message); \ cGoTestLogf(" aStr: %s", ((cGoStr)aStr)); \ cGoTestLogf(" bStr: %s", ((cGoStr)bStr)); \ cGoTestLogLineFile(aLine, aFile); \ } #endif
stephengaito/cGoTestGenerator
tests/SimpleCGoTest.c
// +build cGoTests // A simple cGoTest #include "_cgo_export.h" #include "testsCGoTests.h" #include "cGoTests.h" /// \testFixture testFixture A test fixture /// \brief Setup the testFixture /// \inFixture testFixture /// void *testFixtureCGoTestSetup(void) { return NULL; } /// \brief Tear down the testFixture /// \inFixture testFixture /// void testFixtureCGoTestTeardown(void *data) { // do nothing } /// \brief Test the cGoTest pointer assertions /// /// \inFixture testFixture /// char *pointerCGoTest(void* data) { cGoTest_NotNil_MayFail("a pointer is not nil", pointerCGoTest); cGoTest_Nil("a pointer is nil", NULL); cGoTest_NotNil_MayFail("data is nil so SHOULD fail", data); return NULL; } /// \brief Test the UInt assertions /// /// \inFixture testFixture /// char *uintCGoTest(void* data) { cGoTest_UIntEquals("two uints are equal", 42, 42); cGoTest_UIntNotEquals("two uints are not equal", 42, 2); return NULL; } char *strCGoTest(void* data) { cGoTest_StrContains( "Should contain word", "This is a test", "test" ); cGoTest_StrNotContains( "Should not contain word", "This is a test", "contain" ); cGoTest_StrEquals( "Strings should be equal", "This is a test", "This is a test" ); cGoTest_StrNotEquals( "Strings should not be equal", "This is a test", "this is a second test" ); return NULL; }
stephengaito/cGoTestGenerator
cGoTestGenerator/templates/packageCGoTests.h
// +build cGoTests /// \file /// \brief This ANSI-C Header file provides the ANSI-C based cTest testing /// framework for the {{ .Name }} GoLang Package. /// /// Package description: /// {{ .BriefDesc }} /// /// This file is automatically (re)generated changes made to this file will /// be lost. #ifndef {{ .Name }}_CGO_TESTS_H #define {{ .Name }}_CGO_TESTS_H #ifndef NULL #define NULL 0 #endif extern void *nullSetup(void); {{ range .Suites }} // begin suite: {{ .Name }} {{ range .Fixtures }} // begin fixture: {{ .Name }} {{ if .SetupName }} extern void *{{ .SetupName }} (void); {{ end }} {{ if .TeardownName }} extern void {{ .TeardownName }} (void *data); {{ end }} {{ range .Cases }} extern char *{{ .Name }}(void *data); {{ end }} // end fixture: {{ .Name }} {{ end }} // end suite: {{ .Name }} {{ end }} #endif
stephengaito/cGoTestGenerator
cGoTestGenerator/templates/cGoTestsUtils.c
<reponame>stephengaito/cGoTestGenerator // +build cGoTests /// \file /// \brief This ANSI-C Header file provides the ANSI-C based cGoTest testing /// framework. /// /// Package description: /// {{ .BriefDesc }} /// /// This file is automatically (re)generated changes made to this file will /// be lost. #include "cGoTests.h" void *nullSetup(void) { return NULL; }
webispy/ocf_mylight
ocf_mylight_configuration.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include "ocf_mylight.h" struct conf_data { char *name; double loc[2]; char *locn; char *currency; char *region; }; static struct conf_data _cd; static OCResourceHandle _confhandle; static size_t _loc_dimensions[MAX_REP_ARRAY_DEPTH] = {2, 0, 0}; static OCEntityHandlerResult on_get(OCEntityHandlerFlag flag _UNUSED_, OCEntityHandlerRequest *req, void *user_data _UNUSED_) { OCEntityHandlerResponse resp; OCRepPayload *payload = NULL; payload = OCRepPayloadCreate(); OCRepPayloadAddResourceType(payload, "oic.wk.con"); OCRepPayloadAddInterface(payload, "oic.if.baseline"); OCRepPayloadAddInterface(payload, "oic.if.rw"); OCRepPayloadSetDoubleArray(payload, "loc", _cd.loc, _loc_dimensions); OCRepPayloadSetPropString(payload, "n", _cd.name); OCRepPayloadSetPropString(payload, "locn", _cd.locn); OCRepPayloadSetPropString(payload, "c", _cd.currency); OCRepPayloadSetPropString(payload, "r", _cd.region); memset(&resp, 0, sizeof(OCEntityHandlerResponse)); resp.requestHandle = req->requestHandle; resp.resourceHandle = req->resource; resp.ehResult = OC_EH_OK; resp.payload = (OCPayload*) payload; ocf_mylight_verbose_response(&resp); if (OCDoResponse(&resp) != OC_STACK_OK) { DBG("Error sending response"); OCRepPayloadDestroy(payload); return OC_EH_ERROR; } OCRepPayloadDestroy(payload); return OC_EH_OK; } static OCEntityHandlerResult on_post(OCEntityHandlerFlag flag _UNUSED_, OCEntityHandlerRequest *req, void *user_data _UNUSED_) { OCEntityHandlerResponse resp; OCRepPayload *payload = NULL; OCRepPayload *input = (OCRepPayload *) req->payload; char *val = NULL; double *loc = NULL; if (OCRepPayloadGetPropString(input, "n", &val)) { free(_cd.name); _cd.name = val; ocf_mylight_device_set_name(_cd.name); } if (OCRepPayloadGetDoubleArray(input, "loc", &loc, _loc_dimensions)) { if (loc) { _cd.loc[0] = loc[0]; _cd.loc[1] = loc[1]; free(loc); } } if (OCRepPayloadGetPropString(input, "locn", &val)) { free(_cd.locn); _cd.locn = val; } if (OCRepPayloadGetPropString(input, "c", &val)) { free(_cd.currency); _cd.currency = val; } if (OCRepPayloadGetPropString(input, "r", &val)) { free(_cd.region); _cd.region = val; } payload = OCRepPayloadCreate(); OCRepPayloadAddResourceType(payload, "oic.wk.con"); OCRepPayloadAddInterface(payload, "oic.if.baseline"); OCRepPayloadAddInterface(payload, "oic.if.rw"); OCRepPayloadSetDoubleArray(payload, "loc", _cd.loc, _loc_dimensions); OCRepPayloadSetPropString(payload, "n", _cd.name); OCRepPayloadSetPropString(payload, "locn", _cd.locn); OCRepPayloadSetPropString(payload, "c", _cd.currency); OCRepPayloadSetPropString(payload, "r", _cd.region); memset(&resp, 0, sizeof(OCEntityHandlerResponse)); resp.requestHandle = req->requestHandle; resp.resourceHandle = req->resource; resp.ehResult = OC_EH_OK; resp.payload = (OCPayload*) payload; ocf_mylight_verbose_response(&resp); if (OCDoResponse(&resp) != OC_STACK_OK) { DBG("Error sending response"); OCRepPayloadDestroy(payload); return OC_EH_ERROR; } OCRepPayloadDestroy(payload); return OC_EH_OK; } static struct ocf_ops conf_ops = { .get = on_get, .post = on_post }; int ocf_mylight_configuration_init() { OCStackResult ret; _cd.name = strdup(ocf_mylight_device_get_name()); _cd.loc[0] = 37.532600; _cd.loc[1] = 127.024612; _cd.locn = strdup("My home"); _cd.region = strdup("Korea (Gyeonggi)"); _cd.currency = strdup("KRW"); ret = OCCreateResource(&_confhandle, "oic.wk.con", "oic.if.rw", "/oic/con", ocf_mylight_handler, &conf_ops, OC_DISCOVERABLE | OC_SECURE); if (ret != OC_STACK_OK) { DBG("OCCreateResource() failed. (ret=%d)", ret); return -1; } return 0; }
webispy/ocf_mylight
ocf_mylight_light.c
#ifdef __TIZENRT__ #include <tinyara/config.h> #include <tinyara/gpio.h> #endif #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include "ocf_mylight.h" struct light_resource { OCResourceHandle handle; bool value; char *uri; int gpio; }; static struct light_resource _light[] = { { .handle = NULL, .value = false, .uri = "/a/light/0", .gpio = 45 }, { .handle = NULL, .value = false, .uri = "/a/light/1", .gpio = 49 } }; static void gpio_write(int port, int value) { #ifdef CONFIG_ARCH_BOARD_ARTIK053 char tmp[20]; int fd; snprintf(tmp, 16, "/dev/gpio%d", port); fd = open(tmp, O_RDWR); if (fd < 0) { DBG("open(%s) failed.", tmp); return; } MSG("GPIO: '%s' value '%d'", tmp, value); ioctl(fd, GPIOIOC_SET_DIRECTION, GPIO_DIRECTION_OUT); snprintf(tmp, 2, "%1d", value); write(fd, tmp, 2); close(fd); #else MSG("GPIO: '%d' value '%d'", port, value); #endif } static int find_light(OCResourceHandle handle) { unsigned int i; for (i = 0; i < sizeof(_light) / sizeof(struct light_resource); i++) { if (_light[i].handle == handle) return i; } DBG("Can't find light"); return -1; } static OCEntityHandlerResult on_get(OCEntityHandlerFlag flag _UNUSED_, OCEntityHandlerRequest *req, void *user_data _UNUSED_) { OCEntityHandlerResponse resp; OCRepPayload *payload = NULL; int id; MSG("received GET request"); id = find_light(req->resource); if (id < 0) return OC_EH_ERROR; payload = OCRepPayloadCreate(); OCRepPayloadAddResourceType(payload, "oic.r.switch.binary"); OCRepPayloadAddInterface(payload, "oic.if.baseline"); OCRepPayloadAddInterface(payload, "oic.if.a"); OCRepPayloadSetUri(payload, _light[id].uri); OCRepPayloadSetPropBool(payload, "value", _light[id].value); memset(&resp, 0, sizeof(OCEntityHandlerResponse)); resp.requestHandle = req->requestHandle; resp.resourceHandle = req->resource; resp.ehResult = OC_EH_OK; resp.payload = (OCPayload*) payload; ocf_mylight_verbose_response(&resp); if (OCDoResponse(&resp) != OC_STACK_OK) { DBG("Error sending response"); OCRepPayloadDestroy(payload); return OC_EH_ERROR; } OCRepPayloadDestroy(payload); return OC_EH_OK; } static OCEntityHandlerResult on_put_post(OCEntityHandlerFlag flag _UNUSED_, OCEntityHandlerRequest *req, void *user_data _UNUSED_) { OCEntityHandlerResponse resp; OCRepPayload *payload = NULL; int id; bool value; if (req->method == OC_REST_PUT) MSG("received PUT request"); else if (req->method == OC_REST_POST) MSG("received POST request"); id = find_light(req->resource); if (id < 0) return OC_EH_ERROR; payload = (OCRepPayload *) req->payload; if (OCRepPayloadGetPropBool(payload, "value", &value)) ocf_mylight_light_set_status(id, value); payload = OCRepPayloadCreate(); OCRepPayloadAddResourceType(payload, "oic.r.switch.binary"); OCRepPayloadAddInterface(payload, "oic.if.baseline"); OCRepPayloadAddInterface(payload, "oic.if.a"); OCRepPayloadSetUri(payload, _light[id].uri); OCRepPayloadSetPropBool(payload, "value", _light[id].value); memset(&resp, 0, sizeof(OCEntityHandlerResponse)); resp.requestHandle = req->requestHandle; resp.resourceHandle = req->resource; resp.ehResult = OC_EH_OK; resp.payload = (OCPayload*) payload; ocf_mylight_verbose_response(&resp); if (OCDoResponse(&resp) != OC_STACK_OK) { DBG("Sending response failed."); OCRepPayloadDestroy(payload); return OC_EH_ERROR; } OCRepPayloadDestroy(payload); return OC_EH_OK; } static OCEntityHandlerResult on_del(OCEntityHandlerFlag flag _UNUSED_, OCEntityHandlerRequest *req _UNUSED_, void *user_data _UNUSED_) { DBG("Forbidden"); return OC_EH_FORBIDDEN; } static OCEntityHandlerResult on_register_observe( OCEntityHandlerFlag flag _UNUSED_, OCEntityHandlerRequest *req, void *user_data _UNUSED_) { int id; DBG("Registration request with observation Id %d", req->obsInfo.obsId); id = find_light(req->resource); if (id < 0) return OC_EH_ERROR; ocf_mylight_notify_add(id, req->obsInfo.obsId); return OC_EH_OK; } static OCEntityHandlerResult on_deregister_observe( OCEntityHandlerFlag flag _UNUSED_, OCEntityHandlerRequest *req, void *user_data _UNUSED_) { int id; DBG("De-registration request for observation Id %d", req->obsInfo.obsId); id = find_light(req->resource); if (id < 0) return OC_EH_ERROR; ocf_mylight_notify_del(id, req->obsInfo.obsId); return OC_EH_OK; } static struct ocf_ops light_ops = { .get = on_get, .put = on_put_post, .post = on_put_post, .del = on_del, .register_observe = on_register_observe, .deregister_observe = on_deregister_observe }; int ocf_mylight_light_get_handle(unsigned int id, OCResourceHandle *handle) { if (id >= sizeof(_light) / sizeof(struct light_resource)) return -1; if (!handle) return -1; *handle = _light[id].handle; return 0; } const char *ocf_mylight_light_peek_uri(unsigned int id) { if (id >= sizeof(_light) / sizeof(struct light_resource)) return NULL; return _light[id].uri; } int ocf_mylight_light_set_status(unsigned int id, bool status) { if (id >= sizeof(_light) / sizeof(struct light_resource)) return -1; if (_light[id].value == status) return 0; _light[id].value = status; DBG("Light%u value changed to %d", id, status); gpio_write(_light[id].gpio, _light[id].value); ocf_mylight_notify_emit(id); return 0; } int ocf_mylight_light_get_status(unsigned int id, bool *status) { if (id >= sizeof(_light) / sizeof(struct light_resource)) return -1; if (!status) return -1; *status = _light[id].value; return 0; } int ocf_mylight_light_init() { OCStackResult ret; unsigned int i; for (i = 0; i < sizeof(_light) / sizeof(struct light_resource); i++) { ret = OCCreateResource(&(_light[i].handle), "oic.r.switch.binary", "oic.if.a", _light[i].uri, ocf_mylight_handler, &light_ops, OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE); if (ret != OC_STACK_OK) { DBG("OCCreateResource() failed. (ret=%d)", ret); return -1; } MSG("Light resource created. <id: %u>", i); MSG(" - resource: 0x%p", _light[i].handle); MSG(" - uri: '%s'", _light[i].uri); } return 0; } void ocf_mylight_light_exit() { }
webispy/ocf_mylight
ocf_mylight_device.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include "ocf_mylight.h" static OCDeviceInfo _di = { .specVersion = "ocf.1.1.0" }; static OCEntityHandlerResult on_get(OCEntityHandlerFlag flag _UNUSED_, OCEntityHandlerRequest *req _UNUSED_, char *uri _UNUSED_, void *user_data _UNUSED_) { if (uri) { if (strcmp(uri, "/oic/d") != 0) DBG("invalid url"); return OC_EH_RESOURCE_NOT_FOUND; } DBG("dev on_get"); /* TODO */ return OC_EH_OK; } static OCEntityHandlerResult on_put_post(OCEntityHandlerFlag flag _UNUSED_, OCEntityHandlerRequest *req _UNUSED_, char *uri _UNUSED_, void *user_data _UNUSED_) { if (req->method == OC_REST_PUT) DBG("dev on_put"); else if (req->method == OC_REST_POST) DBG("dev on_ppost"); return OC_EH_FORBIDDEN; } static OCEntityHandlerResult on_del(OCEntityHandlerFlag flag _UNUSED_, OCEntityHandlerRequest *req _UNUSED_, char *uri _UNUSED_, void *user_data _UNUSED_) { DBG("dev on_del"); return OC_EH_FORBIDDEN; } struct ocf_dev_ops dev_ops = { .get = on_get, .put = on_put_post, .post = on_put_post, .del = on_del }; const char *ocf_mylight_device_get_name() { return _di.deviceName; } int ocf_mylight_device_set_name(const char *name) { if (!name) return -1; if (_di.deviceName) free(_di.deviceName); _di.deviceName = strdup(name); OCSetPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME, _di.deviceName); return 0; } int ocf_mylight_device_init() { OCStackResult ret; OCSetDefaultDeviceEntityHandler(ocf_mylight_dev_handler, &dev_ops); _di.deviceName = strdup("ARTIK-053-Light"); _di.dataModelVersions = OCCreateOCStringLL("ocf.res.1.1.0,ocf.sh.1.1.0"); _di.types = OCCreateOCStringLL("oic.d.light"); ret = OCSetDeviceInfo(_di); if (ret != OC_STACK_OK) { DBG("Device Registration failed! (ret=%d)", ret); return -1; } return 0; }
webispy/ocf_mylight
ocf_mylight.h
#ifndef __MYOCF_H__ #define __MYOCF_H__ #include <iotivity_config.h> #include <platform_features.h> #include <ocstack.h> #include <logger.h> #include <ocpayload.h> #define _UNUSED_ __attribute__((unused)) #define DBG(fmt,args...) fprintf(stdout, "\e[1;32m<%s:%d> " fmt "\e[0m\n", __FILE__, __LINE__, ##args) #define MSG(fmt,args...) fprintf(stdout, "\e[1;34m" fmt "\e[0m\n", ##args) struct ocf_ops { OCEntityHandler get; OCEntityHandler put; OCEntityHandler post; OCEntityHandler del; OCEntityHandler register_observe; OCEntityHandler deregister_observe; }; struct ocf_dev_ops { OCDeviceEntityHandler get; OCDeviceEntityHandler put; OCDeviceEntityHandler post; OCDeviceEntityHandler del; }; OCEntityHandlerResult ocf_mylight_handler(OCEntityHandlerFlag flag, OCEntityHandlerRequest *req, void *user_data); OCEntityHandlerResult ocf_mylight_dev_handler(OCEntityHandlerFlag flag, OCEntityHandlerRequest *req, char *uri, void *user_data); void ocf_mylight_verbose_payload(const char *indent, OCPayload *payload); void ocf_mylight_verbose_response(OCEntityHandlerResponse *resp); void ocf_mylight_verbose_request(OCEntityHandlerFlag flag, OCEntityHandlerRequest *req); int ocf_mylight_playform_init(); const char *ocf_mylight_device_get_name(); int ocf_mylight_device_set_name(const char *name); int ocf_mylight_device_init(); int ocf_mylight_light_init(); void ocf_mylight_light_exit(); int ocf_mylight_light_get_handle(unsigned int id, OCResourceHandle *handle); const char *ocf_mylight_light_peek_uri(unsigned int id); int ocf_mylight_light_set_status(unsigned int id, bool status); int ocf_mylight_light_get_status(unsigned int id, bool *status); int ocf_mylight_configuration_init(); int ocf_mylight_maintenance_init(); int ocf_mylight_security_init(); int ocf_mylight_notify_init(); void ocf_mylight_notify_exit(); int ocf_mylight_notify_add(unsigned int light_id, OCObservationId obs_id); int ocf_mylight_notify_del(unsigned int light_id, OCObservationId obs_id); int ocf_mylight_notify_emit(unsigned int light_id); int ocf_mylight_userinput_init(); #endif
webispy/ocf_mylight
ocf_mylight_userinput.c
<filename>ocf_mylight_userinput.c<gh_stars>1-10 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <errno.h> #include <sys/types.h> #include "ocf_mylight.h" static void on_signal_1(int signo) { bool status; MSG("SIGUSR1(%d) - toggle /a/light/0", signo); if (ocf_mylight_light_get_status(0, &status) == -1) return; ocf_mylight_light_set_status(0, !status); } static void on_signal_2(int signo) { bool status; MSG("SIGUSR2(%d) - toggle /a/light/1", signo); if (ocf_mylight_light_get_status(1, &status) == -1) return; ocf_mylight_light_set_status(1, !status); } int ocf_mylight_userinput_init() { struct sigaction usr1, usr2; usr1.sa_handler = on_signal_1; sigemptyset(&usr1.sa_mask); usr1.sa_flags = 0; usr2.sa_handler = on_signal_2; sigemptyset(&usr2.sa_mask); usr2.sa_flags = 0; if (sigaction(SIGUSR1, &usr1, 0) == -1) { DBG("sigaction failed. (errno=%d)", errno); return -1; } if (sigaction(SIGUSR2, &usr2, 0) == -1) { DBG("sigaction failed. (errno=%d)", errno); return -1; } MSG("Control /a/light/{0, 1} resource by signal"); MSG(" - 'kill -USR1 %d': toggle the /a/light/0", getpid()); MSG(" - 'kill -USR2 %d': toggle the /a/light/1", getpid()); return 0; }
webispy/ocf_mylight
ocf_mylight_notify.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <errno.h> #include "ocf_mylight.h" #define MAX_SLOT 8 struct notify_slot { bool active; OCObservationId id; }; static struct notify_slot slots[2][MAX_SLOT]; static pthread_t _notify_tid; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t lock_loop = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static unsigned int changed_light = 0; static int find_empty_slot(unsigned int light_id) { int i; for (i = 0; i < MAX_SLOT; i++) { if (slots[light_id][i].active == false) return i; } return -1; } static int find_slot(unsigned int light_id, OCObservationId id) { int i; for (i = 0; i < MAX_SLOT; i++) { if (slots[light_id][i].id == id) return i; } return -1; } static void notify(int light_id) { OCRepPayload *payload = NULL; OCObservationId list[MAX_SLOT]; OCResourceHandle handle; int i; int list_cnt = 0; bool value; pthread_mutex_lock(&lock); for (i = 0; i < MAX_SLOT; i++) { if (slots[light_id][i].active) { list[list_cnt] = slots[light_id][i].id; list_cnt++; } } DBG("list_cnt = %d", list_cnt); pthread_mutex_unlock(&lock); payload = OCRepPayloadCreate(); OCRepPayloadAddResourceType(payload, "oic.r.switch.binary"); OCRepPayloadAddInterface(payload, "oic.if.baseline"); OCRepPayloadAddInterface(payload, "oic.if.a"); OCRepPayloadSetUri(payload, ocf_mylight_light_peek_uri(light_id)); ocf_mylight_light_get_status(light_id, &value); OCRepPayloadSetPropBool(payload, "value", value); ocf_mylight_light_get_handle(light_id, &handle); OCNotifyListOfObservers(handle, list, list_cnt, payload, OC_NA_QOS); OCRepPayloadDestroy(payload); } static void *loop_notify(void *user_data _UNUSED_) { MSG("Notify Thread ready..."); while (1) { pthread_mutex_lock(&lock_loop); pthread_cond_wait(&cond, &lock_loop); MSG("Do notify! (light=%d)", changed_light); notify(changed_light); pthread_mutex_unlock(&lock_loop); } return NULL; } int ocf_mylight_notify_add(unsigned int light_id, OCObservationId obs_id) { int i; if (light_id > 1) { DBG("invalid light_id(%u)", light_id); return -1; } DBG("Light%u obs_id = %d", light_id, obs_id); pthread_mutex_lock(&lock); i = find_empty_slot(light_id); if (i == -1) { DBG("notify slot is full"); pthread_mutex_unlock(&lock); return -1; } slots[light_id][i].active = true; slots[light_id][i].id = obs_id; pthread_mutex_unlock(&lock); return 0; } int ocf_mylight_notify_del(unsigned int light_id, OCObservationId obs_id) { int i; if (light_id > 1) { DBG("invalid light_id(%u)", light_id); return -1; } DBG("Light%u obs_id = %d", light_id, obs_id); pthread_mutex_lock(&lock); i = find_slot(light_id, obs_id); if (i == -1) { DBG("invalid obs_id(%d)", obs_id); pthread_mutex_unlock(&lock); return -1; } slots[light_id][i].active = false; slots[light_id][i].id = 0; pthread_mutex_unlock(&lock); return 0; } int ocf_mylight_notify_emit(unsigned int light_id) { if (light_id > 1) { DBG("invalid light_id(%u)", light_id); return -1; } pthread_mutex_lock(&lock_loop); MSG("request (light=%d)", light_id); changed_light = light_id; pthread_cond_signal(&cond); pthread_mutex_unlock(&lock_loop); return 0; } int ocf_mylight_notify_init() { int i; for (i = 0; i < MAX_SLOT; i++) { slots[0][i].active = false; slots[0][i].id = 0; slots[1][i].active = false; slots[1][i].id = 0; } if (pthread_create(&_notify_tid, NULL, loop_notify, NULL) != 0) { DBG("pthread_create failed. errno=%d", errno); return -1; } return 0; } void ocf_mylight_notify_exit() { }
webispy/ocf_mylight
ocf_mylight_security.c
<reponame>webispy/ocf_mylight #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include "ocf_mylight.h" #include <pinoxmcommon.h> static FILE* on_open(const char *path, const char *mode) { DBG("open: path=%s, mode=%s", path, mode); return fopen(path, mode); } static size_t on_read(void *ptr, size_t size, size_t nmemb, FILE *fp) { DBG("read: size=%zd, nmemb=%zd, fp=0x%p", size, nmemb, fp); return fread(ptr, size, nmemb, fp); } static size_t on_write(const void *ptr, size_t size, size_t nmemb, FILE *fp) { DBG("write: size=%zd, nmemb=%zd, fp=0x%p", size, nmemb, fp); return fwrite(ptr, size, nmemb, fp); } static int on_close(FILE *fp) { DBG("close: fp=0x%p", fp); return fclose(fp); } static int on_unlink(const char *path) { DBG("unlink: path=%s", path); return unlink(path); } static void on_display_pin(char *pin, size_t length, void *user_data _UNUSED_) { MSG("PIN CODE: '%s' (pin length=%zd)", pin, length); } static void on_close_pin(void) { MSG("PIN CLOSED"); } OCPersistentStorage ps = { .open = on_open, .read = on_read, .write = on_write, .close = on_close, .unlink = on_unlink }; int ocf_mylight_security_init() { OCStackResult ret; OCRegisterPersistentStorageHandler(&ps); ret = SetDisplayPinWithContextCB(on_display_pin, NULL); if (ret != OC_STACK_OK) { DBG("SetDisplayPinWithContextCB failed! (ret=%d)", ret); return -1; } SetClosePinDisplayCB(on_close_pin); ret = SetRandomPinPolicy(8, NUM_PIN); if (ret != OC_STACK_OK) { DBG("SetRandomPinPolicy failed! (ret=%d)", ret); return -1; } return 0; }
webispy/ocf_mylight
ocf_mylight_maintenance.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include "ocf_mylight.h" static OCResourceHandle _mnthandle; static bool _fr; static bool _rb; static OCEntityHandlerResult on_get(OCEntityHandlerFlag flag _UNUSED_, OCEntityHandlerRequest *req, void *user_data _UNUSED_) { OCEntityHandlerResponse resp; OCRepPayload *payload = NULL; payload = OCRepPayloadCreate(); OCRepPayloadAddResourceType(payload, "oic.wk.mnt"); OCRepPayloadAddInterface(payload, "oic.if.baseline"); /** * FIXME: mismatch Spec and CTT * * In the OIC 1.1.2 specification document, the 'oic.if.rw' interface is * correct for the 'oic.wk.mnt' resource type. * However, CTT 1.5.0.0 tools 'Check_13' test cases report FAIL results * because the tool want the interface 'oic.if.r'. */ // OCRepPayloadAddInterface(payload, "oic.if.rw"); OCRepPayloadAddInterface(payload, "oic.if.r"); OCRepPayloadSetPropBool(payload, "fr", _fr); OCRepPayloadSetPropBool(payload, "rb", _rb); memset(&resp, 0, sizeof(OCEntityHandlerResponse)); resp.requestHandle = req->requestHandle; resp.resourceHandle = req->resource; resp.ehResult = OC_EH_OK; resp.payload = (OCPayload*) payload; ocf_mylight_verbose_response(&resp); if (OCDoResponse(&resp) != OC_STACK_OK) { DBG("Error sending response"); OCRepPayloadDestroy(payload); return OC_EH_ERROR; } OCRepPayloadDestroy(payload); return OC_EH_OK; } static OCEntityHandlerResult on_post(OCEntityHandlerFlag flag _UNUSED_, OCEntityHandlerRequest *req, void *user_data _UNUSED_) { OCEntityHandlerResponse resp; OCRepPayload *payload = NULL; OCRepPayload *input = (OCRepPayload *) req->payload; bool val = NULL; if (req->query) { /** * CTT testcase requests POST with if=oic.if.r query. */ if (strncmp(req->query, "if=oic.if.r", 11) == 0) return OC_EH_FORBIDDEN; } payload = OCRepPayloadCreate(); OCRepPayloadAddResourceType(payload, "oic.wk.mnt"); OCRepPayloadAddInterface(payload, "oic.if.baseline"); /** * FIXME: mismatch Spec and CTT * * In the OIC 1.1.2 specification document, the 'oic.if.rw' interface is * correct for the 'oic.wk.mnt' resource type. * However, CTT 1.5.0.0 tools 'Check_13' test cases report FAIL results * because the tool want the interface 'oic.if.r'. */ // OCRepPayloadAddInterface(payload, "oic.if.rw"); OCRepPayloadAddInterface(payload, "oic.if.r"); if (OCRepPayloadGetPropBool(input, "fr", &val)) { _fr = val; /** * Do Factory Reset */ MSG("Factory Reset request"); } OCRepPayloadSetPropBool(payload, "fr", _fr); if (OCRepPayloadGetPropBool(input, "rb", &val)) { _rb = val; /** * Do Reboot */ MSG("Reboot request"); } OCRepPayloadSetPropBool(payload, "rb", _rb); memset(&resp, 0, sizeof(OCEntityHandlerResponse)); resp.requestHandle = req->requestHandle; resp.resourceHandle = req->resource; resp.ehResult = OC_EH_OK; resp.payload = (OCPayload*) payload; ocf_mylight_verbose_response(&resp); if (OCDoResponse(&resp) != OC_STACK_OK) { DBG("Error sending response"); OCRepPayloadDestroy(payload); return OC_EH_ERROR; } OCRepPayloadDestroy(payload); return OC_EH_OK; } static struct ocf_ops mnt_ops = { .get = on_get, .post = on_post }; int ocf_mylight_maintenance_init() { OCStackResult ret; /** * FIXME: fr(factory reset) and rb(reboot) status * * CTT requests update(POST) for fr and rb properties, CTT then * retrieve(GET) the properties to confirm it has changed. */ _fr = false; _rb = false; /** * FIXME: mismatch Spec and CTT * * In the OIC 1.1.2 specification document, the 'oic.if.rw' interface is * correct for the 'oic.wk.mnt' resource type. * However, CTT 1.5.0.0 tools 'Check_13' test cases report FAIL results * because the tool want the interface 'oic.if.r'. */ // ret = OCCreateResource(&_mnthandle, "oic.wk.mnt", "oic.if.rw", ret = OCCreateResource(&_mnthandle, "oic.wk.mnt", "oic.if.r", "/oic/mnt", ocf_mylight_handler, &mnt_ops, OC_DISCOVERABLE | OC_SECURE); if (ret != OC_STACK_OK) { DBG("OCCreateResource() failed. (ret=%d)", ret); return -1; } return 0; }
webispy/ocf_mylight
ocf_mylight_verbose.c
<reponame>webispy/ocf_mylight #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include "ocf_mylight.h" struct num_str { int number; char *str; }; /** * CoAP Option Numbers * http://www.iana.org/assignments/core-parameters/core-parameters.xhtml */ static struct num_str _coap_options[] = { { 0, "Reserved" }, { 1, "If-Match" }, { 3, "Uri-Host" }, { 4, "ETag" }, { 5, "If-None-Match" }, { 6, "Observe" }, { 7, "Uri-Port" }, { 8, "Location-Path" }, { 11, "Uri-Path" }, { 12, "Content-Format" }, { 14, "Max-Age" }, { 15, "Uri-Query" }, { 17, "Accept" }, { 20, "Location-Query" }, { 23, "Block2" }, { 27, "Block1" }, { 28, "Size2" }, { 35, "Proxy-Uri" }, { 39, "Proxy-Scheme" }, { 60, "Size1" }, { 128, "Reserved" }, { 132, "Reserved" }, { 136, "Reserved" }, { 140, "Reserved" }, { 258, "No-Response" }, { 2049, "OCF-Accept-Content-Format-Version" }, { 2053, "OCF-Content-Format-Version" }, }; static void _method(OCMethod method) { if (method & OC_REST_NOMETHOD) printf("NOMETHOD "); if (method & OC_REST_GET) printf("GET "); if (method & OC_REST_PUT) printf("PUT "); if (method & OC_REST_POST) printf("POST "); if (method & OC_REST_DELETE) printf("DELETE "); if (method & OC_REST_OBSERVE) printf("OBSERVE "); if (method & OC_REST_OBSERVE_ALL) printf("OBSERVE_ALL "); if (method & OC_REST_PRESENCE) printf("PRESENCE "); if (method & OC_REST_DISCOVER) printf("DISCOVER "); } static void _flag(OCEntityHandlerFlag flag) { if (flag & OC_REQUEST_FLAG) printf("REQUEST "); if (flag & OC_OBSERVE_FLAG) printf("OBSERVE "); } static void _ll(OCStringLL *ll) { OCStringLL *cur = ll; while (cur) { printf("%s ", cur->value); cur = cur->next; } } static void _ll_rep_value(OCRepPayloadValue *values) { OCRepPayloadValue *cur = values; while (cur) { printf("{\"%s\": ", cur->name); switch (cur->type) { case OCREP_PROP_INT: printf("%zd} ", cur->i); break; case OCREP_PROP_DOUBLE: printf("%f} ", cur->d); break; case OCREP_PROP_BOOL: printf("%d} ", cur->b); break; case OCREP_PROP_STRING: printf("\"%s\"} ", cur->str); break; case OCREP_PROP_BYTE_STRING: printf("len=%zd [...]} ", cur->ocByteStr.len); break; case OCREP_PROP_OBJECT: printf("{0x%p}}", cur->obj); break; case OCREP_PROP_ARRAY: printf("[type=%d]}", cur->arr.type); break; default: printf("unknown} "); break; } cur = cur->next; } } static void _payload_representation(const char *indent, OCRepPayload *payload) { printf("%s - payload-type: %d (%s)\n", indent, payload->base.type, "Representation"); printf("%s - uri: %s\n", indent, payload->uri); if (payload->types) { printf("%s - types: ", indent); _ll(payload->types); printf("\n"); } if (payload->interfaces) { printf("%s - interfaces: ", indent); _ll(payload->interfaces); printf("\n"); } if (payload->values) { printf("%s - values: ", indent); _ll_rep_value(payload->values); printf("\n"); } } void ocf_mylight_verbose_payload(const char *indent, OCPayload *payload) { if (!payload) return; if (payload->type == PAYLOAD_TYPE_REPRESENTATION) _payload_representation(indent, (OCRepPayload *) payload); else printf("%s - payload-type: %d\n", indent, payload->type); } static const char *_coap_opt_name(int number) { unsigned int i; for (i = 0; i < sizeof(_coap_options) / sizeof(struct num_str); i++) { if (_coap_options[i].number == number) return _coap_options[i].str; } return "Unknown"; } static void _header_options(OCHeaderOption *opt, uint8_t count) { int i; int j; printf(" - vendor specific header count: %d\n", count); for (i = 0; i < count; i++) { printf(" - [%d] ", i); if (opt[i].protocolID != 2) { printf("Invalid protocol(%d), option_id=0x%x, len=%d\n", opt[i].protocolID, opt[i].optionID, opt[i].optionLength); continue; } printf("CoAP option_id=0x%x (%s), option_len=%d\n", opt[i].optionID, _coap_opt_name(opt[i].optionID), opt[i].optionLength); if (opt[i].optionLength > 0) { printf(" Data: "); for (j = 0; j < opt[i].optionLength; j++) printf("%02X ", opt[i].optionData[j]); printf("\n"); } } } void ocf_mylight_verbose_request(OCEntityHandlerFlag flag, OCEntityHandlerRequest *req) { MSG("IncomingRequest: (id: %d)", req->messageID); printf(" - resourceHandle: 0x%p\n", req->resource); printf(" - uri: '%s'\n", OCGetResourceUri(req->resource)); printf(" - property: 0x%X\n", OCGetResourceProperties(req->resource)); printf(" - flag: 0x%X ( ", flag); _flag(flag); printf(")\n"); printf(" - method: %d ( ", req->method); _method(req->method); printf(")\n"); printf(" - query: '%s'\n", req->query); printf(" - dev_addr: adapter:%d, flags:0x%X, port:%d\n", req->devAddr.adapter, req->devAddr.flags, req->devAddr.port); if (req->numRcvdVendorSpecificHeaderOptions > 0) _header_options(req->rcvdVendorSpecificHeaderOptions, req->numRcvdVendorSpecificHeaderOptions); ocf_mylight_verbose_payload("", req->payload); } void ocf_mylight_verbose_response(OCEntityHandlerResponse *resp) { MSG("OutgoingResponse:"); printf(" - resourceHandle: 0x%p\n", resp->resourceHandle); printf(" - result: %d\n", resp->ehResult); printf(" - resourceUri: '%s'\n", resp->resourceUri); printf(" - persistentBufferFlag: %d\n", resp->persistentBufferFlag); if (resp->numSendVendorSpecificHeaderOptions > 0) _header_options(resp->sendVendorSpecificHeaderOptions, resp->numSendVendorSpecificHeaderOptions); ocf_mylight_verbose_payload("", resp->payload); }
webispy/ocf_mylight
ocf_mylight_main.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include "ocf_mylight.h" static int gQuitFlag = 0; static int server_cb(int argc _UNUSED_, char *argv[] _UNUSED_) { MSG("IoTivity Demo - IOTIVITY version is %s", IOTIVITY_VERSION); MSG("OCF My Light Server is starting..."); #ifndef CONFIG_ARCH_BOARD_ARTIK053 ocf_mylight_security_init(); #endif if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK) { DBG("OCStack init error"); return 0; } MSG("Supported Endpoint Transport Protocol Suites: 0x%X", OCGetSupportedEndpointTpsFlags()); ocf_mylight_playform_init(); ocf_mylight_device_init(); ocf_mylight_configuration_init(); ocf_mylight_maintenance_init(); ocf_mylight_light_init(); ocf_mylight_notify_init(); #ifndef CONFIG_ARCH_BOARD_ARTIK053 ocf_mylight_userinput_init(); #endif MSG("Entering ocserver main loop..."); while (!gQuitFlag) { usleep(10000); if (OCProcess() != OC_STACK_OK) { DBG("OCStack process error"); return 0; } } ocf_mylight_light_exit(); MSG("Exiting ocserver main loop..."); if (OCStop() != OC_STACK_OK) DBG("OCStack process error"); return 0; } static void _timestamp() { struct tm stamp; struct timespec tspec; char timebuf[32]; clock_gettime(CLOCK_REALTIME, &tspec); localtime_r(&tspec.tv_sec, &stamp); strftime(timebuf, sizeof(timebuf), "%m-%d %H:%M:%S", &stamp); printf("%s.%03ld", timebuf, tspec.tv_nsec / 1000000); } OCEntityHandlerResult ocf_mylight_handler(OCEntityHandlerFlag flag, OCEntityHandlerRequest *req, void *user_data) { struct ocf_ops *ops = user_data; OCEntityHandlerResult ret = OC_EH_METHOD_NOT_ALLOWED; printf("\n"); _timestamp(); MSG("\n<New request>"); ocf_mylight_verbose_request(flag, req); if (!ops) return ret; if (flag & OC_REQUEST_FLAG) { if (OC_REST_GET == req->method && ops->get) ret = ops->get(flag, req, user_data); else if (OC_REST_PUT == req->method && ops->put) ret = ops->put(flag, req, user_data); else if (OC_REST_POST == req->method && ops->post) ret = ops->post(flag, req, user_data); else if (OC_REST_DELETE == req->method && ops->del) ret = ops->del(flag, req, user_data); } if (flag & OC_OBSERVE_FLAG) { if (OC_OBSERVE_REGISTER == req->obsInfo.action && ops->register_observe) ret = ops->register_observe(flag, req, user_data); else if (OC_OBSERVE_DEREGISTER == req->obsInfo.action && ops->deregister_observe) ret = ops->deregister_observe(flag, req, user_data); } MSG(" return code: %d", ret); MSG("</New request>\n"); return ret; } OCEntityHandlerResult ocf_mylight_dev_handler(OCEntityHandlerFlag flag, OCEntityHandlerRequest *req, char *uri, void *user_data) { struct ocf_dev_ops *ops = user_data; OCEntityHandlerResult ret = OC_EH_METHOD_NOT_ALLOWED; printf("\n"); _timestamp(); MSG("\n<New request for device>"); ocf_mylight_verbose_request(flag, req); MSG(" - uri: %s", uri); if (!ops) return ret; if (flag & OC_REQUEST_FLAG) { if (OC_REST_GET == req->method && ops->get) ret = ops->get(flag, req, uri, user_data); else if (OC_REST_PUT == req->method && ops->put) ret = ops->put(flag, req, uri, user_data); else if (OC_REST_DELETE == req->method && ops->del) ret = ops->del(flag, req, uri, user_data); } MSG(" return code: %d", ret); MSG("</New request for device>\n"); return ret; } int ocf_mylight_get_quit_flag() { return gQuitFlag; } #ifndef CONFIG_ARCH_BOARD_ARTIK053 int main(int argc, char *argv[]) { server_cb(argc, argv); return 0; } #else #define IOTIVITY_TEST_STACKSIZE 4096 #define IOTIVITY_TEST_PRI 100 #define IOTIVITY_TEST_SCHED_POLICIY SCHED_RR #ifdef CONFIG_BUILD_KERNEL int main(int argc, char *argv[]) #else int ocf_mylight_main(int argc, char *argv[]) #endif { task_create("ocf_mylight_server", IOTIVITY_TEST_PRI, IOTIVITY_TEST_STACKSIZE, server_cb, (FAR char * const *)NULL); return 0; } #endif
webispy/ocf_mylight
ocf_mylight_platform.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include "ocf_mylight.h" static OCPlatformInfo platformInfo = { .platformID = "C0FFEE00-BAB0-FACE-B00C-00BA5EBA1100", .manufacturerName = "GeekRedLed", .manufacturerUrl = "http://geekredled.com", .modelNumber = "A053LIGHT0", .dateOfManufacture = "2017-07-11", .platformVersion = "BadIotivity1.2", .operatingSystemVersion = "fakerOS", .hardwareVersion = "ARTIK053", .firmwareVersion = "TEST_1.0", .supportUrl = "http://geekredled.com", .systemTime = "2017-07-11T16:06:00+09:00" }; int ocf_mylight_playform_init() { OCStackResult ret; ret = OCSetPlatformInfo(platformInfo); if (ret != OC_STACK_OK) { DBG("Platform Registration failed! (ret=%d)", ret); return -1; } return 0; }
miklhh/Othello
othello/othello-ai.h
<reponame>miklhh/Othello /* * Class AI. * This is the othello ai. For the record it only has one important method, * alphabeta. This is going to be wider later on. * * Good settings for the AI: (Updated 2016-06-16) * Good settings for the AI: (Updated 2019-04-13) * 1. Let the search depth be around 7 in alphabeta. * 2. Long time since I saw this last haha. * * Methods: * -- move evaluateMove () Make AI evaluate a new move. * -- void setAiColor(color) Switch AI color. * -- piece getAiColor() Get AI color. * -- void setCurrentGame(game) Give AI the current game. */ #ifndef _OTHELLO_AI_H #define _OTHELLO_AI_H #include "othello-game.h" #include <utility> using mini = std::pair<int, std::pair<unsigned, unsigned>>; using move = std::pair<unsigned, unsigned>; class ai { public: // Public methods. Methods for interacting with the AI and its different // components. move evaluateMove(); void setAiColor(piece color); void setCurrentGame(game newGame); piece getAiColor() const; void setSearchDepth(unsigned int searchDepth); private: // The alphabeta algorithm with alpha-beta prunings. mini alphaBeta(game node, int depth, bool maximizingPlayer, piece maximizingColor, int alpha, int beta, move moveMade, bool lateGame); // Heurisitc valuing functions. int heuristicValue(game _game, piece maximizingColor); int mobilityTester(game _game, piece maximizingColor); int cornerTester(game _game, piece maximizingColor); int fieldTester(game _game, piece maximizingColor); int tileWeight(unsigned int x, unsigned int y, game _game, piece maximizingColor); // Other private methods. piece reverseColor(piece color) const; mini makeMini(int value, unsigned int x, unsigned int y) const; int getSearchDepth(); private: // Ai local field variables. game _currentGame{}; piece _aiColor{ piece::WHITE }; unsigned _moveCount{ 0 }; unsigned _searchDepth{ 7 }; }; #endif
miklhh/Othello
othello/othello-game.h
<gh_stars>1-10 /* * This class represents a game of othello. It contains all the data and * functionallity requiered to play a game of othello. It has some extra methods * to ease the work for the AI. * * Public Methods: * -- bool makeMove(x,y,color) Use this method to make a move. * -- bool testLegitMove(x,y,color) Returns true if the move is legit. * -- moves getLegitMoves(color) Returns all the legit moves. * -- piece testTile(x,y) Returns the piece that stands on x,y. * -- board getBoard() Return a copy of the game board. * -- bool testGameOver() Returns true if the game is over. * -- unsigned testScoreWhite() Returns white players score. * -- unsigned testScroeBlack() Returns black players score. * -- piece reverseColor(color) Returns the opposite color. * */ #ifndef _OTHELLO_GAME_H #define _OTHELLO_GAME_H #include "othello-board.h" #include "moves.h" #include <deque> class game { private: /* * The physicl representation of the data. For more information about the * class board, please look in the othello-board header file. */ board _gameBoard{}; /* * The neighbour-board. This object keeps tracks of the tiles that should be * tested by the functions make-move and get legit moves! This is mostly * implemented to speed up the process of getting all the legit move, so * that the ai can work fast. */ neighbourBoard _neighbourBoard{}; bool _gameInitialized{ false }; // Is the game initialized? bool _gameOver{ false }; // Is the game over? piece _playerTurn{ piece::BLACK }; // Whos turn is it? public: game(); /* * Methods important for playing the game. Rules can be found: * https://en.wikipedia.org/wiki/Reversi#Rules */ bool makeMove(unsigned x, unsigned y, piece color); piece testPlayerTurn() const; piece testTile(unsigned x, unsigned y) const; moves getLegitMoves(piece color) const; bool testLegitMove(unsigned x, unsigned y, piece color) const; /* * Methods impotant for displaying game information. */ unsigned testScoreWhite() const; unsigned testScoreBlack() const; piece reverseColor(piece color) const; board getBoard() const; bool testGameOver() const; private: void initNewNeighbours(); bool testNeighbourTemplate( unsigned x, unsigned y, unsigned deltax, unsigned deltay) const; bool testLegitRowTemplate( unsigned x, unsigned y, unsigned deltax, unsigned deltay, piece testingColor, bool first) const; void flipRowTemplate( unsigned x, unsigned y, unsigned deltax, unsigned deltay, piece flipToColor); }; #endif
miklhh/Othello
othello/othello-board.h
/* * This header file holds all the 'low-level' physical data that the othello/ * reversi game uses. The class board and neighbourBoard is used for storing the * moves and neighbours in. */ #ifndef _OTHELLO_BOARD_H #define _OTHELLO_BOARD_H enum class piece { EMPTY, // EMPTY WHITE, // WHITE BLACK, // BLACK OOB, // Out-of-bound. BADPICE // Return if somethign goes wrong. }; enum class neighbourPiece { HN, // Has neighbour. DNHN, // Doesn't have neighbour. OOB, // Out of bounds. }; /* * Class for the neighbour-board system. The neighbour system is used to ease * the workload for the ai. The neighbour-system gives information about which * tiles that has to be tested and not. */ class neighbourBoard { public: // Public methods neighbourPiece setTile(unsigned x, unsigned y, neighbourPiece piece); neighbourPiece testTile(unsigned x, unsigned y) const noexcept; private: // The physical data neighbourPiece _neighbours[8][8]; }; /* * Class for the board. The class 'board' is where the data for the othello * board is stored. */ class board { public: board(); // Public methods. piece setTile(unsigned x, unsigned y, piece p); piece testTile(unsigned x, unsigned y) const noexcept; private: //The physical data of the board. piece _gameBoard[8][8]; }; #endif
miklhh/Othello
frontend/frontend.h
<reponame>miklhh/Othello /* * Frontend for othello game. */ #include "../othello/othello-board.h" #include <SFML/Graphics.hpp> #include <utility> #include "../othello/moves.h" class frontend { public: frontend(); ~frontend() = default; // Methods: void drawBoard(const board &b); void drawUI(piece playerTurn); void drawLegitMoves(moves legitMoves, piece color); public: // Renderwindow. sf::RenderWindow window; // Textures. sf::Texture blackTexture{}; sf::Texture whiteTexture{}; sf::Texture boardTexture{}; sf::Texture blackPlayerTurnTexture{}; sf::Texture whitePlayerTurnTexture{}; sf::Texture gameInfoTexture{}; // Sprites. sf::Sprite blackSprite{}; sf::Sprite whiteSprite{}; sf::Sprite boardSprite{}; sf::Sprite blackPlayerTurnSprite{}; sf::Sprite whitePlayerTurnSprite{}; sf::Sprite gameInfoSprite{}; };
miklhh/Othello
othello/moves.h
/* * Data structure to help store a set of moves throughtout the game. Is was some * sort of homemade jumbo-mombo in the original game, but the deque does its job * (and more) better, so now it's just an alias for the std::deque. */ #ifndef _MOVES_H #define _MOVES_H #include <utility> #include <deque> using GamePair = std::pair<unsigned, unsigned>; using moves = std::deque<GamePair>; #endif
groomsy/custom-font-loading-demo
FontTest/PreviewViewController.h
// // PreviewViewController.h // FontTest // // Created by <NAME> on 10/30/14. // Copyright (c) 2014 GroomsyDev. All rights reserved. // @import UIKit; @interface PreviewViewController : UIViewController @property (nonatomic, assign, getter=shouldLoadWithFontDescriptor) BOOL loadWithFontDescriptor; @property (nonatomic, assign) uint64_t start; @end
groomsy/custom-font-loading-demo
FontTest/HomeViewController.h
// // HomeViewController.h // FontTest // // Created by <NAME> on 10/30/14. // Copyright (c) 2014 GroomsyDev. All rights reserved. // @import UIKit; @interface HomeViewController : UIViewController @end
groomsy/custom-font-loading-demo
FontTest/AppDelegate.h
<reponame>groomsy/custom-font-loading-demo // // AppDelegate.h // FontTest // // Created by <NAME> on 10/30/14. // Copyright (c) 2014 GroomsyDev. All rights reserved. // @import UIKit; @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
raduMMR/HE_Bioinformatics
HE_Image.h
#pragma once #include <iostream> #include <vector> #include "seal.h" using namespace std; using namespace seal; class HE_Image { EncryptionParameters parms; mutable PolyCRTBuilder crtbuilder; /* @brief dimensiunea kernelului */ int kernel_size; public: HE_Image(EncryptionParameters &parms, int kernel_size); ~HE_Image(); void encrypt_for_filtering(int** &matrix_pixels, int N, vector<vector<BigPoly> > &encrypted_kernels, int &slot_count, BigPoly& public_key)const; void decrypt_after_filtering(int *&matrix_pixels, vector<BigPoly> enc_image, int slot_count, BigPoly &secret_key)const; void omp_decrypt_after_filtering(int *&matrix_pixels, vector<BigPoly> enc_image, int slot_count, BigPoly &secret_key)const; void encode_filter(int* &kernel, int N, vector<BigPoly> &filter, int slot_count)const; void hom_filtering(vector<vector<BigPoly> > &encrypted_kernels, vector<BigPoly> &filter, int original_kernel[], vector<BigPoly> &enc_image, EvaluationKeys& evaluation_keys, BigPoly &secret_key)const; void omp_hom_filtering(vector<vector<BigPoly> > &encrypted_kernels, vector<BigPoly> &filter, int original_kernel[], vector<BigPoly> &enc_image, EvaluationKeys& evaluation_keys, BigPoly &secret_key)const; /*PolyCRTBuilder& get_crt_builder() { return crtbuilder; } EncryptionParameters& get_enc_params() { return parms; }*/ };
raduMMR/HE_Bioinformatics
basic_examples.h
#pragma once #include <iostream> #include <string> #include <seal.h> using namespace std; using namespace seal; /* SEAL original examples*/ void example_basics(); void example_weighted_average(); void example_parameter_selection(); void example_batching(); void print_example_banner(string title); /* MMR's helper functions*/ void generate_parameters(EncryptionParameters &params, BigPoly &public_key, BigPoly &secret_key, EvaluationKeys &eval_keys); void save_parameters(vector<string> filename, EncryptionParameters &params, BigPoly &public_key, BigPoly &secret_key, EvaluationKeys &eval_keys); void load_parameters(vector<string> filename, EncryptionParameters &params, BigPoly &public_key, BigPoly &secret_key, EvaluationKeys &eval_keys); /*********************************************************************************************/ void test_encryption_time(); void test_mix_mult(); void test_mult_time(); void test_reliniarize_after_many_mults(); void test_homomorphic_conv(); void batch_low_param(EncryptionParameters &parms, BigPoly &public_key, BigPoly &secret_key, EvaluationKeys &evaluation_keys); void SEAL_eval_max_depth(EncryptionParameters &parms, BigPoly &public_key, BigPoly &secret_key, EvaluationKeys &evaluation_keys); void conv_parameter_selection(EncryptionParameters &optimal_parms); void test_real_conv(EncryptionParameters &parms, BigPoly &public_key, BigPoly &secret_key, EvaluationKeys &evaluation_keys); /* @brief save/load SEAL context parms, pk, sk, ek **************************************************** @read_write [in] true genereaza si salveaza contextul SEAL false incarca contextul SEAL **************************************************** @params [out] parms @params [out] public_key @params [out] secret_key @params [out] evaluation_keys */ void SEAL_save_load(bool read_write, EncryptionParameters &parms, BigPoly &public_key, BigPoly &secret_key, EvaluationKeys &evaluation_keys); /* @brief performs the convolution of the signals represented by their associated polynomials @param [in] v1 first signal @param [in] v2 the second signal @param [in] l1 the length of the first signal @param [in] l2 the length of the second signal @param [out] res the result of the convolution @param [out] l the length of the resulted signal */ void dummy_convolution(int *v1, int *v2, int l1, int l2, int *&res, int &l); /* @brief image sharpening with kernel 0 -1 0 -1 5 -1 0 -1 0 !!! kernelul si parametrii schemei se primesc ca params in functie */ void hom_image_sharpening(); /* @brief algoritm de partitionare homomorfice a esantioanelor unui semnal 1D in k clustere @pursose TEST_ONLY */ void hom_k_means(); void test_op(bool load = false); void test_crt_builder(const EncryptionParameters parms, PolyCRTBuilder &crtbuilder); void test_HE_image(); void test_field();
raduMMR/HE_Bioinformatics
Hom_Conv.h
#pragma once #include <iostream> #include <vector> #include <fstream> #include "seal.h" using namespace std; using namespace seal; class Hom_Conv { EncryptionParameters parms; BigPoly public_key; BigPoly secret_key; EvaluationKeys evaluation_keys; vector<BigPoly> filter; public: Hom_Conv(vector<string> key_files, ofstream &out); ~Hom_Conv(); void set_filter(vector<int>& filter); void encrypt_signal(vector<int> &signal, vector<BigPoly> &encrypted_signal)const; void decrypt_signal(vector<int> &signal, vector<BigPoly> &encrypted_signal)const; void filter_signal(vector<BigPoly> &in, vector<BigPoly> &out)const; void SIMD_set_filter(vector<int>& filter); void SIMD_encrypt_signal(vector<int> &signal, vector<BigPoly> &encrypted_signal)const; void SIMD_decrypt_signal(vector<int> &signal, vector<BigPoly> &encrypted_signal)const; void SIMD_filter_signal(vector<BigPoly> &in, vector<BigPoly> &out)const; void PF_set_filter(vector<int>& filter); void PF_decrypt_signal(vector<int> &signal, vector<BigPoly> &encrypted_signal)const; void PF_filter_signal(vector<BigPoly> &in, vector<BigPoly> &out)const; void PF_SIMD_set_filter(vector<int>& filter); void PF_SIMD_decrypt_signal(vector<int> &signal, vector<BigPoly> &encrypted_signal)const; void PF_SIMD_filter_signal(vector<BigPoly> &in, vector<BigPoly> &out)const; }; void test_Hom_Conv(); void test_hom_SIMD(); void test_hom_PF(); void test_hom_PF_SIMD();
raduMMR/HE_Bioinformatics
HE_Signal.h
<gh_stars>0 #pragma once #include <iostream> #include <vector> #include "seal.h" using namespace std; using namespace seal; class HE_Signal { protected: EncryptionParameters parms; BigPoly *secret_key; BigPoly *public_key; EvaluationKeys *evaluation_keys; public: HE_Signal(const char* poly_modulus = "1x^2048 + 1", int plain_modulus = 1073153, int decomposition_bit_count = 32, const char *coeff_modulus = "3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD793F83"); virtual ~HE_Signal(); virtual void encrypt_signal(vector<int> &plain_samples, vector<BigPoly> &encrypted_samples)const; virtual void decrypt_signal(vector<int> &plain_samples, vector<BigPoly> &encrypted_samples)const; void decrypt_no_relin(vector<int> &plain_samples, vector<BigPoly> &encrypted_samples)const; void mult_enc_signals(vector<BigPoly> &enc_s1, vector<BigPoly> &enc_s2, vector<BigPoly> &enc_s)const; void conv_window_method(vector<BigPoly> &filter, vector<BigPoly> &signal, vector<BigPoly> &result)const; }; void read_signal(const char *filename, vector<int> &signal); void write_signal(const char *filename, vector<int> &signal); void mult_plain_signals(vector<int> &s1, vector<int> &s2, vector<int> &s_mult);
raduMMR/HE_Bioinformatics
HE_Batch_Signal.h
<gh_stars>0 #pragma once #include "HE_Signal.h" class HE_Batch_Signal : public HE_Signal { size_t slot_count; mutable int window_size; PolyCRTBuilder *crtbuilder; /* @brief coeficientii filtrului criptati intr-un ctxt se afla impachetat un coeficient al filtrului de slots ori ______________________ filter_enc_coeffs[0] = | a_0| a_0 | ... | a_0 | */ vector<BigPoly> filter_enc_coeffs; vector<BigPoly> encrypted_masks; /* prelucrarea s-ar putea face si cu un filtru cu coeficienti necriptati */ vector<int> filtru_necriptat; public: HE_Batch_Signal(const char* poly_modulus = "1x^2048 + 1", int plain_modulus = 1073153, int decomposition_bit_count = 32, const char *coeff_modulus = "3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD793F83"); ~HE_Batch_Signal(); /* @brief seteaza filtrul cu care se va face convolutia */ void set_filter(vector<int> filter_coeffs); void encrypt_signal(vector<int> &signal_coeffs, vector<vector<BigPoly> > &encrypted_windows)const; void decrypt_signal(vector<int> &signal_coeffs, vector<BigPoly> &encrypted_signal)const; void filter_signal(vector<vector<BigPoly> > &encrypted_windows, vector<BigPoly> &encrypted_signal)const; };
raduMMR/HE_Bioinformatics
MyTimer.h
<reponame>raduMMR/HE_Bioinformatics<gh_stars>0 #pragma once #include <Windows.h> class MyTimer { LARGE_INTEGER frequency; LARGE_INTEGER start; LARGE_INTEGER end; public: void start_timer(); double stop_timer(); };
kasoki/pebble-fancywatch
src/main.c
#include <pebble.h> #include "weather.h" #define EVENT_TYPE 0 #define IMAGE_SIZE 55 #define NUMBER_OF_IMAGES 9 #define TIME_POS_Y 25 #define DATE_POS_Y TIME_POS_Y + 52 #define WEATHER_POS_Y DATE_POS_Y + 33 // 28 (old value) const int WEATHER_IMAGE_RESOURCE_IDS[NUMBER_OF_IMAGES] = { RESOURCE_ID_CLEAR_DAY, RESOURCE_ID_CLEAR_NIGHT, RESOURCE_ID_CLOUDY, RESOURCE_ID_SHOWER_RAIN, RESOURCE_ID_RAIN, RESOURCE_ID_THUNDERSTORM, RESOURCE_ID_SNOW, RESOURCE_ID_MIST, RESOURCE_ID_ERROR }; const int BATTERY_IMAGE_RESOURCE_IDS[4] = { RESOURCE_ID_BATTERY_0, RESOURCE_ID_BATTERY_1, RESOURCE_ID_BATTERY_2, RESOURCE_ID_BATTERY_3 }; enum { PEBBLE_EVENT_IDENT_NEW_WEATHER_INFO = 0, PEBBLE_EVENT_IDENT_CONFIGURATION_CHANGED = 1 }; enum { CONFIGURATION_IDENT_TEMP_METRIC = 1, CONFIGURATION_IDENT_SHOW_BATTERY = 2, CONFIGURATION_IDENT_USE_12HOUR_FORMAT = 3 }; enum { PERSIST_KEY_TEMP_METRIC = 0, PERSIST_KEY_SHOW_BATTERY = 1, PERSIST_KEY_USE_12_HOUR = 2 }; enum { BATTERY_HIDE = 0, BATTERY_SHOW = 1 }; static void init(void); static void destroy(void); static void window_load(Window*); static void window_unload(Window*); static void force_clock_tick_update(void); static void handle_clock_tick(struct tm*, TimeUnits); static void init_app_message(void); static void update_battery_indicator(void); static int get_battery_image(uint8_t); static bool battery_state_changed(void); static void destroy_battery_indicator(void); static void on_received_handler(DictionaryIterator*, void*); static void on_weather_handler_received(DictionaryIterator*, void*); static void on_configuration_handler_received(DictionaryIterator*, void*); static Window *window; static TextLayer *time_layer; static TextLayer *date_layer; static TextLayer *temp_layer; static BitmapLayer *weather_image_layer; static BitmapLayer *battery_image_layer; static GBitmap *weather_image; static GBitmap *battery_image; static weather_t weather; static BatteryChargeState charge_state; static uint8_t old_battery_percent = -1; static int TEMPERATURE_METRIC = WEATHER_CONFIGURATION_IDENT_CELSIUS; static int SHOW_BATTERY = BATTERY_SHOW; static bool USE_12_HOUR_FORMAT = false; static bool battery_indicator_initialized = false; /** init fancy watch */ static void init(void) { // retrieve data TEMPERATURE_METRIC = persist_exists(PERSIST_KEY_TEMP_METRIC) ? persist_read_int(PERSIST_KEY_TEMP_METRIC) : WEATHER_CONFIGURATION_IDENT_CELSIUS; SHOW_BATTERY = persist_exists(PERSIST_KEY_SHOW_BATTERY) ? persist_read_int(PERSIST_KEY_SHOW_BATTERY) : BATTERY_SHOW; USE_12_HOUR_FORMAT = persist_exists(PERSIST_KEY_USE_12_HOUR) ? persist_read_bool(PERSIST_KEY_USE_12_HOUR) : clock_is_24h_style(); window = window_create(); // init weather struct weather = (weather_t) { .icon_id = WEATHER_ICON_ERROR, .temp_kelvin = 0, .temp_celsius = 0, .temp_fahrenheit = 0 }; init_app_message(); window_set_window_handlers(window, (WindowHandlers) { .load = window_load, .unload = window_unload, }); const bool animated = true; window_stack_push(window, animated); } /** init app messages */ static void init_app_message(void) { app_message_open(64, 16); app_message_register_inbox_received(on_received_handler); } /** destroy fancy watch */ static void destroy(void) { // store data persist_write_int(PERSIST_KEY_TEMP_METRIC, TEMPERATURE_METRIC); persist_write_int(PERSIST_KEY_SHOW_BATTERY, SHOW_BATTERY); persist_write_bool(PERSIST_KEY_USE_12_HOUR, USE_12_HOUR_FORMAT); destroy_battery_indicator(); window_destroy(window); } /** load and setup window */ static void window_load(Window *window) { window_set_background_color(window, GColorBlack); Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); // setup time layer time_layer = text_layer_create((GRect) { .origin = { 0, TIME_POS_Y }, .size = { bounds.size.w, 50 } }); text_layer_set_text_color(time_layer, GColorWhite); text_layer_set_background_color(time_layer, GColorClear); text_layer_set_font(time_layer, fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_ROBOTO_BOLD_SUBSET_49))); text_layer_set_text_alignment(time_layer, GTextAlignmentCenter); // setup date layer date_layer = text_layer_create((GRect) { .origin = { 0, DATE_POS_Y }, .size = { bounds.size.w, 25 } }); text_layer_set_text_color(date_layer, GColorWhite); text_layer_set_background_color(date_layer, GColorClear); text_layer_set_font(date_layer, fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_ROBOTO_CONDENSED_21))); text_layer_set_text_alignment(date_layer, GTextAlignmentCenter); // setup temp layer temp_layer = text_layer_create((GRect) { .origin = { bounds.size.w / 2 + 15, WEATHER_POS_Y + IMAGE_SIZE/2 - 11 }, .size = { bounds.size.w / 2, 23 } }); text_layer_set_text_color(temp_layer, GColorWhite); text_layer_set_background_color(temp_layer, GColorClear); text_layer_set_font(temp_layer, fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_ROBOTO_CONDENSED_21))); text_layer_set_text_alignment(temp_layer, GTextAlignmentLeft); // add children layer_add_child(window_layer, text_layer_get_layer(time_layer)); layer_add_child(window_layer, text_layer_get_layer(date_layer)); layer_add_child(window_layer, text_layer_get_layer(temp_layer)); force_clock_tick_update(); // subscribe to tick service tick_timer_service_subscribe(MINUTE_UNIT, handle_clock_tick); } /** unload window */ static void window_unload(Window *window) { // destroy text layer text_layer_destroy(time_layer); text_layer_destroy(date_layer); text_layer_destroy(temp_layer); // destroy images gbitmap_destroy(weather_image); // destroy bitmap layer bitmap_layer_destroy(weather_image_layer); // unsubscribe services tick_timer_service_unsubscribe(); app_message_deregister_callbacks(); } static void force_clock_tick_update(void) { // call ticker time_t now = time(NULL); struct tm *tick_time; tick_time = localtime(&now); handle_clock_tick(tick_time, MINUTE_UNIT); } /** is called every tick (every second if not low energy mode) */ static void handle_clock_tick(struct tm *tick_time, TimeUnits units_changed) { charge_state = battery_state_service_peek(); if(SHOW_BATTERY == BATTERY_SHOW) { if(battery_state_changed() || !battery_indicator_initialized) { APP_LOG(APP_LOG_LEVEL_DEBUG, "CHANGE BATTERY STATE"); battery_indicator_initialized = true; update_battery_indicator(); } else { APP_LOG(APP_LOG_LEVEL_DEBUG, "DON'T CHANGE BATTERY STATE"); } } else { destroy_battery_indicator(); } // print time static char buffer[] = "00:00"; if(USE_12_HOUR_FORMAT) { strftime(buffer, sizeof("00:00"), "%I:%M", tick_time); } else { strftime(buffer, sizeof("00:00"), "%H:%M", tick_time); } text_layer_set_text(time_layer, buffer); // print date static char date_string[] = "XXX. XX. XXX."; int date_string_size = sizeof(date_string)/sizeof(date_string[0]); strftime(date_string, date_string_size, "%a. %d. %b.", tick_time); APP_LOG(APP_LOG_LEVEL_DEBUG, "current date: %s", date_string); text_layer_set_text(date_layer, date_string); } static void update_battery_indicator(void) { Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); uint8_t percent = charge_state.charge_percent; int battery_resource_id = get_battery_image(percent); destroy_battery_indicator(); battery_image = gbitmap_create_with_resource(BATTERY_IMAGE_RESOURCE_IDS[battery_resource_id]); battery_image_layer = bitmap_layer_create((GRect) { .origin = { bounds.size.w / 2 + 13, 0 }, .size = { bounds.size.w / 2, 42 } }); bitmap_layer_set_bitmap(battery_image_layer, battery_image); layer_add_child(window_layer, bitmap_layer_get_layer(battery_image_layer)); } static int get_battery_image(uint8_t percent) { if(percent >= 75) { return 3; } else if(percent >= 50) { return 2; } else if(percent > 20) { return 1; } else { return 0; } } static bool battery_state_changed(void) { uint8_t percent = charge_state.charge_percent; bool has_changed = false; has_changed = get_battery_image(old_battery_percent) != get_battery_image(percent); old_battery_percent = percent; return has_changed; } static void destroy_battery_indicator(void) { if(battery_image != NULL) { gbitmap_destroy(battery_image); layer_remove_from_parent(bitmap_layer_get_layer(battery_image_layer)); bitmap_layer_destroy(battery_image_layer); } } /** message from PebbleKit JS received */ static void on_received_handler(DictionaryIterator *received, void *context) { APP_LOG(APP_LOG_LEVEL_DEBUG, "received information from PebbleKitJS"); Tuple *event_type = dict_find(received, EVENT_TYPE); switch(event_type->value->int8) { case PEBBLE_EVENT_IDENT_NEW_WEATHER_INFO: APP_LOG(APP_LOG_LEVEL_DEBUG, "received new weather event"); on_weather_handler_received(received, context); break; case PEBBLE_EVENT_IDENT_CONFIGURATION_CHANGED: APP_LOG(APP_LOG_LEVEL_DEBUG, "received configuration changed event"); on_configuration_handler_received(received, context); break; default: APP_LOG(APP_LOG_LEVEL_DEBUG, "received invalid event id: %d", event_type->value->int8); break; } } static void on_weather_handler_received(DictionaryIterator *received, void *context) { Tuple *icon_id = dict_find(received, WEATHER_MESSAGE_ICON_ID); Tuple *temp_kelvin = dict_find(received, WEATHER_MESSAGE_TEMP_KELVIN); Tuple *temp_celsius = dict_find(received, WEATHER_MESSAGE_TEMP_CELSIUS); Tuple *temp_fahrenheit = dict_find(received, WEATHER_MESSAGE_TEMP_FAHRENHEIT); bool error = false; // update weather if(icon_id && temp_kelvin && temp_celsius && temp_fahrenheit) { weather.icon_id = icon_id->value->int8; weather.temp_kelvin = temp_kelvin->value->int8; weather.temp_celsius = temp_celsius->value->int8; weather.temp_fahrenheit = temp_fahrenheit->value->int8; } else { weather.icon_id = WEATHER_ICON_ERROR; weather.temp_kelvin = 0; weather.temp_celsius = 0; weather.temp_fahrenheit = 0; error = true; } if(weather_image != NULL) { gbitmap_destroy(weather_image); layer_remove_from_parent(bitmap_layer_get_layer(weather_image_layer)); bitmap_layer_destroy(weather_image_layer); } int temperature = -1; switch(TEMPERATURE_METRIC) { case WEATHER_CONFIGURATION_IDENT_CELSIUS: temperature = weather.temp_celsius; break; case WEATHER_CONFIGURATION_IDENT_FAHRENHEIT: temperature = weather.temp_fahrenheit; break; case WEATHER_CONFIGURATION_IDENT_KELVIN: temperature = weather.temp_kelvin; break; default: temperature = weather.temp_celsius; break; } // set weather text static char temp_string[] = "XXXXX"; if(!error) { snprintf(temp_string, sizeof("-1337°"), "%d°", temperature); } else { strcpy(temp_string, ""); } text_layer_set_text(temp_layer, temp_string); // set weather image Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); int weather_image_pos_x = bounds.size.w / 2 - IMAGE_SIZE - 5; if(error) { weather_image_pos_x = bounds.size.w / 2 - IMAGE_SIZE + 20; } weather_image = gbitmap_create_with_resource(WEATHER_IMAGE_RESOURCE_IDS[weather.icon_id]); weather_image_layer = bitmap_layer_create((GRect) { .origin = { weather_image_pos_x, WEATHER_POS_Y }, .size = { bounds.size.w / 2, IMAGE_SIZE } }); bitmap_layer_set_bitmap(weather_image_layer, weather_image); layer_add_child(window_layer, bitmap_layer_get_layer(weather_image_layer)); } static void on_configuration_handler_received(DictionaryIterator *received, void *context) { Tuple *temp_metric = dict_find(received, CONFIGURATION_IDENT_TEMP_METRIC); Tuple *show_battery = dict_find(received, CONFIGURATION_IDENT_SHOW_BATTERY); Tuple *use_12hour = dict_find(received, CONFIGURATION_IDENT_USE_12HOUR_FORMAT); TEMPERATURE_METRIC = temp_metric->value->int8; SHOW_BATTERY = show_battery->value->int8; USE_12_HOUR_FORMAT = use_12hour->value->int8 == 1; force_clock_tick_update(); } int main(void) { init(); APP_LOG(APP_LOG_LEVEL_DEBUG, "Done initializing fancy watch, pushed window: %p", window); app_event_loop(); destroy(); }
kasoki/pebble-fancywatch
src/weather.h
#ifndef __FW_WEATHER_H__ #define __FW_WEATHER_H__ enum { WEATHER_MESSAGE_ICON_ID = 1, WEATHER_MESSAGE_TEMP_KELVIN = 2, WEATHER_MESSAGE_TEMP_CELSIUS = 3, WEATHER_MESSAGE_TEMP_FAHRENHEIT = 4 }; enum { WEATHER_CONFIGURATION_IDENT_CELSIUS = 0, WEATHER_CONFIGURATION_IDENT_FAHRENHEIT = 1, WEATHER_CONFIGURATION_IDENT_KELVIN = 2 }; enum { WEATHER_ICON_CLEAR_DAY, WEATHER_ICON_CLEAR_NIGHT, WEATHER_ICON_CLOUDY, WEATHER_ICON_SHOWER_RAIN, WEATHER_ICON_RAIN, WEATHER_ICON_THUNDERSTORM, WEATHER_ICON_SNOW, WEATHER_ICON_MIST, WEATHER_ICON_ERROR }; typedef struct { int icon_id; int temp_kelvin; int temp_celsius; int temp_fahrenheit; } weather_t; #endif
lanserxt/AGToggleFieldSet
AGToggleFieldSetView/AGToggleFieldSetView.h
// // AGToggleFieldSetView.h // ToggleFieldSets // // Created by <NAME> on 05.03.15. // Copyright (c) 2015 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> typedef enum { AGToggleTablesVertical = 0, AGToggleTablesHorizontal = 1 }AGToggleTablesOrientation; typedef enum { AGToggleButtonsPositionOnSides = 0, AGToggleButtonsPositionCentered = 1 }AGToggleButtonsPosition; @protocol AGToggleFieldSetViewDelegate; @interface AGToggleFieldSetView : UIView - (void)setToggleTablesOrientation:(AGToggleTablesOrientation)orientation; - (void)setToggleButtonsPosition:(AGToggleButtonsPosition)position; - (NSArray*)leftItems; - (NSArray*)rightItems; - (void)setLeftItems:(NSArray*)leftItems; - (void)setRightItems:(NSArray*)rightItems; - (void)setDescriptionField:(NSString*)descriptionString; @property (nonatomic, weak) id <AGToggleFieldSetViewDelegate> delegate; @property (nonatomic, strong) UIView *separatorView; @property (nonatomic, strong) UITableView *leftTable; @property (nonatomic, strong) UITableView *rightTable; @property (nonatomic, strong) UIButton *upArrowButton; @property (nonatomic, strong) UIButton *downArrowButton; @end @protocol AGToggleFieldSetViewDelegate @optional - (void)fieldDidToggle:(AGToggleFieldSetView*)toggleFieldSet; @end
RIKEN-LQCD/qws
get_tofu_coord_openY.c
<reponame>RIKEN-LQCD/qws<gh_stars>1-10 //**************************************************************************************** // // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2018-2020, <NAME> <<EMAIL>> // Copyright (c) 2019-2020, <NAME> <<EMAIL>> // // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer listed // in this license in the documentation and/or other materials // provided with the distribution. // // * Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------------------- // ACKNOWLEDGMENT // // This software has been developed in a co-design working group for the lattice QCD // supported by MEXT's programs for the Development and Improvement for the Next // Generation Ultra High-Speed Computer System, under its Subsidies for Operating the // Specific Advanced Large Research Facilities, and Priority Issue 9 // (Elucidation of the Fundamental Laws and Evolution of the Universe) to be tackled by // using the Supercomputer Fugaku. // //**************************************************************************************** /* rank map for 4-dim system Tofu X: 24 Tofu Y: open Tofu Z: 24 Tofu A,B,C: 2x3x2 */ #include <stdint.h> #include <stdio.h> #include <assert.h> #include "rankmap_list.h" #include "get_tofu_coord_common.h" int get_tofu_coord_and_tni_openY(const int myrank, const uint8_t *my_coords, const uint8_t *coords_org, const uint8_t *coords_size, const uint8_t *coords_min, const uint8_t *coords_max, int *rank_coord, int *rank_size, uint8_t (*positive_neighbor_coords)[6], int *pos_rank_in_node, uint8_t (*negative_neighbor_coords)[6], int *neg_rank_in_node, int *tni_list, int DirX, int DirY, int DirZ){ const int DirA=DirA_; const int DirB=DirB_; const int DirC=DirC_; if(myrank==0){ printf("rankmap for open Y tofu axis (20200622)\n"); printf(" coords_org: %d %d %d %d %d %d\n", coords_org[0], coords_org[1], coords_org[2], coords_org[3], coords_org[4], coords_org[5]); printf(" coords_size: %d %d %d %d %d %d\n", coords_size[0], coords_size[1], coords_size[2], coords_size[3], coords_size[4], coords_size[5]); printf(" coords_min: %d %d %d %d %d %d\n", coords_min[0], coords_min[1], coords_min[2], coords_min[3], coords_min[4], coords_min[5]); printf(" coords_max: %d %d %d %d %d %d\n", coords_max[0], coords_max[1], coords_max[2], coords_max[3], coords_max[4], coords_max[5]); fflush(0); } // policy // TZ+ tni=0 // TZ- tni=1 // ///////////////////////////////////////////// // QX ///////////////////////////////////////////// int TA[6] ={0,1,1,1,0,0}; int TZc[6]={0,0,1,2,2,1}; int size_x = 6; // node size in x-direction // starting from "o" // QX+ // 0 0 // +---> +---> + // ^ | 0 ^ TA // 1| \| | // o <---+ <---+ ---->TZc // 1 1 int TNI_Xp[6]={1,0,0,0,1,1}; // QX- (coordinate: clockwise, sending direction: counter-clockwise) // 1 1 // + <---+ <---+ // 1| ^ ^ TA // \| |0 | // o---> +---> + ---->TZc // 0 0 int TNI_Xm[6]={0,1,1,1,0,0}; ///////////////////////////////////////////// // QY ///////////////////////////////////////////// //int TC[6] ={0,1,1,1,0,0}; //int TZd[6]={0,0,1,2,2,1}; int size_TZd=coords_size[DirZ]/3; int size_y = 2*size_TZd; // node size in x-direction int TC[16] ={-1}; int TZd[16]={-1}; int n=0; TC[n]=0; TZd[n]=0; n++; for(int z=0; z<size_TZd; z++){ TC[n]=1; TZd[n]=z; n++; } for(int z=size_TZd-1; z>0; z--){ TC[n]=0; TZd[n]=z; n++; } assert(size_y == n); // QY+ : uses peridicity of TZd // the loop back to the same node is not depicted in the figure // 0 0 // +---> + + ---> + // ^ |0 ^ |0 ^ TC // 0| \| |0 \| | // o +---> + +---> ... ---->TZd // 0 0 // int TNI_Yp[12]={2,0, 2,0, 2,0, 2,0, 2,0,... 2,0}; // 2 for loop back; TC, TZd int TNI_Yp[32]={0}; n=0; while(n<size_y*2){ TNI_Yp[n] = 2; n++; // loop back TNI_Yp[n] = 0; n++; } // QY- : uses peridicity of TZd // the loop back to the same node is not depicted in the figure // 1 1 // + <---+ + <---+ // 1| ^ |1 ^ ^ TC // \| |1 \| |1 | // o + <---+ + <--- ... ---->TZd // 1 //int TNI_Ym[12]={1,3, 1,3,..., 1,3}; // 3 for loop back int TNI_Ym[32]={1}; n=0; while(n<size_y*2){ TNI_Ym[n]=1; n++; TNI_Ym[n]=3; n++; // loop back } ///////////////////////////////////////////// // QZ ///////////////////////////////////////////// int TX[24]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23}; int size_z=24; // node size in z-direction // QZ+: use torus in TX // the loop back to the same node is not depicted in th figure // 2 2 2 // o---> +---> ... +---> + // ^ | 2 // |_____________________| // int TNI_Zp[48]; n=0; while(n<size_z*2){ TNI_Zp[n]=2; n++; // 2 for loop back as well; TX } // QZ-: use torus in TX // the loop back to the same node is not depicted in th figure // 3 3 3 // o <---+ <--- ... <---+ // 3| ^ // |____________________| // int TNI_Zm[48]; n=0; while(n<size_z*2){ TNI_Zm[n]=3; n++; // 3 for loop back as well } ///////////////////////////////////////////// // QT ///////////////////////////////////////////// int TB[66]={-1}; int TY[66]={-1}; int size_t=3*coords_size[DirY]; // node size in t-direction // Y=1: TB= 0 12; TY= 0 00 // Y=2: TB= 0 1221 0; TY= 0 0011 1 // Y=3: TB= 0 1221 12 00; TY= 0 0011 22 21 // Y=4: TB= 0 1221 1221 000; TY= 0 0011 2233 321 // Y=5: TB= 0 1221 1221 12 0000; TY= 0 0011 2233 44 4321 // Y=6: TB= 0 1221 1221 1221 00000; TY= 0 0011 2233 4455 54321 // ... /// int TB4[4]={1,2,2,1}; n=0; TB[n]=0; TY[n]=0; n++; int ii=0; for(int i=0; i<2*coords_size[DirY];i++){ TB[n]=TB4[ii]; TY[n]=i/2; ii=(ii+1)%4; n++; } for(int i=coords_size[DirY]-1; i>0; i--){ TB[n]=0; TY[n]=i; n++; } // QT+ : uses peridicity of TB // // 4 4 4 // +---> + +---> + ...---> + // ^ |4 ^ |4 ^ |4 ^ TB // 4| \| |4 \| | \| | // + +---> + + --->+ + ---->TY // ^ 4 4 |4 // 4| \| // o <---+ <---+ <---+ ... ... <---+ // 4 4 4 4 // // or +--- // ^ | // 4 | |4 // ... + | // | // | // ... <---+<-- // 4 int TNI_Tp[66]={4}; // TB, TY for(int i=0; i<size_t; i++) {TNI_Tp[i] = 4; } // QT- : uses peridicity of TB // // 5 5 5 // + <---+ + <---+ ... <---+ // |5 ^ |5 ^ |5 ^ ^ TB // \| |5 \| |5 \| |5 | // + + <---+ + <---+ + ---->TY // |5 5 5 ^ // \| |5 // o---> +---> +---> + ... ...---> + // 5 5 5 5 // // or +<-- // 5| | // \| | // ... + | // | // |5 // ...---> +--- // 5 int TNI_Tm[66]={5}; // TB, TY for(int i=0; i<size_t; i++) {TNI_Tm[i] = 5; } const int Dir[6]={DirA,DirB,DirC,DirX,DirY,DirZ}; const int *Tmap[7]={TA,TB,TC,TX,TY,TZc,TZd}; const int Nsize[4]={size_x,size_y,size_z,size_t}; print_tofu(myrank, Dir, Tmap, Nsize, coords_size); // find the logical rank coordinate of this rank and the tofu coordinates of the neighbors int mapid=set_neighbors(myrank, my_coords, coords_org, coords_size, coords_min, coords_max, rank_coord, rank_size, positive_neighbor_coords, pos_rank_in_node, negative_neighbor_coords, neg_rank_in_node, Dir, Tmap, Nsize); if(mapid <0 ){ // something is wrong with rank coordinate return mapid; } // tni list const int *tni_list_full[8]={TNI_Xp, TNI_Xm, TNI_Yp, TNI_Ym, TNI_Zp, TNI_Zm, TNI_Tp, TNI_Tm}; for(int dir2=0; dir2<8; dir2++){ int coord=rank_coord[dir2/2]; tni_list[dir2]=tni_list_full[dir2][coord]; } if(myrank==0){ printf("tni map (rankid=%d)\n", myrank); for(int dir2=0; dir2<8; dir2++){ printf(" dir=%d:", dir2); for(int i=0; i<rank_size[dir2/2]; i++) { printf(" %d",tni_list_full[dir2][i]); } printf("\n"); } fflush(stdout); } return RANKMAP_OPEN_Y; }
RIKEN-LQCD/qws
get_tofu_coord_common.h
//**************************************************************************************** // // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2018-2020, <NAME> <<EMAIL>> // Copyright (c) 2019-2020, <NAME> <<EMAIL>> // // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer listed // in this license in the documentation and/or other materials // provided with the distribution. // // * Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------------------- // ACKNOWLEDGMENT // // This software has been developed in a co-design working group for the lattice QCD // supported by MEXT's programs for the Development and Improvement for the Next // Generation Ultra High-Speed Computer System, under its Subsidies for Operating the // Specific Advanced Large Research Facilities, and Priority Issue 9 // (Elucidation of the Fundamental Laws and Evolution of the Universe) to be tackled by // using the Supercomputer Fugaku. // //**************************************************************************************** /* rank map for 4-dim system */ #ifndef GET_TOFU_COORD_COMMON_H #define GET_TOFU_COORD_COMMON_H //enum {DirX_=0, DirY_, DirZ_, DirA_, DirB_, DirC_}; static const char *tofu_char="XYZABC"; #define _MAX_TXxTY 640 /* helper functions */ void get_relative_coords(int *rcoords, int *size, const uint8_t *my_coords, const uint8_t *coords_org, const uint8_t *coords_size, const uint8_t *coords_min, const uint8_t *coords_max); void to_absoulte_coords(uint8_t (*neighbor_coords)[6], const uint8_t *coords_org, const uint8_t *coords_size, const uint8_t *coords_min, const uint8_t *coords_max); int node_coords_is_ok(int myrank, const int *rcoords, int node_x, int node_y, int node_z, int node_t); int lookup1(int rcoord1, const int *T1, int size); int lookup2(int rcoord1, const int *T1, int rcoord2, const int *T2, int size); void dump_coords(int myrank, const uint8_t *my_coords, const uint8_t (*positive_neighbor_coords)[6], const uint8_t (*negative_neighbor_coords)[6]); void print_coords_and_tni(int myrank, const uint8_t *my_coords, const int *rank_coord, const uint8_t (*positive_neighbor_coords)[6], const uint8_t (*negative_neighbor_coords)[6], const int *tni_list); void print_tni(int myrank, const int *rank_coord, const int **tni_list_array); /* void print_tofu_openXYZ(const int myrank, const int **Tmap, const int *Nsize, const uint8_t *coords_size, const int DirX, const int DirY, const int DirZ); int set_neighbors_openXYZ(const int myrank, const uint8_t *my_coords, const uint8_t *coords_org, const uint8_t *coords_size, const uint8_t *coords_min, const uint8_t *coords_max, int *rank_coord, int *rank_size, uint8_t (*positive_neighbor_coords)[6], int *pos_rank_in_node, uint8_t (*negative_neighbor_coords)[6], int *neg_rank_in_node, int DirX, int DirY, int DirZ, const int **Tmap, const int *Nsize); void print_tofu_openY(const int myrank, const int **Tmap, const int *Nsize, const uint8_t *coords_size, const int DirX, const int DirY, const int DirZ); int set_neighbors_openY(const int myrank, const uint8_t *my_coords, const uint8_t *coords_org, const uint8_t *coords_size, const uint8_t *coords_min, const uint8_t *coords_max, int *rank_coord, int *rank_size, uint8_t (*positive_neighbor_coords)[6], int *pos_rank_in_node, uint8_t (*negative_neighbor_coords)[6], int *neg_rank_in_node, int DirX, int DirY, int DirZ, const int **Tmap, const int *Nsize); */ int set_neighbors(const int myrank, const uint8_t *my_coords, const uint8_t *coords_org, const uint8_t *coords_size, const uint8_t *coords_min, const uint8_t *coords_max, int *rank_coord, int *rank_size, uint8_t (*positive_neighbor_coords)[6], int *pos_rank_in_node, uint8_t (*negative_neighbor_coords)[6], int *neg_rank_in_node, const int *Dir, const int **Tmap, const int *Nsize); void print_tofu(const int myrank, const int *Dir, const int **Tmap, const int *Nsize, const uint8_t *coords_size); #endif
RIKEN-LQCD/qws
timing.c
//**************************************************************************************** // // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2018-2020, <NAME> <<EMAIL>> // Copyright (c) 2019-2020, <NAME> <<EMAIL>> // // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer listed // in this license in the documentation and/or other materials // provided with the distribution. // // * Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------------------- // ACKNOWLEDGMENT // // This software has been developed in a co-design working group for the lattice QCD // supported by MEXT's programs for the Development and Improvement for the Next // Generation Ultra High-Speed Computer System, under its Subsidies for Operating the // Specific Advanced Large Research Facilities, and Priority Issue 9 // (Elucidation of the Fundamental Laws and Evolution of the Universe) to be tackled by // using the Supercomputer Fugaku. // //**************************************************************************************** //#include "single_fields.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/time.h> #ifdef _OPENMP #include <omp.h> #endif #define MAXCHAR 64 //extern int nodeid_f; //int nodeid_f=0; extern int rank; extern FILE *para_outputfile; typedef struct timing_node { struct timing_node *next; char *id; unsigned long call_number; double total_time; double recent_start_clock; } timing_list; timing_list *init_timing_node (void); double get_clock (void); void check_timing_ (const char *id) { static timing_list *tl = NULL; double clock_now = get_clock (); timing_list *cur; if (tl == NULL) tl = init_timing_node (); cur = tl; #ifdef _OPENMP if (omp_get_thread_num() !=0) return; #endif if (id == NULL) { fprintf (para_outputfile, "%8s\t%-32s\t%8s\t%12s\t%12s\n", "rank","func_id", "calls", "total(s)", "average(s)"); for (;;) { timing_list *old = cur; if (cur == NULL || cur->id == NULL) break; fprintf (para_outputfile, "%8d\t%-32s\t%8ld\t%12.6e\t%12.6e\n", rank, cur->id, cur->call_number, cur->total_time, cur->total_time / (double) cur->call_number); cur = cur->next; free (old); } return; } for (;;) { if (cur->id == NULL) /* it's a new id */ { cur->id = (char*)id; cur->recent_start_clock = clock_now; break; /* finished creating the new id */ } else /* looking at cur */ { if (strncmp (id, cur->id, MAXCHAR) == 0) /* this id */ { if (cur->recent_start_clock == 0) /* start */ { cur->recent_start_clock = clock_now; } else /* end */ { cur->call_number++; cur->total_time += clock_now - cur->recent_start_clock; cur->recent_start_clock = 0; } break; /* finished this id */ } else /* not this one */ { if (cur->next == NULL) /* end */ { cur = init_timing_node (); cur->next = tl; tl = cur; } else /* not end */ { cur = cur->next; } } } } } timing_list * init_timing_node (void) { timing_list *cur = (timing_list *) malloc (sizeof (timing_list)); cur->next = NULL; cur->id = NULL; cur->call_number = 0; cur->total_time = 0; cur->recent_start_clock = 0; return cur; } #include<time.h> double get_clock (void) { struct timespec tp; clock_gettime(CLOCK_REALTIME, &tp); return ((double) tp.tv_sec + (double) tp.tv_nsec * 1e-9); //struct timeval tp; //gettimeofday(&tp, NULL); //return ((double) tp.tv_sec + (double) tp.tv_usec * 1e-6); } /////////////////////////////////////////////////////// // print out timing statistics // exposed to Fortran with underscore convension /////////////////////////////////////////////////////// void print_timing_(void) { check_timing_ (NULL); }
RIKEN-LQCD/qws
ddd_out_h.h
//**************************************************************************************** // // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2018-2020, <NAME> <<EMAIL>> // Copyright (c) 2019-2020, <NAME> <<EMAIL>> // // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer listed // in this license in the documentation and/or other materials // provided with the distribution. // // * Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------------------- // ACKNOWLEDGMENT // // This software has been developed in a co-design working group for the lattice QCD // supported by MEXT's programs for the Development and Improvement for the Next // Generation Ultra High-Speed Computer System, under its Subsidies for Operating the // Specific Advanced Large Research Facilities, and Priority Issue 9 // (Elucidation of the Fundamental Laws and Evolution of the Universe) to be tackled by // using the Supercomputer Fugaku. // //**************************************************************************************** #ifndef _DDD_OUT_H_H #define _DDD_OUT_H_H #include "ddd_out_h_0_inline.h" //---------------------------------------------------------------------------------------- preprocess mult D for boundary void ddd_out_pre_h_(const sch_t * __restrict__ in, const int *idomain) // // Send for Wilson/Clover operator, Deo or Doe, in a even/odd domain block // // oute = oute + factor Meo ine // // or // // outo = outo + factor Moe ino // // Note: Deo = -kappa Meo, Doe = -kappa Moe // // in : quark field in an even/odd domain (odd for idomain = 0, even for idomain = 1). // input domain is opposite to idomain // idomain : domain index, 0 for even output, 1 for odd output // { // // pack data for send // _S_MULT_WD_DEO_OUT_SEND_HPC_TIC_; int xdmn, ydmn, zdmn, tdmn; xdmn = 1 - *idomain; if (npe[1] == 1) { ydmn = *idomain; } else { ydmn = 1 - *idomain; } if (npe[2] == 1) { zdmn = *idomain; } else { zdmn = 1 - *idomain; } if (npe[3] == 1) { tdmn = *idomain; } else { tdmn = 1 - *idomain; } pgluh_t __restrict__ gx = &gluh[vols*0 + NDIM*vols*xdmn]; pgluh_t __restrict__ gy = &gluh[vols*1 + NDIM*vols*ydmn]; pgluh_t __restrict__ gz = &gluh[vols*2 + NDIM*vols*zdmn]; pgluh_t __restrict__ gt = &gluh[vols*3 + NDIM*vols*tdmn]; #pragma omp parallel { #pragma omp for collapse(3) nowait for (int t = 0; t < nt; ++t) { for (int z = 0; z < nz; ++z) { for (int y = 0; y < ny; ++y) { int it = nxs*ny*nz*t; int iz = nxs*ny*z; int iy = nxs*y; // X-forward { //int x = nxs-1; int ixf = 0 + iy + iz + it; int i0 = y + ny*z + ny*nz*t; __mult_x_forw_pre_3_(xfh_send[i0],in[vols*xdmn+ixf]); } // X-backward { //int x = 0; int ixb = nxs-1 + iy + iz + it; int i1 = y + ny*z + ny*nz*t; projsch1_t a __attribute__((aligned(_ALIGN_SIZE))); __mult_x_back_pre_3_(a,in[vols*xdmn+ixb]); __mult_udag_y_3_(xbh_send[i1],a,(*(gx + ixb))); } } } } #pragma omp for collapse(3) nowait for (int t = 0; t < nt; ++t) { for (int z = 0; z < nz; ++z) { for (int x = 0; x < nxs; ++x) { int it = nxs*ny*nz*t; int iz = nxs*ny*z; // // Y-forward send // { //int y = ny-1; int iyf = x + iz + it; int i2 = x + nxs*z + nxs*nz*t; __mult_y_forw_pre_(yfh_send[i2],in[vols*ydmn+iyf]); } // // Y-backward send // { //int y = 0; int iyb = x + iz + it + (ny-1)*nxs; int i3 = x + nxs*z + nxs*nz*t; __attribute__((aligned(_ALIGN_SIZE))) projsch_t a; __mult_y_back_pre_(a,in[vols*ydmn+iyb]); __mult_udag_y_(ybh_send[i3],a,(*(gy + iyb))); } } } } #pragma omp for collapse(3) nowait for (int t = 0; t < nt; ++t) { for (int y = 0; y < ny; ++y) { for (int x = 0; x < nxs; ++x) { int it = nxs*ny*nz*t; int iy = nxs*y; // // Z-forward send // { //int z = nz-1; int izf = x + iy + it; int i4 = x + nxs*y + nxs*ny*t; __mult_z_forw_pre_(zfh_send[i4],in[vols*zdmn+izf]); } // // Z-backward send // { //int z = 0; int izb = x + iy + it + (nz-1)*nxs*ny; int i5 = x + nxs*y + nxs*ny*t; __attribute__((aligned(_ALIGN_SIZE))) projsch_t a; __mult_z_back_pre_(a,in[vols*zdmn+izb]); __mult_udag_y_(zbh_send[i5],a,(*(gz + izb))); } } } } #pragma omp for collapse(3) nowait for (int z = 0; z < nz; ++z) { for (int y = 0; y < ny; ++y) { for (int x = 0; x < nxs; ++x) { int iz = nxs*ny*z; int iy = nxs*y; // // T-forward send // { //int t = nt-1; int itf = x + iy + iz; int i6 = x + nxs*y + nxs*ny*z; __mult_t_forw_pre_(tfh_send[i6],in[vols*tdmn+itf]); } // // T-backward send // { //int t = 0; int itb = x + iy + iz + (nt-1)*nxs*ny*nz; int i7 = x + nxs*y + nxs*ny*z; __attribute__((aligned(_ALIGN_SIZE))) projsch_t a; __mult_t_back_pre_(a,in[vols*tdmn+itb]); __mult_udag_y_(tbh_send[i7],a,(*(gt + itb))); } } } } #pragma omp barrier } // end of omp parallel _S_MULT_WD_DEO_OUT_SEND_HPC_TOC_; #pragma omp single nowait { if (*idomain == 0) { memcpy(xfh_recv, xfh_send, sizeof(half)*12*ny*nz*nt); } else { xbound_h_start(0); } if (*idomain == 1) { memcpy(xbh_recv, xbh_send, sizeof(half)*12*ny*nz*nt); } else { xbound_h_start(1); } xbound_h_start(2); xbound_h_start(3); xbound_h_start(4); xbound_h_start(5); xbound_h_start(6); xbound_h_start(7); } } //---------------------------------------------------------------------------------------- postprocess mult D for boundary void ddd_out_pos_h_(sch_t * __restrict__ out, const sch_t * __restrict__ in, const int *idomain, float factor) // // Multiply Wilson/Clover operator from odd/even to even/odd domain // // oute = oute + factor Meo ino // or // outo = outo + factor Moe ine // // Note: Deo = -kappa Meo, Doe = -kappa Moe // // out : quark field in an even/odd domain (output) // in : quark field in an odd/even domain (input) // idomain : domain index, 0 for even output, 1 for odd output // factor : a factor for hopping parameter kappa or -kappa // { pgluh_t __restrict__ gx = &gluh[vols*0 + NDIM*vols*(*idomain)]; pgluh_t __restrict__ gy = &gluh[vols*1 + NDIM*vols*(*idomain)]; pgluh_t __restrict__ gz = &gluh[vols*2 + NDIM*vols*(*idomain)]; pgluh_t __restrict__ gt = &gluh[vols*3 + NDIM*vols*(*idomain)]; half hfactor = half(factor); #pragma omp single { xbound_h_wait(0); xbound_h_wait(1); xbound_h_wait(2); xbound_h_wait(3); xbound_h_wait(4); xbound_h_wait(5); xbound_h_wait(6); xbound_h_wait(7); } _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TIC_; #pragma omp parallel for collapse(4) for (int t = 0; t < nt; t++) { for (int z = 0; z < nz; z++) { for (int y = 0; y < ny; y++) { for (int x = 0; x < nxs; x++) { if (x == nxs-1 || y == ny-1 || z == nz-1 || t == nt-1 || x==0 || y == 0 || z == 0 || t == 0 ) { int it = nxs*ny*nz*t; int iz = nxs*ny*z; int iy = nxs*y; int i0 = x + iy + iz + it; sch_t tmp __attribute__((aligned(_ALIGN_SIZE))) ; for(int c = 0; c < 3; c++) { for(int s = 0; s < 4; s++) { for(int ri = 0; ri < 2; ri++) { for(int j = 0; j < VLENS; j++) { tmp.c[c][s][ri][j] = half(0.0f); } } } } // // X-forward // if ( x == nxs-1 ) { _mult_forw_x_recv_; } // // X-backward // if ( x == 0 ) { _mult_back_x_recv_; } // // Y-forward // if ( y == ny-1 ) { _mult_forw_y_recv_; } // // Y-backward // if ( y == 0 ) { _mult_back_y_recv_; } // // Z-forward // if ( z == nz-1 ) { _mult_forw_z_recv_; } // // Z-backward // if ( z == 0 ) { _mult_back_z_recv_; } // // T-forward // if ( t == nt-1 ) { _mult_forw_t_recv_; } // // T-backward // if ( t == 0 ) { _mult_back_t_recv_; } __mult_clvh( tmp.cv, clvh[i0 + vols*(*idomain)].cv); sch_t *outi = out + i0; //#pragma loop norecurrence for (int c = 0; c < 3; c++) { for (int s = 0; s < 4; s++) { for (int j = 0; j < VLENS; j++) { outi->c[c][s][0][j] += tmp.c[c][s][0][j] * hfactor; outi->c[c][s][1][j] += tmp.c[c][s][1][j] * hfactor; } } } } // if edge sites } } } } _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TOC_; #pragma omp single { xbound_h_send_waitall(); } } #endif
RIKEN-LQCD/qws
timing.h
//**************************************************************************************** // // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2018-2020, <NAME> <<EMAIL>> // Copyright (c) 2019-2020, <NAME> <<EMAIL>> // // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer listed // in this license in the documentation and/or other materials // provided with the distribution. // // * Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------------------- // ACKNOWLEDGMENT // // This software has been developed in a co-design working group for the lattice QCD // supported by MEXT's programs for the Development and Improvement for the Next // Generation Ultra High-Speed Computer System, under its Subsidies for Operating the // Specific Advanced Large Research Facilities, and Priority Issue 9 // (Elucidation of the Fundamental Laws and Evolution of the Universe) to be tackled by // using the Supercomputer Fugaku. // //**************************************************************************************** #ifndef TIMI_H #define TIMI_H #include"profiler.h" #ifndef PROF_SELECTIVE #define IF_PROF(A) A #else #define IF_PROF(A) if(prof_flag){A} #ifdef MAIN int prof_flag; #else extern int prof_flag; #endif #endif #ifdef PROF_TARGET # define _TIC_ # define _TOC_ # define _BCG_ITER_TIC_ # define _BCG_ITER_TOC_ # define _BCG_DDS_ITER_TIC_ # define _BCG_DDS_ITER_TOC_ # define _BCG_PRECDDS_TIC_ # define _BCG_PRECDDS_TOC_ # define _BCG_PRECDDS_ITER_TIC_ # define _BCG_PRECDDS_ITER_TOC_ # define _BCG_PRECDDS_ITER_REDUC1_TIC_ # define _BCG_PRECDDS_ITER_REDUC1_TOC_ # define _BCG_PRECDDS_ITER_REDUC2_TIC_ # define _BCG_PRECDDS_ITER_REDUC2_TOC_ # define _BCG_PRECDDS_ITER_REDUC3_TIC_ # define _BCG_PRECDDS_ITER_REDUC3_TOC_ # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC1_TIC_ # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC1_TOC_ # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC2_TIC_ # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC2_TOC_ # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC3_1_TIC_ # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC3_1_TOC_ # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC3_2_TIC_ # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC3_2_TOC_ # define _MCG_ITER_TIC_ # define _MCG_ITER_TOC_ # define _CG_ITER_TIC_ # define _CG_ITER_TOC_ # define _DEO_IN_TIC_ # define _DEO_IN_TOC_ # define _DEE_DEO_IN_TIC_ # define _DEE_DEO_IN_TOC_ # define _DEO_OUT_PRE_TIC_ # define _DEO_OUT_PRE_TOC_ # define _DEE_DEO_OUT_POST_TIC_ # define _DEE_DEO_OUT_POST_TOC_ # define _MTILDE_TIC_ # define _MTILDE_TOC_ # define _PREC_S_TIC_ # define _PREC_S_TOC_ # define _PREC_DDD_S_TIC_ # define _PREC_DDD_S_TOC_ # define _JINV_DDD_IN_S_TIC_ # define _JINV_DDD_IN_S_TOC_ # define _DDD_IN_S_TIC_ # define _DDD_IN_S_TOC_ # define _DDD_OUT_PRE_S_TIC_ # define _DDD_OUT_PRE_S_TOC_ # define _DDD_OUT_POS_S_TIC_ # define _DDD_OUT_POS_S_TOC_ # define _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TIC_ # define _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TOC_ # define _S_MULT_WD_DEO_OUT_SEND_HPC_TIC_ # define _S_MULT_WD_DEO_OUT_SEND_HPC_TOC_ # define _OTHER_CALC_TIC_ # define _OTHER_CALC_TOC_ # define _OVERLAPPED_CALC_TIC_ # define _OVERLAPPED_CALC_TOC_ # define _COMLIB_IRECV_ALL_C_TIC_ # define _COMLIB_IRECV_ALL_C_TOC_ # define _COMLIB_ISEND_ALL_C_TIC_ # define _COMLIB_ISEND_ALL_C_TOC_ # define _COMLIB_SEND_WAIT_ALL_C_TIC_ # define _COMLIB_SEND_WAIT_ALL_C_TOC_ # define TARGET_ALL 1 # define TARGET_JINV 2 # define TARGET_IN 3 # define TARGET_PRE 4 # define TARGET_POS 5 # define TARGET_OTHER 6 # define TARGET_ALL_CALC 7 # define TARGET_OVERLAPPED 8 # define TARGET_SEND 9 # define TARGET_SEND_POST 10 # define TARGET_RECV 11 # define TARGET_REDUC1 12 # define TARGET_REDUC2 13 # define TARGET_REDUC3 14 # if PROF_TARGET == TARGET_ALL # undef _BCG_PRECDDS_ITER_TIC_ # undef _BCG_PRECDDS_ITER_TOC_ # define _BCG_PRECDDS_ITER_TIC_ IF_PROF(PROF_START_SRL("all")) # define _BCG_PRECDDS_ITER_TOC_ IF_PROF(PROF_STOP_SRL("all")) # elif PROF_TARGET == TARGET_JINV # undef _JINV_DDD_IN_S_TIC_ # undef _JINV_DDD_IN_S_TOC_ # define _JINV_DDD_IN_S_TIC_ IF_PROF(PROF_START_SRL("jinv")) # define _JINV_DDD_IN_S_TOC_ IF_PROF(PROF_STOP_SRL("jinv")) # elif PROF_TARGET == TARGET_IN # undef _DDD_IN_S_TIC_ # undef _DDD_IN_S_TOC_ # define _DDD_IN_S_TIC_ IF_PROF(PROF_START_SRL("in")) # define _DDD_IN_S_TOC_ IF_PROF(PROF_STOP_SRL("in")) # elif PROF_TARGET == TARGET_PRE # undef _S_MULT_WD_DEO_OUT_SEND_HPC_TIC_ # undef _S_MULT_WD_DEO_OUT_SEND_HPC_TOC_ # define _S_MULT_WD_DEO_OUT_SEND_HPC_TIC_ IF_PROF(PROF_START_SRL("pre")) # define _S_MULT_WD_DEO_OUT_SEND_HPC_TOC_ IF_PROF(PROF_STOP_SRL("pre")) # elif PROF_TARGET == TARGET_POS # undef _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TIC_ # undef _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TOC_ # define _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TIC_ IF_PROF(PROF_START_SRL("pos")) # define _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TOC_ IF_PROF(PROF_STOP_SRL("pos")) # elif PROF_TARGET == TARGET_OTHER # undef _BCG_PRECDDS_ITER_TIC_ # undef _BCG_PRECDDS_ITER_TOC_ # undef _BCG_PRECDDS_ITER_REDUC1_TIC_ # undef _BCG_PRECDDS_ITER_REDUC1_TOC_ # undef _BCG_PRECDDS_ITER_REDUC2_TIC_ # undef _BCG_PRECDDS_ITER_REDUC2_TOC_ # undef _BCG_PRECDDS_ITER_REDUC3_TIC_ # undef _BCG_PRECDDS_ITER_REDUC3_TOC_ # undef _OTHER_CALC_TIC_ # undef _OTHER_CALC_TOC_ # define _BCG_PRECDDS_ITER_TIC_ IF_PROF(PROF_START("other")) # define _BCG_PRECDDS_ITER_TOC_ IF_PROF(PROF_STOP("other")) # define _BCG_PRECDDS_ITER_REDUC1_TIC_ IF_PROF(PROF_STOP("other")) # define _BCG_PRECDDS_ITER_REDUC1_TOC_ IF_PROF(PROF_START("other")) # define _BCG_PRECDDS_ITER_REDUC2_TIC_ IF_PROF(PROF_STOP("other")) # define _BCG_PRECDDS_ITER_REDUC2_TOC_ IF_PROF(PROF_START("other")) # define _BCG_PRECDDS_ITER_REDUC3_TIC_ IF_PROF(PROF_STOP ("other")) # define _BCG_PRECDDS_ITER_REDUC3_TOC_ IF_PROF(PROF_START("other")) # define _OTHER_CALC_TIC_ IF_PROF(PROF_START_SRL("other")) # define _OTHER_CALC_TOC_ IF_PROF(PROF_STOP_SRL("other")) # elif PROF_TARGET == TARGET_ALL_CALC # undef _BCG_PRECDDS_ITER_TIC_ # undef _BCG_PRECDDS_ITER_TOC_ # undef _BCG_PRECDDS_ITER_REDUC1_TIC_ # undef _BCG_PRECDDS_ITER_REDUC1_TOC_ # undef _BCG_PRECDDS_ITER_REDUC2_TIC_ # undef _BCG_PRECDDS_ITER_REDUC2_TOC_ # undef _BCG_PRECDDS_ITER_REDUC3_TIC_ # undef _BCG_PRECDDS_ITER_REDUC3_TOC_ # undef _S_MULT_WD_DEO_OUT_SEND_HPC_TOC_ # undef _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TIC_ # undef _COMLIB_SEND_WAIT_ALL_C_TIC_ # undef _COMLIB_SEND_WAIT_ALL_C_TOC_ # define _BCG_PRECDDS_ITER_TIC_ IF_PROF(PROF_START("all_calc")) # define _BCG_PRECDDS_ITER_TOC_ IF_PROF(PROF_STOP("all_calc")) # define _BCG_PRECDDS_ITER_REDUC1_TIC_ IF_PROF(PROF_STOP("all_calc")) # define _BCG_PRECDDS_ITER_REDUC1_TOC_ IF_PROF(PROF_START("all_calc")) # define _BCG_PRECDDS_ITER_REDUC2_TIC_ IF_PROF(PROF_STOP("all_calc")) # define _BCG_PRECDDS_ITER_REDUC2_TOC_ IF_PROF(PROF_START("all_calc")) # define _BCG_PRECDDS_ITER_REDUC3_TIC_ IF_PROF(PROF_STOP ("all_calc")) # define _BCG_PRECDDS_ITER_REDUC3_TOC_ IF_PROF(PROF_START("all_calc")) // The regions from _S_MULT_WD_DEO_OUT_SEND_HPC_TOC_ to _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TIC_ // and from _COMLIB_SEND_WAIT_ALL_C_TIC_ to _COMLIB_SEND_WAIT_ALL_C_TOC_ // include communications and caluculations which overlap with the communications, // so it is not counted as calculation time. # define _S_MULT_WD_DEO_OUT_SEND_HPC_TOC_ IF_PROF(PROF_STOP_SRL("all_calc")) # define _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TIC_ IF_PROF(PROF_START_SRL("all_calc")) # define _COMLIB_SEND_WAIT_ALL_C_TIC_ IF_PROF(PROF_STOP_SRL("all_calc")) # define _COMLIB_SEND_WAIT_ALL_C_TOC_ IF_PROF(PROF_START_SRL("all_calc")) # elif PROF_TARGET == TARGET_OVERLAPPED # undef _OVERLAPPED_CALC_TIC_ # undef _OVERLAPPED_CALC_TOC_ # define _OVERLAPPED_CALC_TIC_ IF_PROF(PROF_START_SRL("overlapped")) # define _OVERLAPPED_CALC_TOC_ IF_PROF(PROF_STOP_SRL("overlapped")) # elif PROF_TARGET == TARGET_RECV # undef _COMLIB_IRECV_ALL_C_TIC_ # undef _COMLIB_IRECV_ALL_C_TOC_ # define _COMLIB_IRECV_ALL_C_TIC_ IF_PROF(PROF_START_SRL("comlib_irecv_all_c")) # define _COMLIB_IRECV_ALL_C_TOC_ IF_PROF(PROF_STOP_SRL("comlib_irecv_all_c")) # elif PROF_TARGET == TARGET_SEND # undef _COMLIB_ISEND_ALL_C_TIC_ # undef _COMLIB_ISEND_ALL_C_TOC_ # define _COMLIB_ISEND_ALL_C_TIC_ IF_PROF(PROF_START_SRL("comlib_isend_all_c")) # define _COMLIB_ISEND_ALL_C_TOC_ IF_PROF(PROF_STOP_SRL("comlib_isend_all_c")) # elif PROF_TARGET == TARGET_SEND_POST # undef _COMLIB_SEND_WAIT_ALL_C_TIC_ # undef _COMLIB_SEND_WAIT_ALL_C_TOC_ # define _COMLIB_SEND_WAIT_ALL_C_TIC_ IF_PROF(PROF_START_SRL("comlib_isend_wait_all_c")) # define _COMLIB_SEND_WAIT_ALL_C_TOC_ IF_PROF(PROF_STOP_SRL("comlib_isend_wait_all_c")) # elif PROF_TARGET == TARGET_REDUC1 # undef _BCG_PRECDDS_ITER_REDUC1_TIC_ # undef _BCG_PRECDDS_ITER_REDUC1_TOC_ # define _BCG_PRECDDS_ITER_REDUC1_TIC_ IF_PROF(PROF_START_SRL("bicgstab_precdd_s_iter_reduc1_")) # define _BCG_PRECDDS_ITER_REDUC1_TOC_ IF_PROF(PROF_STOP_SRL("bicgstab_precdd_s_iter_reduc1_")) # elif PROF_TARGET == TARGET_REDUC2 # undef _BCG_PRECDDS_ITER_REDUC2_TIC_ # undef _BCG_PRECDDS_ITER_REDUC2_TOC_ # define _BCG_PRECDDS_ITER_REDUC2_TIC_ IF_PROF(PROF_START_SRL("bicgstab_precdd_s_iter_reduc2_")) # define _BCG_PRECDDS_ITER_REDUC2_TOC_ IF_PROF(PROF_STOP_SRL("bicgstab_precdd_s_iter_reduc2_")) # elif PROF_TARGET == TARGET_REDUC3 # undef _BCG_PRECDDS_ITER_REDUC3_TIC_ # undef _BCG_PRECDDS_ITER_REDUC3_TOC_ # define _BCG_PRECDDS_ITER_REDUC3_TIC_ IF_PROF(PROF_START_SRL("bicgstab_precdd_s_iter_reduc3_")) # define _BCG_PRECDDS_ITER_REDUC3_TOC_ IF_PROF(PROF_STOP_SRL("bicgstab_precdd_s_iter_reduc3_")) # else # error "invalid PROF_TARGET" # endif #else # define _TIC_ IF_PROF(PROF_START(__func__)) # define _TOC_ IF_PROF( PROF_STOP(__func__)) # define _BCG_ITER_TIC_ IF_PROF(PROF_START("bicgstab_iter_")) # define _BCG_ITER_TOC_ IF_PROF( PROF_STOP("bicgstab_iter_")) # define _BCG_DDS_ITER_TIC_ IF_PROF(PROF_START("bicgstab_dd_s_iter_")) # define _BCG_DDS_ITER_TOC_ IF_PROF( PROF_STOP("bicgstab_dd_s_iter_")) # define _BCG_PRECDDS_TIC_ IF_PROF(PROF_START("bicgstab_precdd_s_")) # define _BCG_PRECDDS_TOC_ IF_PROF( PROF_STOP("bicgstab_precdd_s_")) # define _BCG_PRECDDS_ITER_TIC_ IF_PROF(PROF_START("bicgstab_precdd_s_iter_")) # define _BCG_PRECDDS_ITER_TOC_ IF_PROF( PROF_STOP("bicgstab_precdd_s_iter_")) # define _BCG_PRECDDS_ITER_REDUC1_TIC_ IF_PROF(PROF_START("bicgstab_precdd_s_iter_reduc1_")) # define _BCG_PRECDDS_ITER_REDUC1_TOC_ IF_PROF( PROF_STOP("bicgstab_precdd_s_iter_reduc1_")) # define _BCG_PRECDDS_ITER_REDUC2_TIC_ IF_PROF(PROF_START("bicgstab_precdd_s_iter_reduc2_")) # define _BCG_PRECDDS_ITER_REDUC2_TOC_ IF_PROF( PROF_STOP("bicgstab_precdd_s_iter_reduc2_")) # define _BCG_PRECDDS_ITER_REDUC3_TIC_ IF_PROF(PROF_START("bicgstab_precdd_s_iter_reduc3_")) # define _BCG_PRECDDS_ITER_REDUC3_TOC_ IF_PROF( PROF_STOP("bicgstab_precdd_s_iter_reduc3_")) # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC1_TIC_ IF_PROF(PROF_START("bicgstab_precdd_s_iter_bar_reduc1_")) # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC1_TOC_ IF_PROF( PROF_STOP("bicgstab_precdd_s_iter_bar_reduc1_")) # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC2_TIC_ IF_PROF(PROF_START("bicgstab_precdd_s_iter_bar_reduc2_")) # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC2_TOC_ IF_PROF( PROF_STOP("bicgstab_precdd_s_iter_bar_reduc2_")) # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC3_1_TIC_ IF_PROF(PROF_START("bicgstab_precdd_s_iter_bar_reduc3_1_")) # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC3_1_TOC_ IF_PROF( PROF_STOP("bicgstab_precdd_s_iter_bar_reduc3_1_")) # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC3_2_TIC_ IF_PROF(PROF_START("bicgstab_precdd_s_iter_bar_reduc3_2_")) # define _BCG_PRECDDS_ITER_BARRIER_BEFORE_REDUC3_2_TOC_ IF_PROF( PROF_STOP("bicgstab_precdd_s_iter_bar_reduc3_2_")) # define _MCG_ITER_TIC_ IF_PROF(PROF_START("mcg_iter_")) # define _MCG_ITER_TOC_ IF_PROF( PROF_STOP("mcg_iter_")) # define _CG_ITER_TIC_ IF_PROF(PROF_START("cg_iter_")) # define _CG_ITER_TOC_ IF_PROF( PROF_STOP("cg_iter_")) # define _DEO_IN_TIC_ IF_PROF(PROF_START("deo_in_")) # define _DEO_IN_TOC_ IF_PROF( PROF_STOP("deo_in_")) # define _DEE_DEO_IN_TIC_ IF_PROF(PROF_START("dee_deo_in_")) # define _DEE_DEO_IN_TOC_ IF_PROF( PROF_STOP("dee_deo_in_")) # define _DEO_OUT_PRE_TIC_ IF_PROF(PROF_START("deo_out_pre_")) # define _DEO_OUT_PRE_TOC_ IF_PROF( PROF_STOP("deo_out_pre_")) # define _DEE_DEO_OUT_POST_TIC_ IF_PROF(PROF_START("dee_deo_out_post_")) # define _DEE_DEO_OUT_POST_TOC_ IF_PROF( PROF_STOP("dee_deo_out_post_")) # define _MTILDE_TIC_ IF_PROF(PROF_START("mtilde")) # define _MTILDE_TOC_ IF_PROF( PROF_STOP("mtilde")) # define _PREC_S_TIC_ IF_PROF(PROF_START("prec_s_")) # define _PREC_S_TOC_ IF_PROF( PROF_STOP("prec_s_")) # define _PREC_DDD_S_TIC_ IF_PROF(PROF_START("prec_ddd_s_")) # define _PREC_DDD_S_TOC_ IF_PROF( PROF_STOP("prec_ddd_s_")) # define _DDD_IN_S_TIC_ IF_PROF(PROF_START("ddd_in_s_")) # define _DDD_IN_S_TOC_ IF_PROF( PROF_STOP("ddd_in_s_")) # define _JINV_DDD_IN_S_TIC_ IF_PROF(PROF_START_SRL("jinv_ddd_in_s_")) # define _JINV_DDD_IN_S_TOC_ IF_PROF( PROF_STOP_SRL("jinv_ddd_in_s_")) # define _DDD_OUT_PRE_S_TIC_ IF_PROF(PROF_START("ddd_out_pre_s_")) # define _DDD_OUT_PRE_S_TOC_ IF_PROF( PROF_STOP("ddd_out_pre_s_")) # define _DDD_OUT_POS_S_TIC_ IF_PROF(PROF_START("ddd_out_pos_s_")) # define _DDD_OUT_POS_S_TOC_ IF_PROF( PROF_STOP("ddd_out_pos_s_")) # define _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TIC_ IF_PROF(PROF_START_SRL("s_mult_wd_deo_out_recv_hpc_calc_")) # define _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TOC_ IF_PROF( PROF_STOP_SRL("s_mult_wd_deo_out_recv_hpc_calc_")) # define _S_MULT_WD_DEO_OUT_SEND_HPC_TIC_ IF_PROF(PROF_START_SRL("s_mult_wd_deo_out_send_hpc_")) # define _S_MULT_WD_DEO_OUT_SEND_HPC_TOC_ IF_PROF( PROF_STOP_SRL("s_mult_wd_deo_out_send_hpc_")) # define _OTHER_CALC_TIC_ # define _OTHER_CALC_TOC_ # define _OVERLAPPED_CALC_TIC_ # define _OVERLAPPED_CALC_TOC_ # define _COMLIB_IRECV_ALL_C_TIC_ # define _COMLIB_IRECV_ALL_C_TOC_ # define _COMLIB_ISEND_ALL_C_TIC_ # define _COMLIB_ISEND_ALL_C_TOC_ # define _COMLIB_SEND_WAIT_ALL_C_TIC_ # define _COMLIB_SEND_WAIT_ALL_C_TOC_ #endif #endif
RIKEN-LQCD/qws
rdma_comlib_2buf.h
<reponame>RIKEN-LQCD/qws //**************************************************************************************** // // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2018-2020, <NAME> <<EMAIL>> // Copyright (c) 2019-2020, <NAME> <<EMAIL>> // // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer listed // in this license in the documentation and/or other materials // provided with the distribution. // // * Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------------------- // ACKNOWLEDGMENT // // This software has been developed in a co-design working group for the lattice QCD // supported by MEXT's programs for the Development and Improvement for the Next // Generation Ultra High-Speed Computer System, under its Subsidies for Operating the // Specific Advanced Large Research Facilities, and Priority Issue 9 // (Elucidation of the Fundamental Laws and Evolution of the Universe) to be tackled by // using the Supercomputer Fugaku. // //**************************************************************************************** /* rdma commucation with double buffering: wrapper functions for rdma communication <NAME> <EMAIL> 2018 Dec. 17, 2019 Feb. 6 Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty. Usage: void rdma_comlib_2buf::comlib_init() void rdma_comlib_2buf::comlib_finalize() initialize/finalize the rdma communication NOTE: Re-initialization does not work in this FJMPI RDMA implementation. member functions: void init(const int tni_id, const int dst_rank, const int rcv_rank, const size_t size) allocate the buffer tni_id: specifies the Tofu Netowork Interface (TNI), [0...5] dst_rank: "target" rank for the 1-to-1 communication rcv_rank: rank of which "target" is this rank size: buffer size in byte void finalize() deallocate the buffer void* sbuff() retunrs pointer to the send buffer void* rbuff() recieve buffer with the current parity void irecv() asynchronous RDMA get the data from reciev buffer with the current parity void isendrecv() asynchronous RDMA send/receive with the current parity void isend_check() check and wait for RDMA isend finishes void irecv_check() check and wait for RDMA irecieve finishes void irecv_ok() set ok status to the receive buffer with the current parity void reset_comm() clear the has_started flag set by isendrecv(), in order to supress *_check() void flip_parity() flip the parity for the buffering int get_parity() return the parity static void swap_vcq_for_sending(rdma_comlib_2buf &buf1, rdma_comlib_2buf &buf2) swap the interanl vcqs used in sending. suppose that before the swap: vcq1(= vcq in buf1) sends to, e.g., +A and recieves from -A. vcq2(= vcq in buf2) sends to, e.g., -A and recieves from +A. after the swap vcq1 sends to -A and recieves from -A (now communicates with only -A) vcq2 sends to +A and recieves from +A (now communicates with only +A) void excahge_rdma_comlib_targets(rdma_comlib_2buf &buf1, rdma_comlib_2buf &buf2) [deprecated] swap the targets to send. If buf1 and buf2 send data to the opposite directions to each other, out-going and in-coming trafic to/from the same process become to share the vcq (and TNI) // interface to rankmap static int set_rankmap(int dim) prepare rankmap and its internal id. (in) dim: dimension of the system, [2,4] static int get_rank_map(int *rank_coord, int *neighbor_ranks, int *rank_size) obtain the prepared the rankmap (out) rank_coord: 2 or 4 dim array to specify the logical rank cooridanate (out) neighbor_ranks: 4 or 8 dim array to spedcify the logical neghbors. Directions are [+x, -x, +y, -y,...] (out) rank_size: logical size of 2 or 4 dim ranks. */ #ifndef RDMA_COMLIB_2BUF_H #define RDMA_COMLIB_2BUF_H #include <stdlib.h> #include <mpi.h> //extern "C" { //#include "rdma_utofu_comlib.h" //} #define RDMA_2BUF_USE_SHARED_COMMUNICATOR #ifdef _UTOFU_RDMA //extern "C" { //#include "rdma_utofu_comlib.h" //} // data type defined in the rdma_utofu_comlib.h typedef struct{ volatile int *sbuff; volatile int *rbuff; // char dummy[96]; // the size of dummy is environment dependent char dummy[128]; // the size of dummy is environment dependent } rdma_data_t; // interface to call functions in rdma_utofu_comlib.c extern "C" { void rdma_comlib_init(void); void rdma_comlib_finalize(void); void rdma_comlib_new_ext(rdma_data_t *id, const int *nic_id, const int *dst_rank, const int *rcv_rank, const size_t *size, const int *has_ext); void rdma_comlib_delete_ext(rdma_data_t *id, const int *has_ext); void rdma_comlib_new_duplicate(rdma_data_t *id, const rdma_data_t *id_org, const size_t *size, const int *has_external); // new communicataor with the same vcq void rdma_comlib_exchange_targets(rdma_data_t *id1, rdma_data_t *id2); void rdma_comlib_swap_vcq_for_sending(rdma_data_t *id1, rdma_data_t *id2); void rdma_comlib_isendrecv(rdma_data_t *id); void rdma_comlib_isend_check(rdma_data_t *id); void get_rdma_comlib_isend_finish_tag(int *nicid, int *tag); void rdma_comlib_irecv(rdma_data_t *id); void rdma_comlib_irecv_check(rdma_data_t *id); void rdma_comlib_irecv_ok(rdma_data_t *id); void rdma_comlib_clear_mrq(rdma_data_t *id); int rdma_comlib_get_ssize(const rdma_data_t *id); #include "rankmap_lib.h" } namespace { void rdma_comlib_new_2buf_wrapper(rdma_data_t *id, const int nic_id, const int dst_rank, const int rcv_rank, const size_t size, const int has_ext){ #ifdef RDMA_2BUF_USE_SHARED_COMMUNICATOR rdma_comlib_new_ext(&id[0], &nic_id, &dst_rank, &rcv_rank, &size, &has_ext); rdma_comlib_new_duplicate(&id[1], &id[0], &size, &has_ext); #else rdma_comlib_new_ext(&id[0], &nic_id, &dst_rank, &rcv_rank, &size, &has_ext); rdma_comlib_new_ext(&id[1], &nic_id, &dst_rank, &rcv_rank, &size, &has_ext); #endif } } #else //extern "C" { //#include "rdma_comlib.h" //} typedef struct{ volatile int *sbuff; volatile int *rbuff; char dummy[104]; // the size of dummy is environment dependent } rdma_data_t; // interface to call functions in rdma_comlib.c extern "C" { void rdma_comlib_init(void); void rdma_comlib_finalize(void); void rdma_comlib_new_ext(rdma_data_t *id, const int *nic_id, const int *dst_rank, const size_t *size, const int *has_ext); void rdma_comlib_delete_ext(rdma_data_t *id, const int *has_ext); void rdma_comlib_isendrecv(rdma_data_t *id); void rdma_comlib_isend_check(rdma_data_t *id); void get_rdma_comlib_isend_finish_tag(int *nicid, int *tag); void rdma_comlib_irecv(rdma_data_t *id); void rdma_comlib_irecv_check(rdma_data_t *id); void rdma_comlib_irecv_ok(rdma_data_t *id); int rdma_comlib_get_ssize(const rdma_data_t *id); } namespace { void rdma_comlib_clear_mrq(rdma_data_t* id) {} void rdma_comlib_new_ext_wrapper(rdma_data_t *id, const int nic_id, const int dst_rank, const int rcv_rank, const size_t size, const int has_ext){ rdma_comlib_new_ext(id, &nic_id, &dst_rank, &size, &has_ext); } } #endif class rdma_comlib_2buf{ public: rdma_comlib_2buf(): m_parity(0), m_is_allocated(false) { } ~rdma_comlib_2buf() { finalize(); // delete the allocated buffers } // wrapper to rdma_comlib: init/finalize static void comlib_init() { rdma_comlib_init(); } static void comlib_finalize(void) { rdma_comlib_finalize(); } // todo: separate rank map/tni assignment to indepedent class static int set_rankmap(int dim){ int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); if(dim==4) { m_rankmap_id=rankmap_lib_set_rankmap4d(); } else { fprintf(stderr, "err in making rankmap: unkown dim = %d\n",dim); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } if(m_rankmap_id<0){ if(myrank==0){ fprintf(stderr, "WARNING: err in making rankmap, using the default map.\n"); } } return m_rankmap_id; } static int get_rank_map(int *rank_coord, int *neighbor_ranks, int *rank_size){ //fprintf(stderr, "get_neighbor_ranks: m_rankmap_id=%d\n",m_rankmap_id); if(m_rankmap_id>=0) { rankmap_lib_get_rankmap(rank_coord, neighbor_ranks, rank_size); } return m_rankmap_id; } static void get_tni_ids(int *tni_ids, int m_rankmap_id){ rankmap_lib_get_tni_list(tni_ids, &m_rankmap_id); } static void swap_vcq_for_sending(rdma_comlib_2buf &buf1, rdma_comlib_2buf &buf2){ buf1.swap_vcq_for_sending(buf2); }; // wapper to rdma_comlib: new/delete void init(const int tni_id, const int dst_rank, const int rcv_rank, const size_t size); void finalize(); void exchange_targets(rdma_comlib_2buf &buf2){ rdma_comlib_exchange_targets(&m_rdma_data[0], &(buf2.m_rdma_data[0])); rdma_comlib_exchange_targets(&m_rdma_data[1], &(buf2.m_rdma_data[1])); } void swap_vcq_for_sending(rdma_comlib_2buf &buf2){ rdma_comlib_swap_vcq_for_sending(&m_rdma_data[0], &(buf2.m_rdma_data[0])); rdma_comlib_swap_vcq_for_sending(&m_rdma_data[1], &(buf2.m_rdma_data[1])); } // accesser to the buffers void* sbuff() const { return (void*) m_rdma_data[m_parity].sbuff; } void* rbuff() const { return (void*) m_rdma_data[m_parity].rbuff; } // wrapper to rdma_comlib, cont'd void irecv() { rdma_comlib_irecv( &m_rdma_data[m_parity] ); } void isendrecv() { rdma_comlib_isendrecv( &m_rdma_data[m_parity] ); m_has_started[m_parity] = true; } void isend_check() { if(m_has_started[m_parity]){ rdma_comlib_isend_check( &m_rdma_data[m_parity] ); } } void irecv_check() { // poll and clean mrq for the previous communication // this is needed to avoid flooding the mrq rdma_comlib_clear_mrq( &m_rdma_data[1-m_parity] ); // wait for the recv buffer is ready rdma_comlib_irecv_check( &m_rdma_data[m_parity] ); } void irecv_ok() { rdma_comlib_irecv_ok( &m_rdma_data[m_parity] ); } void reset_comm() { m_has_started[m_parity]=false; } // parity for the double buffering void flip_parity() { m_parity = 1-m_parity; } int get_parity() const { return m_parity; } private: volatile int m_parity; volatile bool m_has_started[2]; bool m_is_allocated; rdma_data_t m_rdma_data[2]; private: volatile static int m_rankmap_id; }; #endif
RIKEN-LQCD/qws
get_tofu_coord_common.c
//**************************************************************************************** // // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2018-2020, <NAME> <<EMAIL>> // Copyright (c) 2019-2020, <NAME> <<EMAIL>> // // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer listed // in this license in the documentation and/or other materials // provided with the distribution. // // * Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------------------- // ACKNOWLEDGMENT // // This software has been developed in a co-design working group for the lattice QCD // supported by MEXT's programs for the Development and Improvement for the Next // Generation Ultra High-Speed Computer System, under its Subsidies for Operating the // Specific Advanced Large Research Facilities, and Priority Issue 9 // (Elucidation of the Fundamental Laws and Evolution of the Universe) to be tackled by // using the Supercomputer Fugaku. // //**************************************************************************************** /* rank map for 4-dim system */ #include "rankmap_list.h" #include "get_tofu_coord_common.h" #include <stdint.h> #include <stdio.h> extern FILE *para_outputfile; /* helper functions */ void get_relative_coords(int *rcoords, int *size, const uint8_t *my_coords, const uint8_t *coords_org, const uint8_t *coords_size, const uint8_t *coords_min, const uint8_t *coords_max){ for(int i=0; i<6; i++){ rcoords[i] = my_coords[i] - coords_org[i]; if( (i == DirX_ || i == DirZ_ || i == DirB_) && (my_coords[i] < coords_org[i]) ){ // using torus rcoords[i] = (coords_max[i] + 1 + my_coords[i] - coords_min[i]) - coords_org[i]; } size[i]=coords_size[i]; } } void to_absolute_coords(uint8_t (*neighbor_coords)[6], const uint8_t *coords_org, const uint8_t *coords_size, const uint8_t *coords_min, const uint8_t *coords_max){ for(int dir=0; dir <4; dir++){ for(int i=0; i<6; i++){ neighbor_coords[dir][i]+=coords_org[i]; if( (i == DirX_ || i == DirZ_ || i == DirB_) && (neighbor_coords[dir][i]>coords_max[i]) ){ // using the torus neighbor_coords[dir][i]-=(coords_max[i]+1); neighbor_coords[dir][i]+=coords_min[i]; } } } } int node_coords_is_ok(int myrank, const int *rcoords, int node_x, int node_y, int node_z, int node_t){ if(node_x<0){ fprintf(stderr, "rank %d: cannot happen: no node_x is found: rcoords=%d %d %d %d %d %d\n", myrank, rcoords[0],rcoords[1], rcoords[2], rcoords[3], rcoords[4], rcoords[5]); return 0; } if(node_y<0){ fprintf(stderr, "rank %d: cannot happen: no node_y is found: rcoords=%d %d %d %d %d %d\n", myrank, rcoords[0],rcoords[1], rcoords[2], rcoords[3], rcoords[4], rcoords[5]); return 0; } if(node_z<0){ fprintf(stderr, "rank %d: cannot happen: no node_z is found: rcoords=%d %d %d %d %d %d\n", myrank, rcoords[0],rcoords[1], rcoords[2], rcoords[3], rcoords[4], rcoords[5]); return 0; } if(node_t<0){ fprintf(stderr, "rank %d: cannot happen: no node_t is found: rcoords=%d %d %d %d %d %d\n", myrank, rcoords[0],rcoords[1], rcoords[2], rcoords[3], rcoords[4], rcoords[5]); return 0; } return 1; } int lookup1(int rcoord1, const int *T1, int size){ int node=-1; for(int i=0; i<size; i++){ if(rcoord1 == T1[i]){ node=i; break; } } return node; } int lookup2(int rcoord1, const int *T1, int rcoord2, const int *T2, int size){ int node=-1; for(int i=0; i<size; i++){ if(rcoord1 == T1[i] && rcoord2 == T2[i] ){ node=i; break; } } return node; } void dump_coords(int myrank, const uint8_t *my_coords, const uint8_t (*positive_neighbor_coords)[6], const uint8_t (*negative_neighbor_coords)[6]){ #ifdef _DEBUG_TOFU_COORD for(int dir=0; dir <4; dir++){ const uint8_t *p=positive_neighbor_coords[dir]; const uint8_t *n=negative_neighbor_coords[dir]; const uint8_t *m=my_coords; fprintf(stderr, " rank=%d [%d %d %d %d %d %d], dir=%d: positive_ncoords = %d %d %d %d %d %d, nagative_ncoords = %d %d %d %d %d %d\n", myrank, m[0], m[1], m[2], m[3], m[4], m[5], dir, p[0],p[1],p[2],p[3],p[4],p[5], n[0],n[1],n[2],n[3],n[4],n[5]); } #endif } void print_coords_and_tni(int myrank, const uint8_t *my_coords, const int *rank_coord, const uint8_t (*positive_neighbor_coords)[6], const uint8_t (*negative_neighbor_coords)[6], const int *tni_list){ if(para_outputfile){ fprintf(para_outputfile, "rank=%d\n", myrank); fprintf(para_outputfile, " Logical coordinate: %d %d %d %d\n", rank_coord[0], rank_coord[1], rank_coord[2], rank_coord[3]); fprintf(para_outputfile, " Tofu coordinate: %2d %2d %2d %2d %2d %2d\n", my_coords[0], my_coords[1], my_coords[2], my_coords[3], my_coords[4], my_coords[5]); for(int dir=0; dir <4; dir++){ const uint8_t *p=positive_neighbor_coords[dir]; const uint8_t *n=negative_neighbor_coords[dir]; fprintf(para_outputfile, "dir=%d: forward, tofu = %2d %2d %2d %2d %2d %2d , tni = %d\n", dir, p[0],p[1],p[2],p[3],p[4],p[5], tni_list[2*dir]); fprintf(para_outputfile, "dir=%d: backward, tofu = %2d %2d %2d %2d %2d %2d , tni = %d\n", dir, n[0],n[1],n[2],n[3],n[4],n[5], tni_list[2*dir+1]); } fflush(para_outputfile); } } void print_tni(int myrank, const int *rank_size, const int **tni_list_array){ if(myrank==0){ printf("----------------------------\n"); printf("TNI_list\n"); printf(" QX+: "); for(int i=0; i<rank_size[0]; i++) { printf(" %d", tni_list_array[0][i]); } printf("\n"); printf(" QX-: "); for(int i=0; i<rank_size[0]; i++) { printf(" %d", tni_list_array[1][i]); } printf("\n"); printf(" QY+: "); for(int i=0; i<rank_size[1]; i++) { printf(" %d", tni_list_array[2][i]); } printf("\n"); printf(" QY-: "); for(int i=0; i<rank_size[1]; i++) { printf(" %d", tni_list_array[3][i]); } printf("\n"); printf(" QZ+: "); for(int i=0; i<rank_size[2]; i++) { printf(" %d", tni_list_array[4][i]); } printf("\n"); printf(" QZ-: "); for(int i=0; i<rank_size[2]; i++) { printf(" %d", tni_list_array[5][i]); } printf("\n"); printf(" QT+: "); for(int i=0; i<rank_size[3]; i++) { printf(" %d", tni_list_array[6][i]); } printf("\n"); printf(" QT-: "); for(int i=0; i<rank_size[3]; i++) { printf(" %d", tni_list_array[7][i]); } printf("\n"); printf("----------------------------\n"); fflush(stdout); } } void print_tofu_openXYZ(const int myrank, const int **Tmap, const int *Nsize, const uint8_t *coords_size, const int DirX, const int DirY, const int DirZ){ const int *TA=Tmap[0]; const int *TB=Tmap[1]; const int *TC=Tmap[2]; const int *TX=Tmap[3]; const int *TY=Tmap[4]; const int *TZc=Tmap[5]; const int *TZd=Tmap[6]; const int size_x=Nsize[0]; const int size_y=Nsize[1]; const int size_z=Nsize[2]; const int size_t=Nsize[3]; const int DirA=DirA_; const int DirB=DirB_; const int DirC=DirC_; if(myrank==0){ int size[6]={coords_size[0], coords_size[1], coords_size[2], coords_size[3], coords_size[4], coords_size[5]}; printf("tofu size (original): [A,B,C,X,Y,Z]=[%d,%d,%d,%d,%d,%d]\n", size[DirA_],size[DirB_],size[DirC_],size[DirX_],size[DirY_],size[DirZ_]); printf(" rotate: X,Y,Z --> %c,%c,%c\n", tofu_char[DirX], tofu_char[DirY], tofu_char[DirZ]); printf("tofu size (rotated): [A,B,C,X,Y,Z]=[%d,%d,%d,%d,%d,%d]\n", size[DirA],size[DirB],size[DirC],size[DirX],size[DirY],size[DirZ]); printf("----- node coordinates -----\n"); printf("map for x: TA = "); for(int i=0; i<size_x; i++){printf("%3d",TA[i]); } printf("\n"); printf(" TZc = "); for(int i=0; i<size_x; i++){printf("%3d",TZc[i]); } printf("\n"); printf("map for y: TC = "); for(int i=0; i<size_y; i++){printf("%3d",TC[i]); } printf("\n"); printf(" TZd = "); for(int i=0; i<size_y; i++){printf("%3d",TZd[i]); } printf("\n"); printf("map for z: TB = "); for(int i=0; i<size_z; i++){printf("%3d",TB[i]); } printf("\n"); printf("map for t: TX = "); for(int i=0; i<size_t; i++){printf("%3d",TX[i]); } printf("\n"); printf(" TY = "); for(int i=0; i<size_t; i++){printf("%3d",TY[i]); } printf("\n"); printf("inner node size: 1 2 2 1\n"); printf("----------------------------\n"); fflush(0); } } int set_neighbors(const int myrank, const uint8_t *my_coords, const uint8_t *coords_org, const uint8_t *coords_size, const uint8_t *coords_min, const uint8_t *coords_max, int *rank_coord, int *rank_size, uint8_t (*positive_neighbor_coords)[6], int *pos_rank_in_node, uint8_t (*negative_neighbor_coords)[6], int *neg_rank_in_node, const int *Dir, const int **Tmap, const int *Nsize){ // no need to rotate coords_org, coords_size, coords_min, coords_max // but need to rotate (i.e, DirX and DirB might be flipped) positive_neighbor_coords and negative_neighbor_coords const int proc_per_node=4; const int pny_in_node=2; const int pnz_in_node=2; const int *TA=Tmap[0]; const int *TB=Tmap[1]; const int *TC=Tmap[2]; const int *TX=Tmap[3]; const int *TY=Tmap[4]; const int *TZc=Tmap[5]; const int *TZd=Tmap[6]; const int size_x=Nsize[0]; const int size_y=Nsize[1]; const int size_z=Nsize[2]; const int size_t=Nsize[3]; const int DirA=Dir[0]; const int DirB=Dir[1]; const int DirC=Dir[2]; const int DirX=Dir[3]; const int DirY=Dir[4]; const int DirZ=Dir[5]; /////////////////////////////////////////////////////////////////// // // find the 4d rank coordiante of this rank // // rank_in_node: // ^ QZ // | 2 3 // | 0 1 // ---------> QY // 2x2 in each node int rank_in_node=myrank % proc_per_node; int py=rank_in_node%pny_in_node; int pz=rank_in_node/pny_in_node; // rank size in each direction rank_size[0] = size_x; rank_size[1] = pny_in_node*size_y; rank_size[2] = pnz_in_node*size_z; rank_size[3] = size_t; /////////////////////////////////////////////////////////////////// // // move to the relative tofu coordiantes // int rcoords[6]; // relative tofu coordinates int size[6]; // tofu size get_relative_coords(rcoords, size, my_coords, coords_org, coords_size, coords_min, coords_max); // divide Tz into continuous and discrete int rcoords_Zc=rcoords[DirZ]%3; // continuous int rcoords_Zd=rcoords[DirZ]/3; // discrete // look up the node coordinate int node_x=lookup2(rcoords[DirA], TA, rcoords_Zc, TZc, size_x); int node_y=lookup2(rcoords[DirC], TC, rcoords_Zd, TZd, size_y); int node_z=lookup1(rcoords[DirX], TX, size_z); int node_t=lookup2(rcoords[DirB], TB, rcoords[DirY], TY, size_t); if(!node_coords_is_ok(myrank, rcoords, node_x, node_y, node_z, node_t)){ return RANKMAP_NODE_NOT_FOUND; } // logical coordinate rank_coord[0]=node_x; rank_coord[1]=2 * node_y + py; rank_coord[2]=2 * node_z + pz; rank_coord[3]=node_t; /////////////////////////////////////////////////////////////////// // // neighbors // for(int i=0; i<6; i++){ for(int dir=0; dir<4; dir++){ positive_neighbor_coords[dir][i]=rcoords[i]; negative_neighbor_coords[dir][i]=rcoords[i]; } } // // x-direction // int dir=0; int xf=(rank_coord[dir]+1) % rank_size[dir]; int xb=(rank_coord[dir]-1+rank_size[dir]) % rank_size[dir]; positive_neighbor_coords[dir][DirA]=TA[xf]; positive_neighbor_coords[dir][DirZ]=3*rcoords_Zd + TZc[xf]; negative_neighbor_coords[dir][DirA]=TA[xb]; negative_neighbor_coords[dir][DirZ]=3*rcoords_Zd + TZc[xb]; pos_rank_in_node[dir]=rank_in_node; neg_rank_in_node[dir]=rank_in_node; // // y-direction : has inner node ranks // dir=1; int yf=(rank_coord[dir]+1) % rank_size[dir]; int yb=(rank_coord[dir]-1+rank_size[dir]) % rank_size[dir]; int pyf=yf % pny_in_node; int pyb=yb % pny_in_node; yf/=pny_in_node; yb/=pny_in_node; positive_neighbor_coords[dir][DirC]=TC[yf]; positive_neighbor_coords[dir][DirZ]=3*TZd[yf] + rcoords_Zc; negative_neighbor_coords[dir][DirC]=TC[yb]; negative_neighbor_coords[dir][DirZ]=3*TZd[yb] + rcoords_Zc; pos_rank_in_node[dir] = pyf + pz*pny_in_node; neg_rank_in_node[dir] = pyb + pz*pny_in_node; // // z-direction : has inner node ranks // dir=2; int zf=(rank_coord[dir]+1) % rank_size[dir]; int zb=(rank_coord[dir]-1+rank_size[dir]) % rank_size[dir]; int pzf=zf % pnz_in_node; int pzb=zb % pnz_in_node; zf/=pnz_in_node; zb/=pnz_in_node; positive_neighbor_coords[dir][DirX]=TX[zf]; negative_neighbor_coords[dir][DirX]=TX[zb]; pos_rank_in_node[dir] = py + pzf*pny_in_node; neg_rank_in_node[dir] = py + pzb*pny_in_node; // // t-direction // dir=3; int tf=(rank_coord[dir]+1) % size_t; int tb=(rank_coord[dir]-1+size_t) % size_t; positive_neighbor_coords[dir][DirB]=TB[tf]; positive_neighbor_coords[dir][DirY]=TY[tf]; negative_neighbor_coords[dir][DirB]=TB[tb]; negative_neighbor_coords[dir][DirY]=TY[tb]; pos_rank_in_node[dir]=rank_in_node; neg_rank_in_node[dir]=rank_in_node; /////////////////////////////////////////////////////////////////// // // back to the absolute tofu coordiantes // to_absolute_coords(positive_neighbor_coords, coords_org, coords_size, coords_min, coords_max); to_absolute_coords(negative_neighbor_coords, coords_org, coords_size, coords_min, coords_max); return 1; } void print_tofu(const int myrank, const int *Dir, const int **Tmap, const int *Nsize, const uint8_t *coords_size){ // no need to rotate coords_size const int size_x=Nsize[0]; const int size_y=Nsize[1]; const int size_z=Nsize[2]; const int size_t=Nsize[3]; const int DirA=DirA_; const int DirC=DirC_; const int DirB=DirB_; if(Dir[3] == DirB_){ // shuriked map: TX and TB are flipped const int *TA=Tmap[0]; const int *TX=Tmap[1]; // not TB const int *TC=Tmap[2]; const int *TB=Tmap[3]; // not TX const int *TY=Tmap[4]; const int *TZc=Tmap[5]; const int *TZd=Tmap[6]; const int DirX=Dir[1]; // not Dir[3] const int DirY=Dir[4]; const int DirZ=Dir[5]; if(myrank==0){ int size[6]={coords_size[0], coords_size[1], coords_size[2], coords_size[3], coords_size[4], coords_size[5]}; printf("tofu size (original): [A,B,C,X,Y,Z]=[%d,%d,%d,%d,%d,%d]\n", size[DirA_],size[DirB_],size[DirC_],size[DirX_],size[DirY_],size[DirZ_]); printf(" rotate: X,Y,Z --> %c,%c,%c\n", tofu_char[DirX], tofu_char[DirY], tofu_char[DirZ]); printf("tofu size (rotated): [A,B,C,X,Y,Z]=[%d,%d,%d,%d,%d,%d]\n", size[DirA],size[DirB],size[DirC],size[DirX],size[DirY],size[DirZ]); printf("----- node coordinates -----\n"); printf("map for x: TA = "); for(int i=0; i<size_x; i++){printf("%3d",TA[i]); } printf("\n"); printf(" TZc = "); for(int i=0; i<size_x; i++){printf("%3d",TZc[i]); } printf("\n"); printf("map for y: TC = "); for(int i=0; i<size_y; i++){printf("%3d",TC[i]); } printf("\n"); printf(" TZd = "); for(int i=0; i<size_y; i++){printf("%3d",TZd[i]); } printf("\n"); printf("map for z: TB = "); for(int i=0; i<size_z; i++){printf("%3d",TB[i]); } printf("\n"); printf("map for t: TX = "); for(int i=0; i<size_t; i++){printf("%3d",TX[i]); } printf("\n"); printf(" TY = "); for(int i=0; i<size_t; i++){printf("%3d",TY[i]); } printf("\n"); printf("inner node size: 1 2 2 1\n"); printf("----------------------------\n"); fflush(stdout); } } else { // original map for full system const int *TA=Tmap[0]; const int *TB=Tmap[1]; const int *TC=Tmap[2]; const int *TX=Tmap[3]; const int *TY=Tmap[4]; const int *TZc=Tmap[5]; const int *TZd=Tmap[6]; const int DirX=Dir[3]; const int DirY=Dir[4]; const int DirZ=Dir[5]; if(myrank==0){ int size[6]={coords_size[0], coords_size[1], coords_size[2], coords_size[3], coords_size[4], coords_size[5]}; printf("tofu size (original): [A,B,C,X,Y,Z]=[%d,%d,%d,%d,%d,%d]\n", size[DirA_],size[DirB_],size[DirC_],size[DirX_],size[DirY_],size[DirZ_]); printf(" rotate: X,Y,Z --> %c,%c,%c\n", tofu_char[DirX], tofu_char[DirY], tofu_char[DirZ]); printf("tofu size (rotated): [A,B,C,X,Y,Z]=[%d,%d,%d,%d,%d,%d]\n", size[DirA],size[DirB],size[DirC],size[DirX],size[DirY],size[DirZ]); printf("----- node coordinates -----\n"); printf("map for x: TA = "); for(int i=0; i<size_x; i++){printf("%3d",TA[i]); } printf("\n"); printf(" TZc = "); for(int i=0; i<size_x; i++){printf("%3d",TZc[i]); } printf("\n"); printf("map for y: TC = "); for(int i=0; i<size_y; i++){printf("%3d",TC[i]); } printf("\n"); printf(" TZd = "); for(int i=0; i<size_y; i++){printf("%3d",TZd[i]); } printf("\n"); printf("map for z: TX = "); for(int i=0; i<size_z; i++){printf("%3d",TX[i]); } printf("\n"); printf("map for t: TB = "); for(int i=0; i<size_t; i++){printf("%3d",TB[i]); } printf("\n"); printf(" TY = "); for(int i=0; i<size_t; i++){printf("%3d",TY[i]); } printf("\n"); printf("inner node size: 1 2 2 1\n"); printf("----------------------------\n"); fflush(stdout); } } }
RIKEN-LQCD/qws
rankmap_lib_utofu.c
<gh_stars>1-10 //**************************************************************************************** // // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2015-2020, <NAME> <<EMAIL>> // Copyright (c) 2018-2020, <NAME> <<EMAIL>> // Copyright (c) 2019-2020, <NAME> <<EMAIL>> // // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer listed // in this license in the documentation and/or other materials // provided with the distribution. // // * Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------------------- // ACKNOWLEDGMENT // // This software has been developed in a co-design working group for the lattice QCD // supported by MEXT's programs for the Development and Improvement for the Next // Generation Ultra High-Speed Computer System, under its Subsidies for Operating the // Specific Advanced Large Research Facilities, and Priority Issue 9 // (Elucidation of the Fundamental Laws and Evolution of the Universe) to be tackled by // using the Supercomputer Fugaku. // //**************************************************************************************** #include <stdlib.h> #include <stdio.h> #include <mpi.h> #include <mpi-ext.h> #include <utofu.h> #include <assert.h> // tofu coordinate etc.: up to 4-dim volatile int m_rankmap_lib_neighbor_ranks[8]; volatile int m_rankmap_lib_process_size[4]; volatile int m_rankmap_lib_process_coord[4]; volatile uint8_t m_rankmap_lib_neighbor_tofu[8][6]; volatile uint8_t m_rankmap_lib_mytofu[6]; volatile uint8_t m_rankmap_lib_mytofu_offset[6]; volatile int m_rankmap_lib_myrank_in_node; volatile int m_rankmap_lib_dim; volatile int m_rankmap_lib_neighbor_rank_in_node[8]; volatile int m_rankmap_lib_tni_list[8]; // get_tofu_coord.c int get_tofu_coord_and_tni(uint8_t *my_coords, int *rank_coord, int *rank_size, uint8_t (*positive_neighbor_coords)[6], int *pos_rank_in_node, uint8_t (*negative_neighbor_coords)[6], int *neg_rank_in_node, int *tni_list); //int get_tofu_coord(uint8_t *my_coords, uint8_t *coords_offset, // int *rank_coord, int *rank_size, // uint8_t (*positive_neighbor_coords)[6], int *pos_rank_in_node, // uint8_t (*negative_neighbor_coords)[6], int *neg_rank_in_node, // const int dim); int get_tni_list_default(int *tni, const int myrank, const int *myrank_coords, const int *myrank_size, const int flag); /////////////////////////////////////////////// // // helper private functions // /////////////////////////////////////////////// // // sanity check: is cq_id correct? // void check_cq_id(utofu_vcq_hdl_t *local_vcq_hdl, uint8_t *coords, int cq_id_guess, int comp_id, int tni_id){ int rc; int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); // obtain id for local vcq utofu_vcq_id_t local_vcq_id0; rc=utofu_query_vcq_id(*local_vcq_hdl, &local_vcq_id0); if(UTOFU_SUCCESS != rc){ fprintf(stderr, "rank %d: Failed at utofu_query_vcq_id()! rc=%d\n", myrank, rc); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } // extract information of the current vcq uint8_t coords0[6]; utofu_tni_id_t tni_id0; utofu_cq_id_t cq_id0; uint16_t extra_val0; rc=utofu_query_vcq_info(local_vcq_id0, coords0, &tni_id0, &cq_id0, &extra_val0); if(UTOFU_SUCCESS != rc){ fprintf(stderr, "rank %d: Failed at utofu_query_vcq_info()! rc=%d\n", myrank, rc); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } #ifdef _RANKMAP_DEBUG fprintf(stderr, "rank %d: local_vcq_id=%d, coords=[%d %d %d %d %d %d], tni_id=%d, cq_id=%d, extra_val=%d\n", myrank, local_vcq_id0, coords0[0],coords0[1],coords0[2],coords0[3],coords0[4],coords0[5], tni_id0, cq_id0, extra_val0); #endif // another vcq_id: is this the same as the origianl local_vcq_id0? utofu_vcq_id_t local_vcq_id2; // int cq_id2=3*(m_rdma_comlib_myrank % proc_per_node); // guess rc=utofu_construct_vcq_id(coords, tni_id, cq_id_guess, comp_id, &local_vcq_id2); if(UTOFU_SUCCESS != rc){ fprintf(stderr, "rank %d: Failed at utofu_construct_vcq_id()! rc=%d, coords=%d %d %d %d %d %d\n", myrank, rc, coords[0],coords[1], coords[2], coords[3], coords[4], coords[5]); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } // check if the caclated vcq_id is ok if(local_vcq_id0 != local_vcq_id2){ fprintf(stderr, "rank %d: imporooper vcq_id: local_vcq_id0=%d, local_vcq_id2=%d; cq_id0=%d, cq_id_guess=%d\n", myrank, local_vcq_id0, local_vcq_id2, cq_id0, cq_id_guess); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } } int check_neighbors(){ int err=0; int dim=m_rankmap_lib_dim; int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); uint8_t sbuffer[6], rbuffer[6]; for(int i=0; i<6; i++){ sbuffer[i]=m_rankmap_lib_mytofu[i]; } const uint8_t *sbuf=sbuffer; uint8_t *rbuf=rbuffer; #ifdef _RANKMAP_DEBUG if(dim==2){ fprintf(stderr, "rank %d: neighbors = %d %d %d %d\n", myrank, m_rankmap_lib_neighbor_ranks[0], m_rankmap_lib_neighbor_ranks[1], m_rankmap_lib_neighbor_ranks[2], m_rankmap_lib_neighbor_ranks[3]); } else if (dim==4){ fprintf(stderr, "rank %d: neighbors = %d %d %d %d\n", myrank, m_rankmap_lib_neighbor_ranks[0], m_rankmap_lib_neighbor_ranks[1], m_rankmap_lib_neighbor_ranks[2], m_rankmap_lib_neighbor_ranks[3], m_rankmap_lib_neighbor_ranks[4], m_rankmap_lib_neighbor_ranks[5], m_rankmap_lib_neighbor_ranks[6], m_rankmap_lib_neighbor_ranks[7]); } #endif MPI_Barrier(MPI_COMM_WORLD); for(int dir=0; dir<dim; dir++){ // recieve from the negative direction int srank=m_rankmap_lib_neighbor_ranks[2*dir]; int rrank=m_rankmap_lib_neighbor_ranks[2*dir+1]; int tag=2*dir+1; //fprintf(stderr, "rank %d, dir=%d: negative: srank=%d, rrank=%d, Sendrecv...\n", myrank, dir, srank, rrank); MPI_Sendrecv(sbuf, 6, MPI_UINT8_T, srank, tag, rbuf, 6, MPI_UINT8_T, rrank, tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //fprintf(stderr, "rank %d, dir=%d: negative: srank=%d, rrank=%d, Sendrecv, done...\n", myrank, dir, srank, rrank); const volatile uint8_t *tmp=&m_rankmap_lib_neighbor_tofu[2*dir+1][0]; if( tmp[0] !=rbuf[0] || tmp[1] !=rbuf[1] || tmp[2] !=rbuf[2] || tmp[3] !=rbuf[3] || tmp[4] !=rbuf[4] || tmp[5] !=rbuf[5] ){ fprintf(stderr, "rank %d: bad tofu coordinate for dir=%d: calc= %d %d %d %d %d %d, recv=%d %d %d %d %d %d [from %d]\n", myrank, 2*dir+1, tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],tmp[5], rbuf[0],rbuf[1],rbuf[2],rbuf[3],rbuf[4],rbuf[5], rrank); err=1; } // recieve from the positive direction srank=m_rankmap_lib_neighbor_ranks[2*dir+1]; rrank=m_rankmap_lib_neighbor_ranks[2*dir]; tag=2*dir; //fprintf(stderr, "rank %d, dir=%d: positive: srank=%d, rrank=%d, Sendrecv...\n", myrank, dir, srank, rrank); MPI_Sendrecv(sbuf, 6, MPI_UINT8_T, srank, tag, rbuf, 6, MPI_UINT8_T, rrank, tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); //fprintf(stderr, "rank %d, dir=%d: positive: srank=%d, rrank=%d, Sendrecv, done\n", myrank, dir, srank, rrank); tmp=&m_rankmap_lib_neighbor_tofu[2*dir][0]; if( tmp[0] !=rbuf[0] || tmp[1] !=rbuf[1] || tmp[2] !=rbuf[2] || tmp[3] !=rbuf[3] || tmp[4] !=rbuf[4] || tmp[5] !=rbuf[5] ){ fprintf(stderr, "rank %d: bad tofu coordinate for dir=%d: calc= %d %d %d %d %d %d, recv=%d %d %d %d %d %d [from %d]\n", myrank, 2*dir, tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],tmp[5], rbuf[0],rbuf[1],rbuf[2],rbuf[3],rbuf[4],rbuf[5], rrank); } } return err; } // // obtain rank id of the logical neighbors // void exchange_ranks(uint8_t *my_coords, int *pos_ranks, int *neg_ranks, uint8_t (*pos_coords)[6], const int *pos_rank_in_node, const int dim, const int proc_per_node){ assert(dim<=4); utofu_stadd_t stadd[4]; int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); int rc; // // crealte local vcq // int tmp=myrank % proc_per_node; int comp_id=tmp; // num_cmp_ids is 8 int cq_id=3*tmp; int tni_id=tmp; struct utofu_onesided_caps *onesided_caps; { // obtain available features int rc=utofu_query_onesided_caps(tni_id, &onesided_caps); if(rc != UTOFU_SUCCESS){ fprintf(stderr, "rank %d: Failed at utofu_query_onesided_caps()\n", myrank); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } } assert(comp_id < onesided_caps->num_cmp_ids); utofu_vcq_hdl_t local_vcq_hdl; //unsigned long int vcq_flag=UTOFU_VCQ_FLAG_THREAD_SAFE | UTOFU_VCQ_FLAG_EXCLUSIVE; //unsigned long int vcq_flag=UTOFU_VCQ_FLAG_EXCLUSIVE; unsigned long int vcq_flag=UTOFU_VCQ_FLAG_THREAD_SAFE; //unsigned long int vcq_flag=0UL; rc=utofu_create_vcq_with_cmp_id(tni_id, comp_id, vcq_flag, &local_vcq_hdl ); if(UTOFU_SUCCESS != rc){ fprintf(stderr, "rank %d: Failed at utofu_create_vcq_with_comp_id()! rc=%d\n", myrank, rc); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } // // check if the cq_id reproduces the id for local_vcq_hdl // check_cq_id(&local_vcq_hdl, my_coords, cq_id, comp_id, tni_id); // // regsiter the buffer to stadd: the local rank is written to the buffer // uint32_t *ranks_addr; size_t stag_alignement=onesided_caps->stag_address_alignment; int asize=stag_alignement/sizeof(uint32_t); posix_memalign((void**)&ranks_addr, stag_alignement, dim*stag_alignement); for(int dir=0; dir<dim; dir++){ uint32_t *addr=ranks_addr + dir*asize; addr[0]=myrank; // set the local rank unsigned int stag=dir; unsigned long flag_stadd=0; rc=utofu_reg_mem_with_stag(local_vcq_hdl, addr, 256, stag, flag_stadd, &stadd[dir]); if(UTOFU_SUCCESS != rc){ fprintf(stderr, "rank %d: Failed at utofu_reg_mem_with_stag() for local send buffer! rc=%d\n", myrank, rc); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } #ifdef _RANKMAP_DEBUG fprintf(stderr, "rank %d: dir=%d, stadd=%ul\n", myrank, dir, stadd[dir]); #endif } // make sure that the stadd is registered in the remote MPI_Barrier(MPI_COMM_WORLD); //////////////////////////////////////////////////////////////////////////// // armw swap: // the buffer is specivied with stadd // // local op_value --> remote buffer // remote buffer --> local notice.rmt_val (the value BEFORE overwritten with op_value) // remote edata --> local notice.edata // // swap with posivie logical direction: // before: op_value, buffer = local rank // after: buffer = rank in negative dirction // notice.rmt_val = rank in positive dirction // [edata: direction] // // prepare arwm communcation // void *desc; posix_memalign((void**)&desc, 8, onesided_caps->max_toq_desc_size*dim); // 64=max_toq_desc_size void *this_desc=desc; size_t desc_size=0; for(int dir=0; dir<dim; dir++){ int tmp=pos_rank_in_node[dir] % proc_per_node; int comp_id=tmp; // num_cmp_ids is 8 int cq_id=3*tmp; // this is a guess int tni_id=tmp; unsigned int stag=dir; utofu_vcq_id_t pos_vcq_id; utofu_stadd_t pos_stadd; // calculate remote_vcq_id rc=utofu_construct_vcq_id(pos_coords[dir], tni_id, cq_id, comp_id, &pos_vcq_id); if(UTOFU_SUCCESS != rc){ const uint8_t *c=pos_coords[dir]; fprintf(stderr, "rank %d: Failed at utofu_construct_vcq_id()! rc=%d, dir=%d, pos_coords=%d %d %d %d %d %d\n", myrank, rc, dir, c[0], c[1], c[2], c[3], c[4], c[5]); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } #ifdef _RANKMAP_DEBUG fprintf(stderr, "rank %d: dir=%d, pos_vcq_id=%ul\n", myrank, dir, pos_vcq_id); #endif // calculate remote_stadd rc=utofu_query_stadd(pos_vcq_id, stag, &pos_stadd); if(UTOFU_SUCCESS != rc){ fprintf(stderr, "rank %d: Failed at utofu_querry_stadd()! rc=%d\n", myrank, rc); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } #ifdef _RANKMAP_DEBUG fprintf(stderr, "rank %d: dir=%d, pos_stadd=%ul\n", myrank, dir, pos_stadd); #endif uint32_t op_value=myrank; uint64_t edata=dir; const unsigned long int flag_armw4 = UTOFU_ONESIDED_FLAG_LOCAL_MRQ_NOTICE | UTOFU_ONESIDED_FLAG_STRONG_ORDER; size_t this_desc_size; rc=utofu_prepare_armw4(local_vcq_hdl, pos_vcq_id, UTOFU_ARMW_OP_SWAP, op_value, pos_stadd, edata, flag_armw4, this_desc, &this_desc_size); this_desc=(char*)this_desc+this_desc_size; desc_size+=this_desc_size; } // // excute arwm communication // void *cbdata; while(1){ rc = utofu_post_toq(local_vcq_hdl, desc, desc_size, &cbdata); if(rc != UTOFU_ERR_BUSY) { break; } rc = utofu_poll_tcq(local_vcq_hdl, 0UL, &cbdata); } if(rc != UTOFU_SUCCESS){ fprintf(stderr, "rank %d: Failed at utofu_post_toq()! rc=%d\n", myrank, rc); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } // // poll the data // for(int i=0; i<dim; i++){ struct utofu_mrq_notice notice; // fprintf(stderr, "rank %d: dir=%d, polling mrq...\n", myrank, i); do { rc = utofu_poll_mrq(local_vcq_hdl, 0UL, &notice); } while (rc == UTOFU_ERR_NOT_FOUND); if(rc != UTOFU_SUCCESS){ fprintf(stderr,"rank %d: %s at %d : i=%d, utofu_poll_mrq, ERROR: %d\n", myrank, __FILE__, __LINE__, i, rc); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } else { switch(notice.notice_type){ case UTOFU_MRQ_TYPE_LCL_ARMW: break; // case UTOFU_MRQ_TYPE_LCL_PUT: // break; default: { const char *type_str; type_str="unkown"; if(notice.notice_type == UTOFU_MRQ_TYPE_LCL_GET) {type_str="LCL_GET";} if(notice.notice_type == UTOFU_MRQ_TYPE_RMT_GET) {type_str="RMT_GET";} if(notice.notice_type == UTOFU_MRQ_TYPE_LCL_ARMW) {type_str="LCL_ARMW";} if(notice.notice_type == UTOFU_MRQ_TYPE_RMT_ARMW) {type_str="RMT_ARMW";} fprintf(stderr,"rank %d: %s at %d : utofu_poll_mrq, notice_type=%s\n", myrank, __FILE__, __LINE__, type_str); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } } } //fprintf(stderr, "rank %d: dir=%d, polling mrq, done\n", myrank, i); uint64_t this_dir=notice.edata; uint32_t rank_pos=notice.rmt_value; pos_ranks[this_dir]=rank_pos; } // make sure all the buffers are updated MPI_Barrier(MPI_COMM_WORLD); if(myrank==0){ // fprintf(stderr, "exchange of rank id with neighbors, done.\n"); } // // set the value obtained // for(int dir=0; dir<dim; dir++){ neg_ranks[dir]=ranks_addr[dir*asize]; } // // release the resources // for(int dir=0; dir<dim; dir++){ utofu_dereg_mem(local_vcq_hdl, stadd[dir], 0); } free(ranks_addr); free(desc); utofu_free_vcq(local_vcq_hdl); } // // obtain rank id of the logical neighbors // void exchange_ranks_with_mpi(int *pos_ranks, int *neg_ranks, const int *rank_coord, const int *rank_size, const int dim){ assert(dim<=4); int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); int num_ranks; MPI_Comm_size(MPI_COMM_WORLD, &num_ranks); int *rank_list_send=(int*)malloc(sizeof(int)*num_ranks); int *rank_list =(int*)malloc(sizeof(int)*num_ranks); if(!rank_list_send){ fprintf(stderr, "rank %d: Failed at malloc for rank_list0.\n", myrank); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } if(!rank_list){ fprintf(stderr, "rank %d: Failed at malloc for rank_list0.\n", myrank); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } memset(rank_list_send, 0, sizeof(int)*num_ranks); int myid=0; int stride=1; for(int i=0; i<dim; i++){ myid+=stride*rank_coord[i]; stride*=rank_size[i]; } rank_list_send[myid]=myrank; MPI_Allreduce(rank_list_send, rank_list, num_ranks, MPI_INT, MPI_SUM, MPI_COMM_WORLD); for(int dir=0; dir<dim; dir++){ int pos_id=0; int neg_id=0; int stride=1; for(int i=0; i<dim; i++){ int pos_coord=rank_coord[i]; int neg_coord=rank_coord[i]; if(i==dir){ pos_coord=(rank_coord[i]+1) % rank_size[i]; neg_coord=(rank_coord[i]-1+rank_size[i]) % rank_size[i]; } pos_id+=stride*pos_coord; neg_id+=stride*neg_coord; stride*=rank_size[i]; } pos_ranks[dir]=rank_list[pos_id]; neg_ranks[dir]=rank_list[neg_id]; } free(rank_list_send); free(rank_list); } // // utilities for rankmap and tni assignemnt // void rankmap_lib_get_rankmap(int *myrank_coord, int *neighbors, int *process_size) { for(int i=0; i < m_rankmap_lib_dim; i++){ myrank_coord[i]=m_rankmap_lib_process_coord[i]; neighbors[2*i]=m_rankmap_lib_neighbor_ranks[2*i]; neighbors[2*i+1]=m_rankmap_lib_neighbor_ranks[2*i+1]; process_size[i]=m_rankmap_lib_process_size[i]; } } int rankmap_lib_set_rankmap4d() { static const int dim=4; static const int proc_per_node=4; int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); // fprintf(stderr, "rank %d: rankmap_lib_set_rankmap4d is called\n", myrank); assert(proc_per_node==4); int err=0; m_rankmap_lib_myrank_in_node=myrank % proc_per_node; m_rankmap_lib_dim=dim; // // get tofu coordinate of this and logical neghboring nodes // uint8_t pos_coords[4][6]; // target Tofu coordinate: posivie neighbors int pos_rank_in_node[4]; // rank id in the node: posivie neighbors uint8_t neg_coords[4][6]; // target Tofu coordinate: negative neighbors int neg_rank_in_node[4]; // rank id in the node: negative neighbors uint8_t my_coords[6]; // Tofu coordinate of this rank int rank_coord[4]; // logical rank coordiante int rank_size[4]; // logical rank size int tni_list[8]; int mapid=get_tofu_coord_and_tni(my_coords, rank_coord, rank_size, &pos_coords[0], pos_rank_in_node, &neg_coords[0], neg_rank_in_node, tni_list); if(mapid<0){ //fprintf(stderr, "rank %d: Failed at get_tofu_coord()! err=%d\n", myrank, err); if(myrank==0){ fprintf(stderr, "WARNING: no rank map is found.\n"); } get_tni_list_default(tni_list, myrank, rank_coord, rank_size, mapid); for(int dir2=0; dir2<8; dir2++){m_rankmap_lib_tni_list[dir2]=tni_list[dir2];} return mapid; // MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } if(myrank==0){ printf("rdma_utofu_comlib: 4d rankmap, size = %d x %d x %d x %d\n", rank_size[0], rank_size[1], rank_size[2], rank_size[3]); fflush(stdout); } #ifdef _RANKMAP_DEBUG fprintf(stderr, "rank %d: tofu coord = (%d %d %d %d %d %d):%d, +x:(%d %d %d %d %d %d):%d, +y:(%d %d %d %d %d %d):%d\n", myrank, my_coords[0], my_coords[1], my_coords[2], my_coords[3], my_coords[4], my_coords[5], tmp, pos_coords[0][0], pos_coords[0][1], pos_coords[0][2], pos_coords[0][3], pos_coords[0][4], pos_coords[0][5], rank_in_node[0], pos_coords[1][0], pos_coords[1][1], pos_coords[1][2], pos_coords[1][3], pos_coords[1][4], pos_coords[1][5], rank_in_node[1]); fprintf(stderr, "rank %d: tni_id=%d, cq_id=%d, comp_id=%d\n", myrank, tni_id, cq_id, comp_id); #endif // // get rank id of the logical neghboring process // int pos_ranks[4]; // positive neighbor int neg_ranks[4]; // negative neighbor // exchange_ranks(my_coords, pos_ranks, neg_ranks, // pos_coords, pos_rank_in_node, // dim, proc_per_node); exchange_ranks_with_mpi(pos_ranks, neg_ranks, rank_coord, rank_size, dim); // // set the result to the global variables // for(int i=0; i<6; i++){ m_rankmap_lib_mytofu[i]=my_coords[i]; } for(int i=0; i<8; i++){ for(int j=0; j<6; j++) { m_rankmap_lib_neighbor_tofu[i][j]=99; }} for(int dir=0; dir<dim; dir++){ m_rankmap_lib_process_coord[dir]=rank_coord[dir]; m_rankmap_lib_process_size[dir]=rank_size[dir]; m_rankmap_lib_neighbor_ranks[2*dir ] = pos_ranks[dir]; m_rankmap_lib_neighbor_ranks[2*dir+1] = neg_ranks[dir]; m_rankmap_lib_neighbor_rank_in_node[2*dir ] = pos_ranks[dir] % proc_per_node; m_rankmap_lib_neighbor_rank_in_node[2*dir+1] = neg_ranks[dir] % proc_per_node; m_rankmap_lib_tni_list[2*dir]=tni_list[2*dir]; m_rankmap_lib_tni_list[2*dir+1]=tni_list[2*dir+1]; for(int i=0; i<6; i++){ m_rankmap_lib_neighbor_tofu[2*dir ][i] = pos_coords[dir][i]; m_rankmap_lib_neighbor_tofu[2*dir+1][i] = neg_coords[dir][i]; } // bug? w/o this dumping, m_rankmap_lib_neighbor is not properly updated; // or violating strict aliasing rule (throught accesing slice of array)? // [ to aviod this bug, m_rankmap_lib_neighbor is changed to volatile ] // uint8_t *p=m_rankmap_lib_neighbor_tofu[2*dir ]; // uint8_t *n=m_rankmap_lib_neighbor_tofu[2*dir+1]; // fprintf(stderr, "fuga: I am %d, dir=%d: positive_ncoods = %d %d %d %d %d, negative_ncoords = %d %d %d %d %d %d\n", // myrank, dir, p[0],p[1],p[2],p[3],p[4],p[5], n[0],n[1],n[2],n[3],n[4],n[5]); } #ifdef DUMP_RANKMAP for(int dir=0; dir <dim; dir++){ volatile uint8_t *p=m_rankmap_lib_neighbor_tofu[2*dir ]; volatile uint8_t *n=m_rankmap_lib_neighbor_tofu[2*dir+1]; volatile uint8_t *m=m_rankmap_lib_mytofu; fprintf(stderr, " rankmap: rank=%d [%d %d %d %d %d %d], dir=%d: positive_ncoords = %d %d %d %d %d %d (rank %d), nagative_ncoords = %d %d %d %d %d %d (rank %d)\n", myrank, m[0], m[1], m[2], m[3], m[4], m[5], dir, p[0],p[1],p[2],p[3],p[4],p[5], pos_ranks[dir], n[0],n[1],n[2],n[3],n[4],n[5], neg_ranks[dir]); } #endif if(myrank==0){ fprintf(stderr, "checking neighbor ranks...\n"); } MPI_Barrier(MPI_COMM_WORLD); err=check_neighbors(); if(myrank==0){ fprintf(stderr, "checking neighbor ranks, done: err=%d\n", err); } MPI_Barrier(MPI_COMM_WORLD); if(err){ fprintf(stderr, "rank %d: error at check_neighbors()\n"); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } if(myrank==0){ printf("rdma_utofu_comlib: 4d rankmap is ready: mapid=%d\n", mapid); fflush(stdout); } return mapid; } int rankmap_lib_get_tni_list(int *tni_list, const int *flag){ int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); if(myrank==0){ fprintf(stderr, "rankmap_lib: calling get_tni_list for dim=%d, flag=%d\n", m_rankmap_lib_dim, *flag); } for(int dir2=0; dir2<2*m_rankmap_lib_dim; dir2++){ tni_list[dir2] = m_rankmap_lib_tni_list[dir2]; } return 0; } void rankmap_lib_dump_rankmap(){ int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); volatile int *rank_coord=m_rankmap_lib_process_coord; volatile int *nranks= m_rankmap_lib_neighbor_ranks; if(m_rankmap_lib_dim==2){ fprintf(stderr, "rank %d: (%d,%d) +x:%d -x:%d +y:%d -y:%d\n",myrank, rank_coord[0],rank_coord[1], nranks[0], nranks[1], nranks[2], nranks[3]); } else if(m_rankmap_lib_dim==4){ fprintf(stderr, "rank %d: (%d,%d,%d,%d) +x:%d -x:%d +y:%d -y:%d +z:%d -z:%d +t:%d -t:%d\n",myrank, rank_coord[0],rank_coord[1],rank_coord[2],rank_coord[3], nranks[0],nranks[1], nranks[2],nranks[3], nranks[4],nranks[5], nranks[6],nranks[7]); } } //
caiomcg/OS-SchedulingSimulation
include/FCFS.h
<filename>include/FCFS.h /** * @class FCFS * * @brief First-Come, First-Served algorithm simulation class * * This Class is responsible for receiving a std::vector of Processes * and run the FCFS algorithm over the input. The user can request the * average response time, the average return time and the average wait * time using getters or the toString method. * * @note See Process Class implementation to create the std::vector. * * @author <NAME> <<EMAIL>> */ #ifndef FCFS_H_ #define FCFS_H_ #include <vector> #include <string> #include <sstream> #include <iomanip> #include <iostream> #include "Process.h" class FCFS { private: std::vector<Process> _queue; /// The Process queue that will be executed under the algorithm. int _amountOfProcesses; /// The amount of process on the process queue. double _avgResponse; /// Average response time. double _avgReturn; /// Average return time. double _avgWait; /// Average waiting time. /** * @brief Calculate the average time. * @details Calculate the average time and populate the * double variables so the user can access the resulting * data. */ void calculateAverageTime(); public: /** * @brief Class constructor. * @details Initialize the class attributes. * * @param processes Process queue to be executed under the algorithm. */ FCFS(std::vector<Process> processes); /** * @brief Class destructor. * @details Does base C++ cleanup. */ ~FCFS(); /** * @brief Called to run the algorithm. * @details Calls the calculateAverageTime member function wich is responsible * for executing the algorithm. */ void init(); /** * @brief Returns the average response time. * * @return The average response time. */ double getAverageResponse() const; /** * @brief Returns the average return time. * * @return The average return time. */ double getAverageReturn() const; /** * @brief Returns the average waiting time. * * @return The average waiting time. */ double getAverageWait() const; /** * @brief Return a formatted string with the algorithm average time. * @details The string returned will be as follow: FCFS X.X X.X X.X * where the first result is the average return time, the second is the * average response time and the third is the average waiting time. * * @return A formatted string. */ std::string toString() const; }; #endif // define FCFS
caiomcg/OS-SchedulingSimulation
include/Utils.h
<filename>include/Utils.h /** * @brief The utils namespace implements useful functions for debugging * * The utils namespace is composed of functions used for extracting * data from files or printing the processes allocated in a std::vector. * * @note Utils function may not be used on the algorithms implementation. * * @author <NAME> <<EMAIL>> */ #ifndef UTILS_H_ #define UTILS_H_ #include <iostream> #include <fstream> #include <vector> #include "Process.h" namespace Utils { /** * @brief Extract the data from a file and store in a std::vector of processes. * @details Open a text file and fetch the data from it creating process objects and * pushing them to the std::vector. * * @param filePath The path where the file is located * @param output The std::vetor where the objects will be pushed to. * * @return True if no problem occured. */ bool extractData(const char* filePath, std::vector<Process>& output); /** * @brief Print the processes from a std::vector. * @details The output will be formatted as follows: * Process - [Program counter] - arrival: arrival time span: process span. * * @param p The std::vector to be printed. */ void print(std::vector<Process>& p); } #endif // define Utils
caiomcg/OS-SchedulingSimulation
include/Process.h
/** * @class Process * * @brief Process simulation class * * This Class is responsible for simulating a process. The * process concists of an arrival time, the process time span * and the program counter for the process. * * @author <NAME> <<EMAIL>> */ #ifndef PROCESS_H_ #define PROCESS_H_ class Process { private: unsigned int _arrival; /// Process arrival time. unsigned int _span; /// Process time span. unsigned int _programCounter; /// Process counter. bool _run; public: /** * @brief Class constructor. * @details Initialize the class attributes. * * @param int Process arrival time. * @param int Process time span. * @param int Process counter(ID). */ Process(unsigned int arrival, unsigned int span, unsigned int programCounter); /** * @brief Class destructor. * @details Does base C++ cleanup. */ ~Process(); /** * @brief Returns the process arrival time. * * @return The arrival time. */ unsigned int getArrivalTime() const; /** * @brief Returns the process time span. * * @return The time span. */ unsigned int getProcessSpan() const; /** * @brief Set the process time span. * * @param int The time span. */ void setProcessSpan(const unsigned int span); /** * @brief Returns the process counter. * * @return The process counter. */ unsigned int getProgramCounter() const; /** * @brief Get if the process ran. * * @return True if ran. */ bool getRun() const; /** * @brief Set if process ran. * * @param run The state of the process. */ void setRun(const bool run); }; #endif // PROCESS_H_
caiomcg/OS-SchedulingSimulation
include/RR.h
/** * @class RR * * @brief Round Robin algorithm simulation class * * This Class is responsible for receiving a std::vector of Processes * and run the RR algorithm over the input. The user can request the * average response time, the average return time and the average wait * time using getters or the toString method. * * @note See Process Class implementation to create the std::vector. * * @author <NAME> <<EMAIL>> */ #ifndef RR_h_ #define RR_h_ #include <vector> #include <string> #include <sstream> #include <iomanip> #include <algorithm> #include "Process.h" #include "Utils.h" class RR { std::vector<Process> _queue; /// The Process queue that will be executed under the algorithm. std::vector<Process> _waiting; /// The Sorted Process queue that will be executed under the algorithm. static const unsigned int quantum = 2; /// The quantum used for every process execution double _avgResponse; /// Average response time. double _avgReturn; /// Average return time. double _avgWait; /// Average waiting time. /** * @brief Remove an amount of elements from the std::vector. * @details Removes the elements based on the distance parameter, which means * that it will remove from the first to first + distance elements. * * @param vector The std::vector that the element will be taken from. * @param int The distance from the beginning to remove. */ void removeFromVector(std::vector<Process>& vector, unsigned int distance); /** * @brief Calculate the average time. * @details Calculate the average time and populate the * double variables so the user can access the resulting * data. */ void calculateAverageTime(); public: /** * @brief Class constructor. * @details Initialize the class attributes. * * @param processes Process queue to be executed under the algorithm. */ RR(std::vector<Process> processes); /** * @brief Class destructor. * @details Does base C++ cleanup. */ ~RR(); /** * @brief Called to run the algorithm. * @details Calls the calculateAverageTime member function wich is responsible * for executing the algorithm. */ void init(); /** * @brief Returns the average response time. * * @return The average response time. */ double getAverageResponse() const; /** * @brief Returns the average return time. * * @return The average return time. */ double getAverageReturn() const; /** * @brief Returns the average waiting time. * * @return The average waiting time. */ double getAverageWait() const; /** * @brief Return a formatted string with the algorithm average time. * @details The string returned will be as follow: RR X.X X.X X.X * where the first result is the average return time, the second is the * average response time and the third is the average waiting time. * * @return A formatted string. */ std::string toString() const; }; #endif //define RR.h
davidcostadev/ufrn-itp
src/aula_10_exercice_03.c
<filename>src/aula_10_exercice_03.c #include <stdio.h> int main() { float celsius; printf("Celsius: "); scanf("%f", &celsius); float kelvin = celsius + 273.15; printf("Kelvin: %f\n", kelvin); return 0; }
davidcostadev/ufrn-itp
src/aula_09_exercice_05.c
#include <stdio.h> int main() { int number; printf("Digite um número: "); scanf("%d", &number); int dividers = 0; int i = 1; while (i <= number) { if (number % i == 0) { printf("- %d é divisor;\n", i); dividers++; } i++; } if (dividers) { printf("%d\n", dividers); } else { printf("No. Divisores\n"); } return 0; }
davidcostadev/ufrn-itp
src/uri_1017.c
// https://www.urionlinejudge.com.br/judge/en/runs/add/1017 #include <stdio.h> int main() { int hours, average_speed; scanf("%d", &hours); scanf("%d", &average_speed); float liters_per_km = 12; float liters = (hours * average_speed) / liters_per_km; printf("%.3f\n", liters); return 0; }
davidcostadev/ufrn-itp
src/uri_1014.c
// https://www.urionlinejudge.com.br/judge/en/problems/view/1014 #include <stdio.h> int main() { int distance; float liters; scanf("%d", &distance); scanf("%f", &liters); float liters_per_km = distance / liters; printf("%.3f km/l\n", liters_per_km); return 0; }
davidcostadev/ufrn-itp
src/aula_09_exercice_03.c
<reponame>davidcostadev/ufrn-itp<gh_stars>1-10 #include <stdio.h> int main() { int A, B; printf("A: "); scanf("%d", &A); printf("B: "); scanf("%d", &B); int w = A; int sum = 0; while(w <= B) { sum += w; w++; } printf("SUM=%d\n", sum); return 0; }
davidcostadev/ufrn-itp
src/aula_08_exercice_01.c
#include <stdio.h> int main() { double a, b; printf("Enter with a 1ª number:\n"); scanf("%lf", &a); printf("Enter with a 2ª number:\n"); scanf("%lf", &b); printf("%lf\n", a + b); return 0; }
davidcostadev/ufrn-itp
src/aula_07_exercice_01.c
#include <stdio.h> int main() { int number; scanf("%d", &number); printf("sucessor: %d\n", number - 1); printf("antecessor: %d\n", number + 1); return 0; }
davidcostadev/ufrn-itp
src/aula_08_exercice_05.c
<reponame>davidcostadev/ufrn-itp<gh_stars>1-10 #include <stdio.h> int main() { float aline = 9; float mario = 10; float sergio = 4.5; float paulo = 7; printf("|NOME\t| NOTA|\n"); printf("+=======+=====|\n"); printf("|ALINE\t|% 5.1f|\n", aline); printf("|MARIO\t|% 5.1f|\n", mario); printf("|SERGIO\t|% 5.1f|\n", sergio); printf("|PAULO\t|% 5.1f|\n", paulo); return 0; }
davidcostadev/ufrn-itp
src/uri_1016.c
<reponame>davidcostadev/ufrn-itp // https://www.urionlinejudge.com.br/judge/en/problems/view/1016 #include <stdio.h> int main() { int km; scanf("%d", &km); int minutes_distance = km * 2; printf("%d minutos\n", minutes_distance); return 0; }
davidcostadev/ufrn-itp
src/uri_1010.c
// https://www.urionlinejudge.com.br/judge/en/problems/view/1010 #include <stdio.h> int main() { int id, unit; float price; float total = 0; scanf("%d %d %f", &id, &unit, &price); total += unit * price; scanf("%d %d %f", &id, &unit, &price); total += unit * price; printf("VALOR A PAGAR: R$ %.2f\n", total); return 0; }
davidcostadev/ufrn-itp
src/aula_08_exercice_04.c
<filename>src/aula_08_exercice_04.c #include <stdio.h> int main() { char option = 'p'; printf("Enter 'P' to show a pine and 'S' to show a squade. [P/S]\n"); scanf("%c", &option); if (option == 'P' || option == 'p') { printf(" X\n"); printf(" XXX\n"); printf(" XXXXX\n"); printf(" XXXXXXX\n"); printf(" XXXXXXXXX\n"); printf(" XXXXXXXXXXX\n"); printf(" XXXXXXXXXXXXX\n"); printf("XXXXXXXXXXXXXXX\n"); printf(" XX\n"); printf(" XX\n"); printf(" XXXX\n"); } else if (option == 'S' || option == 's') { printf("XXXXXXXXX\nX\tX\nX\tX\nXXXXXXXXX\n"); } else { printf("Invalid option\n"); } return 0; }
davidcostadev/ufrn-itp
src/uri_1015.c
// https://www.urionlinejudge.com.br/judge/en/problems/view/1015 #include <stdio.h> #include <math.h> double distance(double x1, double x2, double y1, double y2) { return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)); } int main() { double x1, x2, y1, y2; scanf("%lf %lf", &x1, &y1); scanf("%lf %lf", &x2, &y2); double calc = distance(x1, x2, y1, y2); printf("%.4lf\n", calc); return 0; }
davidcostadev/ufrn-itp
src/aula_12.c
<gh_stars>1-10 #include <stdio.h> int main() { int const MED = 10; int vet[MED]; for (int i = 0; i < MED; i++) vet[i] = 0; for (int i = 0; i < MED; ++i) { printf("%i\n", vet[i]); } vet[15] = 333; char letras[5] = {'d', 'a', 'v', 'i', 'd'}; for (int i = 0; i < 5; i++) { printf("%c", letras[i]); } printf("\n"); return 0; }
davidcostadev/ufrn-itp
src/aula_09_exercice_01.c
#include <stdio.h> int main() { int numbers; printf("N: "); scanf("%d", &numbers); printf("--- WHILE ---\n"); int w = numbers; while (w <= 0) { printf("W = %d\n", w); w++; } printf("--- FOR ---\n"); for (int i = numbers; i < 0; i++) { printf("F = %d\n", i); } return 0; }
davidcostadev/ufrn-itp
src/uri_1011.c
<gh_stars>1-10 // https://www.urionlinejudge.com.br/judge/en/problems/view/1011 #include <stdio.h> #include <math.h> int main() { double radius; scanf("%lf", &radius); double PI = 3.14159; double calc = (4 / 3.0) * PI * pow(radius, 3); printf("VOLUME = %.3lf\n", calc); return 0; }
davidcostadev/ufrn-itp
src/aula_09_exercice_04.c
#include <stdio.h> int main() { int number = 0; while (number < 1 || number > 5) { printf("Digite um número de 1 à 5: "); scanf("%d", &number); if (number < 1 || number > 5) { printf("Error: número inválido.\n"); } } printf("N = %d\n", number); return 0; }
davidcostadev/ufrn-itp
src/aula_10_exercice_02.c
#include <stdio.h> int main() { float fahrenheit; printf("Fahrenheit: "); scanf("%f", &fahrenheit); float celsius = (fahrenheit - 32) * 5.0 / 9.0; printf("Celsius: %f\n", celsius); return 0; }
davidcostadev/ufrn-itp
src/aula_08_exercice_02.c
#include <stdio.h> int main() { double a, b, c; printf("Enter with a 1ª number:\n"); scanf("%lf", &a); printf("Enter with a 2ª number:\n"); scanf("%lf", &b); printf("Enter with a 3ª number:\n"); scanf("%lf", &c); printf("%lf\n", a * c); if (a == 0) { printf("Error: You can't divide %lg by Zero\n", b); return 1; } printf("%lf\n", b / a); return 0; }
davidcostadev/ufrn-itp
src/uri_1013.c
<reponame>davidcostadev/ufrn-itp // https://www.urionlinejudge.com.br/judge/en/problems/view/1013 #include <stdio.h> #include <stdlib.h> int diff_numbers(int x, int y) { return (x + y + abs(x - y)) / 2; } int main() { int a, b, c; scanf("%d %d %d", &a, &b, &c); int a_b = diff_numbers(a, b); int a_c = diff_numbers(a, c); int c_b = diff_numbers(c, b); int greast; if (a_b == a_c) { greast = a_b; } else if (a_b == c_b) { greast = a_b; } else if (a_c = c_b) { greast = c_b; } printf("%d eh o maior\n", greast); return 0; }
davidcostadev/ufrn-itp
src/aula_10_exercice_05.c
<reponame>davidcostadev/ufrn-itp<gh_stars>1-10 #include <stdio.h> float fahrenheitToCelsius(float fahrenheit) { return (fahrenheit - 32) * 5.0 / 9.0; } float celsiusToFahrenheit(float celsius) { return celsius * (9.0 / 5.0) + 32.0; } float kelvinToCelsius(float kelvin) { return kelvin - 273.15; } float celsiusToKelvin(float celsius) { return celsius + 273.15; } int main() { int option; float number; while (option < 1 || option > 5) { printf("Digite:\n"); printf("1 : para Fahrenheit --> Celsius\n"); printf("2 : para Celsius --> Fahrenheit\n"); printf("3 : para Kelvin --> Celsius\n"); printf("4 : para Celsius --> Kelvin\n"); printf("5 : Sair\n"); scanf("%d", &option); if (option < 1 || option > 5) { printf("Error: Opção inválida\n"); } else { if (option == 5) return 0; printf("Digite um numéro para fazer a converção: "); scanf("%f", &number); switch (option) { case 1: printf("=%f\n", fahrenheitToCelsius(number)); break; case 2: printf("=%f\n", celsiusToFahrenheit(number)); break; case 3: printf("=%f\n", kelvinToCelsius(number)); break; case 4: printf("=%f\n", celsiusToKelvin(number)); break; } } } return 0; }
davidcostadev/ufrn-itp
src/aula_08.c
<reponame>davidcostadev/ufrn-itp<filename>src/aula_08.c #include <stdio.h> int main() { int a = 1; int b = 4; while (a < b) { printf("%i\n", a); a++; } return 0; }
davidcostadev/ufrn-itp
src/exercise_03.c
<filename>src/exercise_03.c #include <stdio.h> void exercise_03() { printf("Exercício 03\n"); float fahrenheit; printf("Fahrenheit: "); scanf("%f", &fahrenheit); float celsius = (fahrenheit - 32) * 5 / 9; printf("CELSIUS= %f\n", celsius); } int main() { exercise_03(); return 0; }
davidcostadev/ufrn-itp
src/exercise_02.c
#include <stdio.h> void exercise_02() { printf("Exercício 02\n"); float distance; float liters; printf("Distância em KM: "); scanf("%f", &distance); printf("Litros: "); scanf("%f", &liters); float liter_per_km = distance / liters; printf("CONSUMO_MEDIO=%f km/l\n", liter_per_km); } int main() { exercise_02(); return 0; }
davidcostadev/ufrn-itp
src/uri_1009.c
// https://www.urionlinejudge.com.br/judge/en/problems/view/1009 #include <stdio.h> int main() { char name[100]; float salary, sold_products; scanf("%s", &name); scanf("%f", &salary); scanf("%f", &sold_products); float commission = (15 * sold_products) / 100; float total = salary + commission; printf("TOTAL = R$ %.2f\n", total); return 0; }
davidcostadev/ufrn-itp
src/uri_1008.c
<reponame>davidcostadev/ufrn-itp<filename>src/uri_1008.c // https://www.urionlinejudge.com.br/judge/en/problems/view/1008 #include <stdio.h> int main() { int number, hours; float amount; scanf("%d", &number); scanf("%d", &hours); scanf("%f", &amount); float salary = hours * amount; printf("NUMBER = %d\n", number); printf("SALARY = U$ %.2f\n", salary); return 0; }
davidcostadev/ufrn-itp
src/aula_09_exercice_02.c
#include <stdio.h> int main() { int numbers; printf("N: "); scanf("%d", &numbers); printf("--- WHILE ---\n"); int w = 1; int sum = 0; while (w <= numbers) { int number; printf("N%dº = ", w); scanf("%d", &number); sum += number; w++; } float averange = sum / numbers; printf("MEDIA = %.3f\n", averange); printf("--- FOR ---\n"); int sum_for = 0; for (int i = 1; i <= numbers; i++) { int number_for; printf("N%dº: ", i); scanf("%d", &number_for); sum_for += number_for; } float averange_for = sum_for / numbers; printf("MEDIA=%.3f\n", averange_for); return 0; }
davidcostadev/ufrn-itp
src/uri_1012.c
#include <stdio.h> #include <math.h> int main() { float a, b, c; scanf("%f %f %f", &a, &b, &c); float triangulo, circulo, trapezio, quadrado, retangulo; double pi = 3.14159; triangulo = (a * c) / 2; circulo = pow(c, 2) * pi; trapezio = ((a + b) * c) / 2; quadrado = pow(b, 2); retangulo = a * b; printf("TRIANGULO: %.3f\n", triangulo); printf("CIRCULO: %.3f\n", circulo); printf("TRAPEZIO: %.3f\n", trapezio); printf("QUADRADO: %.3f\n", quadrado); printf("RETANGULO: %.3f\n", retangulo); return 0; }
davidcostadev/ufrn-itp
src/aula_01.c
#include <stdio.h> int main() { printf("Olá\n"); int value1 = 10; int value2 = 5; int value3 = value1 + value2; printf("Digite um número:\n"); scanf("%i", &value1); printf("v1: %d, v2: %d, v3: %d\n", value1, value2, value3); return 0; }
davidcostadev/ufrn-itp
src/aula_07_exercice_02.c
#include <stdio.h> int main() { double a, b; scanf("%lf", &a); scanf("%lf", &b); if (a == b) { printf("%lf\n", a * b); } else if (a < b) { printf("%lf\n", b - a); } else { printf("%lf\n", a - b); } return 0; }
davidcostadev/ufrn-itp
src/aula_08_exercice_03.c
<gh_stars>1-10 #include <stdio.h> int main() { int a, b, c; printf("Enter with a A value:\n"); scanf("%d", &a); printf("Enter with a B value:\n"); scanf("%d", &b); printf("Enter with a C value:\n"); scanf("%d", &c); if (a && b) { printf("VERDADEIRO: A and B\n"); } else { printf("FALSO: A and B\n"); } if (a || c) { printf("VERDADEIRO: A or C\n"); } else { printf("FALSO: A or C\n"); } if (!((a && b) || c)) { printf("VERDADEIRO: !(A && B || C)\n"); } else { printf("FALSO: !(A && B || C)\n"); } return 0; }
davidcostadev/ufrn-itp
src/exercise_01.c
#include <stdio.h> void exercise_01() { printf("Exercício 01\n"); float one; float two; printf("Digite a 1ª nota: "); scanf("%f", &one); printf("Digite a 2ª nota: "); scanf("%f", &two); double media = (one + two) / 2; printf("MEDIA=%f\n", media); } int main() { exercise_01(); return 0; }
davidcostadev/ufrn-itp
src/aula_07_exercice_03.c
<reponame>davidcostadev/ufrn-itp<gh_stars>1-10 #include <stdio.h> int main() { double x, y; char operation; int exit = 0; printf("Enter with your expression\nEx.: 1+3 and ENTER.\nYou can use +, -, * and /.\n"); scanf("%lf %c %lf", &x, &operation, &y); switch (operation) { case '+': printf("> %lf\n", x + y); break; case '-': printf("> %lf\n", x - y); break; case '*': printf("> %lf\n", (x * y)); break; case '/': if (y == 0) { printf("Error: You can't divide %lg by Zero\n", x); } else { printf("%lf\n", x / y); } break; default: printf("Error: Operator Invalid, Please use just + ,- , * and / operators\n"); break; } return 0; }
davidcostadev/ufrn-itp
src/aula_10_exercice_01.c
<filename>src/aula_10_exercice_01.c #include <stdio.h> int main() { float celsius; printf("Celsius: "); scanf("%f", &celsius); float fahrenheit = celsius * (9.0 / 5.0) + 32.0; printf("fahrenheit: %f\n", fahrenheit); return 0; }
davidcostadev/ufrn-itp
src/aula_13.c
<reponame>davidcostadev/ufrn-itp #include <stdio.h> #include <string.h> int main() { char nome_david[] = {'d', 'a', 'v', 'i', 'd', '\0', ' ', 's'}; char nome_juliana[] = "juliana"; char nome_completo[10]; nome_david[7] = '-'; nome_david[8] = '-'; nome_david[10] = '?'; nome_david[11] = '?'; printf("%s\n", nome_david); printf("%s\n", nome_juliana); printf("%s\n", nome_completo); // char test_entrada[3]; // scanf("%f", &test_entrada); // setbuf(stdin, NULL); // limpar o buffer // gets(test_entrada); // não segura // printf("%s\n", test_entrada); // contando printf("%lu-%lu\n", strlen(nome_david), sizeof(nome_david)); printf("%lu-%lu\n", strlen(nome_juliana), sizeof(nome_juliana)); printf("%lu-%lu\n", strlen(nome_completo), sizeof(nome_completo)); // copiando char destino[10]; strcpy(destino, nome_juliana); printf("%s\n", destino); // contact char last_name[] = "costa"; strcat(nome_juliana, last_name); printf("%s\n", nome_juliana); // fgets char line[10] = "123"; fgets(line, sizeof(line), stdin); printf("%s\n", line); for (int i = 0; i < 30; i++) { if (nome_david[i] == '\0') { printf("\\0"); } printf("%c", nome_david[i]); } printf("\n"); return 0; }
davidcostadev/ufrn-itp
src/aula_02.c
<filename>src/aula_02.c #include <stdio.h> int main() { int n1 = 12; int n2 = 10; // tipos de ifs if (n1 > n2) { printf("n1 maior\n"); printf("n1 segunda linha\n"); } if (n2 > n2) printf("n2 maior\n"); if (n1 == n2) printf("iguais\n"); // par e impar if (n1 % 2 == 0) printf("par\n"); if (n1 % 2 != 0) printf("impar\n"); // switch case char value = '5'; switch (value) { case 11: printf("11\n"); break; case '5': printf("5\n"); break; default: printf("??\n"); } return 0; }
ericaguthan/yugabyte-db
src/yb/util/priority_thread_pool.h
// Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #ifndef YB_UTIL_PRIORITY_THREAD_POOL_H #define YB_UTIL_PRIORITY_THREAD_POOL_H #include <memory> #include "yb/util/locks.h" #include "yb/util/status.h" #include "yb/util/enums.h" namespace yb { // PriorityThreadPoolSuspender is provided to task ran by thread pool, task could use it to check // whether is should be preempted in favor of another task with higher priority. class PriorityThreadPoolSuspender { public: virtual void PauseIfNecessary() = 0; virtual ~PriorityThreadPoolSuspender() {} }; class PriorityThreadPoolTask { public: PriorityThreadPoolTask(); virtual ~PriorityThreadPoolTask() = default; // If status is OK - execute this task in the current thread. // Otherwise - abort task with specified status. virtual void Run(const Status& status, PriorityThreadPoolSuspender* suspender) = 0; // Returns true if the task belongs to specified key, which was passed to // PriorityThreadPool::Remove. virtual bool BelongsTo(void* key) = 0; virtual std::string ToString() const = 0; size_t SerialNo() const { return serial_no_; } private: const size_t serial_no_; }; // Tasks submitted to this pool have assigned priority and are picked from queue using it. class PriorityThreadPool { public: explicit PriorityThreadPool(int64_t max_running_tasks); ~PriorityThreadPool(); // Submit task to the pool. // On success task ownership is transferred to the pool, i.e. `task` would point to nullptr. CHECKED_STATUS Submit(int priority, std::unique_ptr<PriorityThreadPoolTask>* task); template <class Task> CHECKED_STATUS Submit(int priority, std::unique_ptr<Task>* task) { std::unique_ptr<PriorityThreadPoolTask> temp_task = std::move(*task); auto result = Submit(priority, &temp_task); task->reset(down_cast<Task*>(temp_task.release())); return result; } // Remove all tasks with provided key from the pool. void Remove(void* key); // Change priority of task with specified serial no. // Returns true if change was performed. bool ChangeTaskPriority(size_t serial_no, int priority); void Shutdown() { StartShutdown(); CompleteShutdown(); } // Two step shutdown paradigm is used to prevent deadlock when shutting down multiple components. // There could be case when one component wait until other component aborts specific job, but // it is not done since shutdown of second component is invoked after shutdown of the first one. // To avoid this case StartShutdown could be invoked on both of them, then CompleteShutdown waits // until they complete it. // Initiates shutdown of this pool. All new tasks will be aborted after this point. void StartShutdown(); // Completes shutdown of this pool. It is safe to destroy pool after it. void CompleteShutdown(); // Dumps state to string, useful for debugging. std::string StateToString(); void TEST_SetThreadCreationFailureProbability(double probability); private: class Impl; std::unique_ptr<Impl> impl_; }; } // namespace yb #endif // YB_UTIL_PRIORITY_THREAD_POOL_H
ericaguthan/yugabyte-db
src/postgres/src/include/common/pg_yb_common.h
/* ---------- * pg_yb_utils.h * * Common utilities for YugaByte/PostgreSQL integration that are reused between * PostgreSQL server code and other PostgreSQL programs such as initdb. * * Copyright (c) YugaByte, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * src/common/pg_yb_common.h * ---------- */ #ifndef PG_YB_COMMON_H #define PG_YB_COMMON_H #define YB_INITDB_ALREADY_DONE_EXIT_CODE 125 /** * Checks if the given environment variable is set to a "true" value (e.g. "1"). */ extern bool YBCIsEnvVarTrue(const char* env_var_name); /** * Checks if the given environment variable is set to a "true" value (e.g. "1"), * but with the given default value in case the environment variable is not * defined, or is set to an empty string or the string "auto". */ extern bool YBCIsEnvVarTrueWithDefault( const char* env_var_name, bool default_value); /** * Checks if the YB_ENABLED_IN_POSTGRES is set. This is different from * IsYugaByteEnabled(), because the IsYugaByteEnabled() also checks that we are * in the "normal processing mode" and we have a YB client session. */ extern bool YBIsEnabledInPostgresEnvVar(); /** * Returns true to allow running PostgreSQL server and initdb as any user. This * is needed by some Docker/Kubernetes environments. */ extern bool YBShouldAllowRunningAsAnyUser(); /** * Check if the environment variable indicating that this is a child process * of initdb is set. */ extern bool YBIsInitDbModeEnvVarSet(); /** * Set the environment variable that will tell initdb's child process * that they are running as part of initdb. */ extern void YBSetInitDbModeEnvVar(); /** * Checks if environment variables indicating that YB's unsupported features must * be restricted are set */ extern bool YBIsUsingYBParser(); /** * Returns ERROR or WARNING level depends on environment variable */ extern int YBUnsupportedFeatureSignalLevel(); /** * Returns whether non-transactional COPY gflag is enabled. */ extern bool YBIsNonTxnCopyEnabled(); /** * Returns whether running the ANALYZE command is enabled. */ extern bool YBIsAnalyzeCmdEnabled(); #endif /* PG_YB_COMMON_H */
ericaguthan/yugabyte-db
src/yb/tserver/remote_bootstrap_session-test.h
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // The following only applies to changes made to this file as part of YugaByte development. // // Portions Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #ifndef YB_TSERVER_REMOTE_BOOTSTRAP_SESSION_TEST_H_ #define YB_TSERVER_REMOTE_BOOTSTRAP_SESSION_TEST_H_ #include <memory> #include <glog/logging.h> #include <gtest/gtest.h> #include "yb/tablet/tablet-test-util.h" #include "yb/common/partial_row.h" #include "yb/common/schema.h" #include "yb/common/wire_protocol-test-util.h" #include "yb/consensus/consensus.h" #include "yb/consensus/consensus_meta.h" #include "yb/consensus/log.h" #include "yb/consensus/metadata.pb.h" #include "yb/consensus/opid_util.h" #include "yb/gutil/gscoped_ptr.h" #include "yb/gutil/ref_counted.h" #include "yb/gutil/strings/fastmem.h" #include "yb/gutil/strings/substitute.h" #include "yb/rpc/messenger.h" #include "yb/tserver/remote_bootstrap_session.h" #include "yb/tablet/tablet_peer.h" #include "yb/tablet/operations/write_operation.h" #include "yb/util/crc.h" #include "yb/util/metrics.h" #include "yb/util/test_util.h" #include "yb/util/threadpool.h" METRIC_DECLARE_entity(table); METRIC_DECLARE_entity(tablet); DECLARE_bool(quick_leader_election_on_create); using std::shared_ptr; using std::string; namespace yb { namespace tserver { using std::unique_ptr; using consensus::ConsensusMetadata; using consensus::RaftConfigPB; using consensus::RaftPeerPB; using log::Log; using log::LogOptions; using log::LogAnchorRegistry; using rpc::Messenger; using rpc::MessengerBuilder; using strings::Substitute; using tablet::YBTabletTest; using tablet::TabletPeer; using tablet::RaftGroupReplicaSuperBlockPB; using tablet::WriteOperationState; const int64_t kLeaderTerm = 1; class RemoteBootstrapTest : public YBTabletTest { public: explicit RemoteBootstrapTest(TableType table_type) : YBTabletTest(GetSimpleTestSchema(), table_type) { } virtual void SetUp() override { ASSERT_OK(ThreadPoolBuilder("raft").Build(&raft_pool_)); ASSERT_OK(ThreadPoolBuilder("prepare").Build(&tablet_prepare_pool_)); ASSERT_OK(ThreadPoolBuilder("log").Build(&log_thread_pool_)); YBTabletTest::SetUp(); SetUpTabletPeer(); ASSERT_NO_FATALS(PopulateTablet()); InitSession(); } virtual void TearDown() override { messenger_->Shutdown(); session_.reset(); WARN_NOT_OK(tablet_peer_->Shutdown(), "Tablet peer shutdown failed"); YBTabletTest::TearDown(); } protected: void SetUpTabletPeer() { scoped_refptr<Log> log; ASSERT_OK(Log::Open(LogOptions(), tablet()->tablet_id(), fs_manager()->GetFirstTabletWalDirOrDie(tablet()->metadata()->table_id(), tablet()->tablet_id()), fs_manager()->uuid(), *tablet()->schema(), 0, // schema_version nullptr, // table_metric_entity nullptr, // tablet_metric_entity log_thread_pool_.get(), log_thread_pool_.get(), std::numeric_limits<int64_t>::max(), // cdc_min_replicated_index &log)); scoped_refptr<MetricEntity> table_metric_entity = METRIC_ENTITY_table.Instantiate(&metric_registry_, Format("table-$0", CURRENT_TEST_NAME())); scoped_refptr<MetricEntity> tablet_metric_entity = METRIC_ENTITY_tablet.Instantiate(&metric_registry_, Format("tablet-$0", CURRENT_TEST_NAME())); RaftPeerPB config_peer; config_peer.set_permanent_uuid(fs_manager()->uuid()); config_peer.set_member_type(RaftPeerPB::VOTER); auto hp = config_peer.mutable_last_known_private_addr()->Add(); hp->set_host("fake-host"); hp->set_port(0); tablet_peer_.reset(new TabletPeer( tablet()->metadata(), config_peer, clock(), fs_manager()->uuid(), Bind( &RemoteBootstrapTest::TabletPeerStateChangedCallback, Unretained(this), tablet()->tablet_id()), &metric_registry_, nullptr /* tablet_splitter */, std::shared_future<client::YBClient*>())); // TODO similar to code in tablet_peer-test, consider refactor. RaftConfigPB config; config.add_peers()->CopyFrom(config_peer); config.set_opid_index(consensus::kInvalidOpIdIndex); std::unique_ptr<ConsensusMetadata> cmeta; ASSERT_OK(ConsensusMetadata::Create(tablet()->metadata()->fs_manager(), tablet()->tablet_id(), fs_manager()->uuid(), config, consensus::kMinimumTerm, &cmeta)); MessengerBuilder mbuilder(CURRENT_TEST_NAME()); messenger_ = ASSERT_RESULT(mbuilder.Build()); proxy_cache_ = std::make_unique<rpc::ProxyCache>(messenger_.get()); log_anchor_registry_.reset(new LogAnchorRegistry()); ASSERT_OK(tablet_peer_->SetBootstrapping()); ASSERT_OK(tablet_peer_->InitTabletPeer( tablet(), nullptr /* server_mem_tracker */, messenger_.get(), proxy_cache_.get(), log, table_metric_entity, tablet_metric_entity, raft_pool_.get(), tablet_prepare_pool_.get(), nullptr /* retryable_requests */, consensus::SplitOpInfo())); consensus::ConsensusBootstrapInfo boot_info; ASSERT_OK(tablet_peer_->Start(boot_info)); ASSERT_OK(tablet_peer_->WaitUntilConsensusRunning(MonoDelta::FromSeconds(2))); AssertLoggedWaitFor([&]() -> Result<bool> { if (FLAGS_quick_leader_election_on_create) { return tablet_peer_->LeaderStatus() == consensus::LeaderStatus::LEADER_AND_READY; } RETURN_NOT_OK(tablet_peer_->consensus()->EmulateElection()); return true; }, MonoDelta::FromMilliseconds(500), "If quick leader elections enabled, wait for peer to be a " "leader, otherwise emulate."); } void TabletPeerStateChangedCallback(const string& tablet_id, std::shared_ptr<consensus::StateChangeContext> context) { LOG(INFO) << "Tablet peer state changed for tablet " << tablet_id << ". Reason: " << context->ToString(); } void PopulateTablet() { for (int32_t i = 0; i < 1000; i++) { WriteRequestPB req; req.set_tablet_id(tablet_peer_->tablet_id()); AddTestRowInsert(i, i * 2, Substitute("key$0", i), &req); WriteResponsePB resp; CountDownLatch latch(1); auto state = std::make_unique<WriteOperationState>(tablet_peer_->tablet(), &req, &resp); state->set_completion_callback(tablet::MakeLatchOperationCompletionCallback(&latch, &resp)); tablet_peer_->WriteAsync( std::move(state), kLeaderTerm, CoarseTimePoint::max() /* deadline */); latch.Wait(); ASSERT_FALSE(resp.has_error()) << "Request failed: " << resp.error().ShortDebugString(); ASSERT_EQ(QLResponsePB::YQL_STATUS_OK, resp.ql_response_batch(0).status()) << "Insert error: " << resp.ShortDebugString(); } ASSERT_OK(tablet()->Flush(tablet::FlushMode::kSync)); } virtual void InitSession() { session_.reset(new RemoteBootstrapSession( tablet_peer_, "TestSession", "FakeUUID", nullptr /* nsessions */)); ASSERT_OK(session_->Init()); } MetricRegistry metric_registry_; scoped_refptr<LogAnchorRegistry> log_anchor_registry_; unique_ptr<ThreadPool> raft_pool_; unique_ptr<ThreadPool> tablet_prepare_pool_; unique_ptr<ThreadPool> log_thread_pool_; std::shared_ptr<TabletPeer> tablet_peer_; scoped_refptr<RemoteBootstrapSession> session_; std::unique_ptr<rpc::Messenger> messenger_; std::unique_ptr<rpc::ProxyCache> proxy_cache_; }; } // namespace tserver } // namespace yb #endif // YB_TSERVER_REMOTE_BOOTSTRAP_SESSION_TEST_H_
HipsterJazzbo/PodTest
Example/PodTest/PTAppDelegate.h
// // PTAppDelegate.h // PodTest // // Created by CocoaPods on 04/28/2015. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface PTAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
HipsterJazzbo/PodTest
Example/PodTest/PTViewController.h
<filename>Example/PodTest/PTViewController.h // // PTViewController.h // PodTest // // Created by <NAME> on 04/28/2015. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface PTViewController : UIViewController @end
lbovolini/ordena-comprime-enad
ordenacao/sort.c
<filename>ordenacao/sort.c<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <string.h> #include "sort.h" #include "string_aux.h" void insertionsort (char **arquivo_memoria, int *indice_linhas, int **indice_separadores, int coluna1, int num_linhas) { if (!arquivo_memoria) { printf ("Erro insertion_sort_2()\n"); exit (EXIT_FAILURE); } for (int i = 1; i < num_linhas; i++) { int atual = indice_linhas[i]; int *atual_separador = indice_separadores[indice_linhas[i]]; int j = i - 1; char *str1 = NULL, *str2 = NULL; free(str1); free(str2); str1 = get_substring (*(arquivo_memoria + indice_linhas[i]), indice_separadores[indice_linhas[i]][coluna1 - 1], indice_separadores[indice_linhas[i]][coluna1]); str2 = get_substring (*(arquivo_memoria + indice_linhas[j]), indice_separadores[indice_linhas[j]][coluna1 - 1], indice_separadores[indice_linhas[j]][coluna1]); while ((j >= 0) && (strcasecmp (str1, str2) > 0)) { indice_linhas[j + 1] = indice_linhas[j]; indice_separadores[indice_linhas[j + 1]] = indice_separadores[indice_linhas[j]]; free(str2); j = j - 1; str2 = get_substring (*(arquivo_memoria + indice_linhas[j]), indice_separadores[indice_linhas[j]][coluna1 - 1], indice_separadores[indice_linhas[j]][coluna1]); } indice_linhas[j + 1] = atual; indice_separadores[indice_linhas[j + 1]] = atual_separador; } } void quicksort_string (char **arquivo_memoria, int *indice_linhas, int **indice_separadores, int coluna1, int num_linhas, int esquerda, int direita) { int i, j; char *pivo, *p1, *p2; i = esquerda; j = direita; pivo = get_substring (*(arquivo_memoria + indice_linhas[(esquerda + direita) / 2]), indice_separadores[indice_linhas[(esquerda + direita) / 2]][coluna1 - 1], indice_separadores[indice_linhas[(esquerda + direita) / 2]][coluna1]); do { p1 = get_substring (*(arquivo_memoria + indice_linhas[i]), indice_separadores[indice_linhas[i]][coluna1 - 1], indice_separadores[indice_linhas[i]][coluna1]); while ((strcasecmp (p1, pivo) < 0) && (i < direita)) { i++; p1 = get_substring (*(arquivo_memoria + indice_linhas[i]), indice_separadores[indice_linhas[i]][coluna1 - 1], indice_separadores[indice_linhas[i]][coluna1]); } p2 = get_substring (*(arquivo_memoria + indice_linhas[j]), indice_separadores[indice_linhas[j]][coluna1 - 1], indice_separadores[indice_linhas[j]][coluna1]); while ((strcasecmp (p2, pivo) > 0) && (j > esquerda)) { j--; p2 = get_substring (*(arquivo_memoria + indice_linhas[j]), indice_separadores[indice_linhas[j]][coluna1 - 1], indice_separadores[indice_linhas[j]][coluna1]); } if (i <= j) { int temp; int *p; temp = indice_linhas[i]; p = indice_separadores[indice_linhas[i]]; indice_linhas[i] = indice_linhas[j]; indice_separadores[indice_linhas[i]] = indice_separadores[indice_linhas[j]]; indice_linhas[j] = temp; indice_separadores[indice_linhas[j]] = p; i++; j--; } } while (i <= j); if (esquerda < j) { quicksort_string (arquivo_memoria, indice_linhas, indice_separadores, coluna1, num_linhas, esquerda, j); } if (i < direita) { quicksort_string (arquivo_memoria, indice_linhas, indice_separadores, coluna1, num_linhas, i, direita); } } void quicksort_number (char **arquivo_memoria, int *indice_linhas, int **indice_separadores, int coluna1, int num_linhas, int esquerda, int direita) { int i, j; float pivo, p1, p2; i = esquerda; j = direita; pivo = get_number (*(arquivo_memoria + indice_linhas[(esquerda + direita) / 2]), indice_separadores[indice_linhas[(esquerda + direita) / 2]][coluna1 - 1], indice_separadores[indice_linhas[(esquerda + direita) / 2]][coluna1]); do { p1 = get_number (*(arquivo_memoria + indice_linhas[i]), indice_separadores[indice_linhas[i]][coluna1 - 1], indice_separadores[indice_linhas[i]][coluna1]); while ((p1 < pivo) && (i < direita)) { i++; p1 = get_number (*(arquivo_memoria + indice_linhas[i]), indice_separadores[indice_linhas[i]][coluna1 - 1], indice_separadores[indice_linhas[i]][coluna1]); } p2 = get_number (*(arquivo_memoria + indice_linhas[j]), indice_separadores[indice_linhas[j]][coluna1 - 1], indice_separadores[indice_linhas[j]][coluna1]); while ((p2 > pivo) && (j > esquerda)) { j--; p2 = get_number (*(arquivo_memoria + indice_linhas[j]), indice_separadores[indice_linhas[j]][coluna1 - 1], indice_separadores[indice_linhas[j]][coluna1]); } if (i <= j) { int temp; int *p; temp = indice_linhas[i]; p = indice_separadores[indice_linhas[i]]; indice_linhas[i] = indice_linhas[j]; indice_separadores[indice_linhas[i]] = indice_separadores[indice_linhas[j]]; indice_linhas[j] = temp; indice_separadores[indice_linhas[j]] = p; i++; j--; } } while (i <= j); if (esquerda < j) { quicksort_number (arquivo_memoria, indice_linhas, indice_separadores, coluna1, num_linhas, esquerda, j); } if (i < direita) { quicksort_number (arquivo_memoria, indice_linhas, indice_separadores, coluna1, num_linhas, i, direita); } } /* void *bubblesort (char **arquivo_memoria, int *indice_linhas, int **indice_separadores, int coluna1, int num_linhas) { if (!arquivo_memoria) { printf ("Erro insertion_sort()\n"); exit (EXIT_FAILURE); } for (int i = 0; i < num_linhas; i++) { for (int j = i; j < num_linhas; j++) { char *str1 = NULL, *str2 = NULL; str1 = get_substring (*(arquivo_memoria + indice_linhas[i]), indice_separadores[indice_linhas[i]][coluna1 - 1], indice_separadores[indice_linhas[i]][coluna1]); str2 = get_substring (*(arquivo_memoria + indice_linhas[j]), indice_separadores[indice_linhas[j]][coluna1 - 1], indice_separadores[indice_linhas[j]][coluna1]); if (strcasecmp (str1, str2) > 0) { // Troca int temp; int *p; temp = indice_linhas[i]; p = indice_separadores[indice_linhas[i]]; indice_linhas[i] = indice_linhas[j]; indice_separadores[indice_linhas[i]] = indice_separadores[indice_linhas[j]]; indice_linhas[j] = temp; indice_separadores[indice_linhas[j]] = p; } free(str1); free(str2); } } }*/