Home | History | Annotate | Download | only in iomgr
      1 /*
      2  *
      3  * Copyright 2015 gRPC authors.
      4  *
      5  * Licensed under the Apache License, Version 2.0 (the "License");
      6  * you may not use this file except in compliance with the License.
      7  * You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  * Unless required by applicable law or agreed to in writing, software
     12  * distributed under the License is distributed on an "AS IS" BASIS,
     13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  * See the License for the specific language governing permissions and
     15  * limitations under the License.
     16  *
     17  */
     18 
     19 #ifndef GRPC_CORE_LIB_IOMGR_EXEC_CTX_H
     20 #define GRPC_CORE_LIB_IOMGR_EXEC_CTX_H
     21 
     22 #include <grpc/support/port_platform.h>
     23 
     24 #include <grpc/support/atm.h>
     25 #include <grpc/support/cpu.h>
     26 #include <grpc/support/log.h>
     27 
     28 #include "src/core/lib/gpr/tls.h"
     29 #include "src/core/lib/gprpp/fork.h"
     30 #include "src/core/lib/iomgr/closure.h"
     31 
     32 typedef int64_t grpc_millis;
     33 
     34 #define GRPC_MILLIS_INF_FUTURE INT64_MAX
     35 #define GRPC_MILLIS_INF_PAST INT64_MIN
     36 
     37 /** A workqueue represents a list of work to be executed asynchronously.
     38     Forward declared here to avoid a circular dependency with workqueue.h. */
     39 typedef struct grpc_workqueue grpc_workqueue;
     40 typedef struct grpc_combiner grpc_combiner;
     41 
     42 /* This exec_ctx is ready to return: either pre-populated, or cached as soon as
     43    the finish_check returns true */
     44 #define GRPC_EXEC_CTX_FLAG_IS_FINISHED 1
     45 /* The exec_ctx's thread is (potentially) owned by a call or channel: care
     46    should be given to not delete said call/channel from this exec_ctx */
     47 #define GRPC_EXEC_CTX_FLAG_THREAD_RESOURCE_LOOP 2
     48 /* This exec ctx was initialized by an internal thread, and should not
     49    be counted by fork handlers */
     50 #define GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD 4
     51 
     52 extern grpc_closure_scheduler* grpc_schedule_on_exec_ctx;
     53 
     54 gpr_timespec grpc_millis_to_timespec(grpc_millis millis, gpr_clock_type clock);
     55 grpc_millis grpc_timespec_to_millis_round_down(gpr_timespec timespec);
     56 grpc_millis grpc_timespec_to_millis_round_up(gpr_timespec timespec);
     57 
     58 namespace grpc_core {
     59 /** Execution context.
     60  *  A bag of data that collects information along a callstack.
     61  *  It is created on the stack at public API entry points, and stored internally
     62  *  as a thread-local variable.
     63  *
     64  *  Generally, to create an exec_ctx instance, add the following line at the top
     65  *  of the public API entry point or at the start of a thread's work function :
     66  *
     67  *  grpc_core::ExecCtx exec_ctx;
     68  *
     69  *  Access the created ExecCtx instance using :
     70  *  grpc_core::ExecCtx::Get()
     71  *
     72  *  Specific responsibilities (this may grow in the future):
     73  *  - track a list of work that needs to be delayed until the top of the
     74  *    call stack (this provides a convenient mechanism to run callbacks
     75  *    without worrying about locking issues)
     76  *  - provide a decision maker (via IsReadyToFinish) that provides a
     77  *    signal as to whether a borrowed thread should continue to do work or
     78  *    should actively try to finish up and get this thread back to its owner
     79  *
     80  *  CONVENTIONS:
     81  *  - Instance of this must ALWAYS be constructed on the stack, never
     82  *    heap allocated.
     83  *  - Exactly one instance of ExecCtx must be created per thread. Instances must
     84  *    always be called exec_ctx.
     85  *  - Do not pass exec_ctx as a parameter to a function. Always access it using
     86  *    grpc_core::ExecCtx::Get().
     87  */
     88 class ExecCtx {
     89  public:
     90   /** Default Constructor */
     91 
     92   ExecCtx() : flags_(GRPC_EXEC_CTX_FLAG_IS_FINISHED) {
     93     grpc_core::Fork::IncExecCtxCount();
     94     Set(this);
     95   }
     96 
     97   /** Parameterised Constructor */
     98   ExecCtx(uintptr_t fl) : flags_(fl) {
     99     if (!(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD & flags_)) {
    100       grpc_core::Fork::IncExecCtxCount();
    101     }
    102     Set(this);
    103   }
    104 
    105   /** Destructor */
    106   virtual ~ExecCtx() {
    107     flags_ |= GRPC_EXEC_CTX_FLAG_IS_FINISHED;
    108     Flush();
    109     Set(last_exec_ctx_);
    110     if (!(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD & flags_)) {
    111       grpc_core::Fork::DecExecCtxCount();
    112     }
    113   }
    114 
    115   /** Disallow copy and assignment operators */
    116   ExecCtx(const ExecCtx&) = delete;
    117   ExecCtx& operator=(const ExecCtx&) = delete;
    118 
    119   /** Return starting_cpu. This is only required for stats collection and is
    120    *  hence only defined if GRPC_COLLECT_STATS is enabled.
    121    */
    122 #if defined(GRPC_COLLECT_STATS) || !defined(NDEBUG)
    123   unsigned starting_cpu() const { return starting_cpu_; }
    124 #endif /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */
    125 
    126   struct CombinerData {
    127     /* currently active combiner: updated only via combiner.c */
    128     grpc_combiner* active_combiner;
    129     /* last active combiner in the active combiner list */
    130     grpc_combiner* last_combiner;
    131   };
    132 
    133   /** Only to be used by grpc-combiner code */
    134   CombinerData* combiner_data() { return &combiner_data_; }
    135 
    136   /** Return pointer to grpc_closure_list */
    137   grpc_closure_list* closure_list() { return &closure_list_; }
    138 
    139   /** Return flags */
    140   uintptr_t flags() { return flags_; }
    141 
    142   /** Checks if there is work to be done */
    143   bool HasWork() {
    144     return combiner_data_.active_combiner != nullptr ||
    145            !grpc_closure_list_empty(closure_list_);
    146   }
    147 
    148   /** Flush any work that has been enqueued onto this grpc_exec_ctx.
    149    *  Caller must guarantee that no interfering locks are held.
    150    *  Returns true if work was performed, false otherwise.
    151    */
    152   bool Flush();
    153 
    154   /** Returns true if we'd like to leave this execution context as soon as
    155    *  possible: useful for deciding whether to do something more or not
    156    *  depending on outside context.
    157    */
    158   bool IsReadyToFinish() {
    159     if ((flags_ & GRPC_EXEC_CTX_FLAG_IS_FINISHED) == 0) {
    160       if (CheckReadyToFinish()) {
    161         flags_ |= GRPC_EXEC_CTX_FLAG_IS_FINISHED;
    162         return true;
    163       }
    164       return false;
    165     } else {
    166       return true;
    167     }
    168   }
    169 
    170   /** Returns the stored current time relative to start if valid,
    171    *  otherwise refreshes the stored time, sets it valid and returns the new
    172    *  value.
    173    */
    174   grpc_millis Now();
    175 
    176   /** Invalidates the stored time value. A new time value will be set on calling
    177    *  Now().
    178    */
    179   void InvalidateNow() { now_is_valid_ = false; }
    180 
    181   /** To be used only by shutdown code in iomgr */
    182   void SetNowIomgrShutdown() {
    183     now_ = GRPC_MILLIS_INF_FUTURE;
    184     now_is_valid_ = true;
    185   }
    186 
    187   /** To be used only for testing.
    188    *  Sets the now value.
    189    */
    190   void TestOnlySetNow(grpc_millis new_val) {
    191     now_ = new_val;
    192     now_is_valid_ = true;
    193   }
    194 
    195   static void TestOnlyGlobalInit(gpr_timespec new_val);
    196 
    197   /** Global initialization for ExecCtx. Called by iomgr. */
    198   static void GlobalInit(void);
    199 
    200   /** Global shutdown for ExecCtx. Called by iomgr. */
    201   static void GlobalShutdown(void) { gpr_tls_destroy(&exec_ctx_); }
    202 
    203   /** Gets pointer to current exec_ctx. */
    204   static ExecCtx* Get() {
    205     return reinterpret_cast<ExecCtx*>(gpr_tls_get(&exec_ctx_));
    206   }
    207 
    208   static void Set(ExecCtx* exec_ctx) {
    209     gpr_tls_set(&exec_ctx_, reinterpret_cast<intptr_t>(exec_ctx));
    210   }
    211 
    212  protected:
    213   /** Check if ready to finish. */
    214   virtual bool CheckReadyToFinish() { return false; }
    215 
    216   /** Disallow delete on ExecCtx. */
    217   static void operator delete(void* p) { abort(); }
    218 
    219  private:
    220   /** Set exec_ctx_ to exec_ctx. */
    221 
    222   grpc_closure_list closure_list_ = GRPC_CLOSURE_LIST_INIT;
    223   CombinerData combiner_data_ = {nullptr, nullptr};
    224   uintptr_t flags_;
    225 
    226 #if defined(GRPC_COLLECT_STATS) || !defined(NDEBUG)
    227   unsigned starting_cpu_ = gpr_cpu_current_cpu();
    228 #endif /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */
    229 
    230   bool now_is_valid_ = false;
    231   grpc_millis now_ = 0;
    232 
    233   GPR_TLS_CLASS_DECL(exec_ctx_);
    234   ExecCtx* last_exec_ctx_ = Get();
    235 };
    236 }  // namespace grpc_core
    237 
    238 #endif /* GRPC_CORE_LIB_IOMGR_EXEC_CTX_H */
    239