Welcome to mirror list, hosted at ThFree Co, Russian Federation.

safe_byte_ranges.ipp « impl « detail « v2.0 « llfio « include - github.com/windirstat/llfio.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 473dc65bb32a03107347f0f8a09cf45e2c22895f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/* Safe small actor read-write lock
(C) 2017 Niall Douglas <http://www.nedproductions.biz/> (12 commits)
File Created: Aug 2017


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 in the accompanying file
Licence.txt or 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.


Distributed under the Boost Software License, Version 1.0.
    (See accompanying file Licence.txt or copy at
          http://www.boost.org/LICENSE_1_0.txt)
*/

#if defined(_WIN32)
#error This file should never be compiled on Windows.
#endif

#include "../../algorithm/shared_fs_mutex/safe_byte_ranges.hpp"

#include "quickcpplib/uint128.hpp"
#include "quickcpplib/utils/thread.hpp"

#include <fcntl.h>
#include <sys/stat.h>

#include <condition_variable>
#include <mutex>
#include <unordered_map>

LLFIO_V2_NAMESPACE_BEGIN

namespace algorithm
{
  namespace shared_fs_mutex
  {
    namespace detail
    {
#if 0
      struct _byte_ranges : public byte_ranges
      {
        using byte_ranges::byte_ranges;
        using byte_ranges::_lock;
        _byte_ranges(byte_ranges &&o)
            : byte_ranges(std::move(o))
        {
        }
      };
#endif
      class threaded_byte_ranges : public shared_fs_mutex
      {
      public:
        using entity_type = shared_fs_mutex::entity_type;
        using entities_type = shared_fs_mutex::entities_type;

      private:
        std::mutex _m;
        file_handle _h;
        std::condition_variable _changed;
        struct _entity_info
        {
          std::vector<unsigned> reader_tids;  // thread ids of all shared lock holders
          unsigned writer_tid;                // thread id of exclusive lock holder
          file_handle::extent_guard filelock;   // exclusive if writer_tid, else shared
          _entity_info(bool exclusive, unsigned tid, file_handle::extent_guard _filelock)
              : writer_tid(exclusive ? tid : 0)
              , filelock(std::move(_filelock))
          {
            reader_tids.reserve(4);
            if(!exclusive)
            {
              reader_tids.push_back(tid);
            }
          }
        };
        std::unordered_map<entity_type::value_type, _entity_info> _thread_locks;  // entity to thread lock
        // _m mutex must be held on entry!
        void _unlock(unsigned mythreadid, entity_type entity)
        {
          auto it = _thread_locks.find(entity.value);  // NOLINT
          assert(it != _thread_locks.end());
          assert(it->second.writer_tid == mythreadid || it->second.writer_tid == 0);
          if(it->second.writer_tid == mythreadid)
          {
            if(!it->second.reader_tids.empty())
            {
              // Downgrade the lock from exclusive to shared
              auto l = _h.lock_range(entity.value, 1, file_handle::lock_kind::shared).value();
#ifndef _WIN32
              // On POSIX byte range locks replace
              it->second.filelock.release();
#endif
              it->second.filelock = std::move(l);
              it->second.writer_tid = 0;
              return;
            }
          }
          else
          {
            // Remove me from reader tids
            auto reader_tid_it = std::find(it->second.reader_tids.begin(), it->second.reader_tids.end(), mythreadid);
            assert(reader_tid_it != it->second.reader_tids.end());
            if(reader_tid_it != it->second.reader_tids.end())
            {
              // We don't care about the order, so fastest is to swap this tid with final tid and resize down
              std::swap(*reader_tid_it, it->second.reader_tids.back());
              it->second.reader_tids.pop_back();
            }
          }
          if(it->second.reader_tids.empty())
          {
            // Release the lock and delete this entity from the map
            _h.unlock_range(entity.value, 1);
            _thread_locks.erase(it);
          }
        }

