1/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7    http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#include "tensorflow/core/kernels/training_op_helpers.h"
17
18namespace tensorflow {
19
20mutex* GetTrainingVariableMutex(OpKernelContext* ctx, int input) {
21  if (ctx->input_dtype(input) == DT_RESOURCE) {
22    Var* var;
23    if (LookupResource(ctx, HandleFromInput(ctx, input), &var).ok()) {
24      return var->mu();
25    } else {
26      ctx->CtxFailureWithWarning(
27          errors::Internal("Invalid variable reference."));
28      return nullptr;
29    }
30  }
31  return ctx->input_ref_mutex(input);
32}
33
34// MaybeLockVariableInputMutexesInOrder is a helper function to acquire mutexes
35// in address order to mitigate deadlock.  Returns a vector of acquired mutexes.
36// Safe to pass duplicates - will only lock each distinct mutex once.  If
37// do_lock is false, returns immediately.  Note that this silently doesn't lock
38// mutexes for invalid variable references; in all usages this is followed by
39// GetInputTensor which will signal a failure.
40std::vector<mutex_lock> MaybeLockVariableInputMutexesInOrder(
41    OpKernelContext* ctx, bool do_lock, const std::vector<int>& input_ids) {
42  std::vector<mutex_lock> locks;
43  if (!do_lock) {
44    return locks;
45  }
46  std::vector<mutex*> mutexes;
47  std::vector<int> acquire_order;
48  for (auto input : input_ids) {
49    mutex* mutex = GetTrainingVariableMutex(ctx, input);
50    // Only lock each mutex once if duplicates exist (n^2 but n is 2 or 3).
51    if (std::find(mutexes.begin(), mutexes.end(), mutex) == mutexes.end()) {
52      acquire_order.push_back(mutexes.size());
53      mutexes.push_back(mutex);
54    }
55  }
56  std::sort(acquire_order.begin(), acquire_order.end(),
57            [&mutexes](int a, int b) { return mutexes[a] < mutexes[b]; });
58
59  for (auto input : acquire_order) {
60    mutex* mu = GetTrainingVariableMutex(ctx, input);
61    if (mu != nullptr) {
62      locks.emplace_back(*mu);
63    }
64  }
65  return locks;
66}
67
68void MaybeForwardRefInputToRefOutput(OpKernelContext* ctx, int input,
69                                     int output) {
70  if (ctx->input_dtype(input) != DT_RESOURCE) {
71    ctx->forward_ref_input_to_ref_output(input, output);
72  }
73}
74
75}  // end namespace tensorflow
76