1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef FFRT_CO_ROUTINE_HPP 17 #define FFRT_CO_ROUTINE_HPP 18 #include <functional> 19 #include <atomic> 20 #include "co2_context.h" 21 #if defined(__aarch64__) 22 constexpr size_t STACK_MAGIC = 0x7BCDABCDABCDABCD; 23 #elif defined(__arm__) 24 constexpr size_t STACK_MAGIC = 0x7BCDABCD; 25 #elif defined(__x86_64__) 26 constexpr size_t STACK_MAGIC = 0x7BCDABCDABCDABCD; 27 #endif 28 29 namespace ffrt { 30 struct TaskCtx; 31 struct WaitEntry; 32 } // namespace ffrt 33 struct CoRoutine; 34 35 enum class CoStatus { 36 CO_UNINITIALIZED, 37 CO_NOT_FINISH, 38 CO_RUNNING, 39 }; 40 41 enum class CoStackProtectType { 42 CO_STACK_WEAK_PROTECT, 43 CO_STACK_STRONG_PROTECT 44 }; 45 46 #if defined(__aarch64__) 47 constexpr uint64_t STACK_SIZE = 1 << 20; // 至少3*PAGE_SIZE 48 #elif defined(__arm__) 49 constexpr uint64_t STACK_SIZE = 1 << 15; 50 #else 51 constexpr uint64_t STACK_SIZE = 1 << 20; 52 #endif 53 54 using CoCtx = struct co2_context; 55 56 struct CoRoutineEnv { 57 CoRoutine* runningCo; 58 CoCtx schCtx; 59 const std::function<bool(ffrt::TaskCtx*)>* pending; 60 }; 61 62 struct StackMem { 63 uint64_t size; 64 size_t magic; 65 uint8_t stk[8]; 66 }; 67 68 struct CoRoutine { 69 std::atomic_int status; 70 CoRoutineEnv* thEnv; 71 ffrt::TaskCtx* task; 72 CoCtx ctx; 73 StackMem stkMem; 74 }; 75 76 struct CoStackAttr { 77 public: 78 explicit CoStackAttr(uint64_t coSize = STACK_SIZE, CoStackProtectType coType = 79 CoStackProtectType::CO_STACK_WEAK_PROTECT) 80 { 81 size = coSize; 82 type = coType; 83 } ~CoStackAttrCoStackAttr84 ~CoStackAttr() {} 85 uint64_t size; 86 CoStackProtectType type; 87 88 static inline CoStackAttr* Instance(uint64_t coSize = STACK_SIZE, 89 CoStackProtectType coType = CoStackProtectType::CO_STACK_WEAK_PROTECT) 90 { 91 static CoStackAttr inst(coSize, coType); 92 return &inst; 93 } 94 }; 95 96 void CoWorkerExit(void); 97 98 void CoStart(ffrt::TaskCtx* task); 99 void CoYield(void); 100 101 void CoWait(const std::function<bool(ffrt::TaskCtx*)>& pred); 102 void CoWake(ffrt::TaskCtx* task, bool timeOut); 103 104 #endif 105