      public:
        threaded_byte_ranges(const path_handle &base, path_view lockfile)
        {
          LLFIO_LOG_FUNCTION_CALL(0);
          _h = file_handle::file(base, lockfile, file_handle::mode::write, file_handle::creation::if_needed, file_handle::caching::temporary).value();
        }
        LLFIO_HEADERS_ONLY_VIRTUAL_SPEC result<void> _lock(entities_guard &out, deadline d, bool spin_not_sleep) noexcept final
        {
          LLFIO_LOG_FUNCTION_CALL(this);
          unsigned mythreadid = QUICKCPPLIB_NAMESPACE::utils::thread::this_thread_id();
          std::chrono::steady_clock::time_point began_steady;
          std::chrono::system_clock::time_point end_utc;
          if(d)
          {
            if((d).steady)
            {
              began_steady = std::chrono::steady_clock::now();
            }
            else
            {
              end_utc = (d).to_time_point();
            }
          }
          // Fire this if an error occurs
          auto disableunlock = undoer([&] { out.release(); });
          size_t n;
          for(;;)
          {
            auto was_contended = static_cast<size_t>(-1);
            bool pls_sleep = true;
            std::unique_lock<decltype(_m)> guard(_m);
            {
              auto undo = undoer([&] {
                // 0 to (n-1) need to be closed
                if(n > 0)
                {
                  --n;
                  // Now 0 to n needs to be closed
                  for(; n > 0; n--)
                  {
                    _unlock(mythreadid, out.entities[n]);
                  }
                  _unlock(mythreadid, out.entities[0]);
                }
              });
              for(n = 0; n < out.entities.size(); n++)
              {
                auto it = _thread_locks.find(out.entities[n].value);
                if(it == _thread_locks.end())
                {
                  // This entity has not been locked before
                  deadline nd;
                  // Only for very first entity will we sleep until its lock becomes available
                  if(n != 0u)
                  {
                    nd = deadline(std::chrono::seconds(0));
                  }
                  else
                  {
                    nd = deadline();
                    if(d)
                    {
                      if((d).steady)
                      {
                        std::chrono::nanoseconds ns = std::chrono::duration_cast<std::chrono::nanoseconds>((began_steady + std::chrono::nanoseconds((d).nsecs)) - std::chrono::steady_clock::now());
                        if(ns.count() < 0)
                        {
                          (nd).nsecs = 0;
                        }
                        else
                        {
                          (nd).nsecs = ns.count();
                        }
                      }
                      else
                      {
                        (nd) = (d);
                      }
                    }
                  }
                  // Allow other threads to use this threaded_byte_ranges
                  guard.unlock();
                  auto outcome = _h.lock_range(out.entities[n].value, 1, (out.entities[n].exclusive != 0u) ? file_handle::lock_kind::exclusive : file_handle::lock_kind::shared, nd);
                  guard.lock();
                  if(!outcome)
                  {
                    was_contended = n;
                    pls_sleep = false;
                    goto failed;
                  }
                  // Did another thread already fill this in?
                  it = _thread_locks.find(out.entities[n].value);
                  if(it == _thread_locks.end())
                  {
                    it = _thread_locks.insert(std::make_pair(static_cast<entity_type::value_type>(out.entities[n].value), _entity_info(out.entities[n].exclusive != 0u, mythreadid, std::move(outcome).value()))).first;
                    continue;
                  }
                  // Otherwise throw away the presumably shared superfluous byte range lock
                  assert(!out.entities[n].exclusive);
                }

                // If we are here, then this entity has been locked by someone before
                auto reader_tid_it = std::find(it->second.reader_tids.begin(), it->second.reader_tids.end(), mythreadid);
                bool already_have_shared_lock = (reader_tid_it != it->second.reader_tids.end());
                // Is somebody already locking this entity exclusively?
                if(it->second.writer_tid != 0)
                {
                  if(it->second.writer_tid == mythreadid)
                  {
                    // If I am relocking myself, return deadlock
                    if((out.entities[n].exclusive != 0u) || already_have_shared_lock)
                    {
                      return errc::resource_deadlock_would_occur;
                    }
                    // Otherwise just add myself to the reader list
                    it->second.reader_tids.push_back(mythreadid);
                    continue;
                  }
                  // Some other thread holds the exclusive lock, so we cannot take it
                  was_contended = n;
                  pls_sleep = true;
                  goto failed;
                }
                // If reached here, nobody is holding the exclusive lock
                assert(it->second.writer_tid == 0);
                if(out.entities[n].exclusive == 0u)
                {
                  // If I am relocking myself, return deadlock
                  if(already_have_shared_lock)
                  {
                    return errc::resource_deadlock_would_occur;
                  }
                  // Otherwise just add myself to the reader list
                  it->second.reader_tids.push_back(mythreadid);
                  continue;
                }
                // We are thus now upgrading shared to exclusive
                assert(out.entities[n].exclusive);
                deadline nd;
                // Only for very first entity will we sleep until its lock becomes available
                if(n != 0u)
                {
                  nd = deadline(std::chrono::seconds(0));
                }
                else
                {
                  nd = deadline();
                  if(d)
                  {
                    if((d).steady)
                    {
                      std::chrono::nanoseconds ns = std::chrono::duration_cast<std::chrono::nanoseconds>((began_steady + std::chrono::nanoseconds((d).nsecs)) - std::chrono::steady_clock::now());
                      if(ns.count() < 0)
                      {
                        (nd).nsecs = 0;
                      }
                      else
                      {
                        (nd).nsecs = ns.count();
                      }
                    }
                    else
                    {
                      (nd) = (d);
                    }
                  }
                }
                // Allow other threads to use this threaded_byte_ranges
                guard.unlock();
                auto outcome = _h.lock_range(out.entities[n].value, 1, file_handle::lock_kind::exclusive, nd);
                guard.lock();
                if(!outcome)
                {
                  was_contended = n;
                  goto failed;
                }
// unordered_map iterators do not invalidate, so no need to refresh
#ifndef _WIN32
                // On POSIX byte range locks replace
                it->second.filelock.release();
#endif
                it->second.filelock = std::move(outcome).value();
                it->second.writer_tid = mythreadid;
              }
              // Dismiss unwind of thread locking and return success
              undo.dismiss();
              disableunlock.dismiss();
              return success();
            }
          failed:
            if(d)
            {
              if((d).steady)
              {
                if(std::chrono::steady_clock::now() >= (began_steady + std::chrono::nanoseconds((d).nsecs)))
                {
                  return errc::timed_out;
                }
              }
              else
              {
                if(std::chrono::system_clock::now() >= end_utc)
                {
                  return errc::timed_out;
                }
              }
            }
            // Move was_contended to front and randomise rest of out.entities
            std::swap(out.entities[was_contended], out.entities[0]);
            auto front = out.entities.begin();
            ++front;
            QUICKCPPLIB_NAMESPACE::algorithm::small_prng::random_shuffle(front, out.entities.end());
            if(pls_sleep && !spin_not_sleep)
            {
              // Sleep until the thread locks next change
              if((d).steady)
              {
                std::chrono::nanoseconds ns = std::chrono::duration_cast<std::chrono::nanoseconds>((began_steady + std::chrono::nanoseconds((d).nsecs)) - std::chrono::steady_clock::now());
                _changed.wait_for(guard, ns);
              }
              else
              {
                _changed.wait_until(guard, d.to_time_point());
              }
            }
          }
          // return success();
        }
        LLFIO_HEADERS_ONLY_VIRTUAL_SPEC void unlock(entities_type entities, unsigned long long /*unused*/) noexcept final
        {
          LLFIO_LOG_FUNCTION_CALL(this);
          unsigned mythreadid = QUICKCPPLIB_NAMESPACE::utils::thread::this_thread_id();
          std::unique_lock<decltype(_m)> guard(_m);
          for(auto &entity : entities)
          {
            _unlock(mythreadid, entity);
          }
        }
      };
      struct threaded_byte_ranges_list
      {
        using key_type = QUICKCPPLIB_NAMESPACE::integers128::uint128;
        std::mutex lock;
        std::unordered_map<key_type, std::weak_ptr<threaded_byte_ranges>, QUICKCPPLIB_NAMESPACE::integers128::uint128_hasher> db;
      };
      inline threaded_byte_ranges_list &tbrlist()
      {
        static threaded_byte_ranges_list v;
        return v;
      }
      LLFIO_HEADERS_ONLY_FUNC_SPEC result<std::shared_ptr<shared_fs_mutex>> inode_to_fs_mutex(const path_handle &base, path_view lockfile) noexcept
      {
        try
        {
          path_view::c_str<> zpath(lockfile);
          struct stat s
          {
          };
          if(-1 == ::fstatat(base.is_valid() ? base.native_handle().fd : AT_FDCWD, zpath.buffer, &s, AT_SYMLINK_NOFOLLOW))
          {
            return posix_error();
          }
          threaded_byte_ranges_list::key_type key;
          key.as_longlongs[0] = s.st_ino;
          key.as_longlongs[1] = s.st_dev;
          std::shared_ptr<threaded_byte_ranges> ret;
          auto &list = tbrlist();
          std::lock_guard<decltype(list.lock)> g(list.lock);
          auto it = list.db.find(key);
          if(it != list.db.end())
          {
            ret = it->second.lock();
            if(ret)
            {
              return ret;
            }
          }
          ret = std::make_shared<threaded_byte_ranges>(base, lockfile);
          if(it != list.db.end())
          {
            it->second = std::weak_ptr<threaded_byte_ranges>(ret);
          }
          else
          {
            list.db.insert({key, std::weak_ptr<threaded_byte_ranges>(ret)});
          }
          return ret;
        }
        catch(...)
        {
          return error_from_exception();
        }
      }
    }  // namespace detail
  }    // namespace shared_fs_mutex
}  // namespace algorithm

LLFIO_V2_NAMESPACE_END