Ticket #9615: MemoryTransactions.hpp

File MemoryTransactions.hpp, 15.3 KB (added by Niall Douglas, 9 years ago)
Line 
1/* MemoryTransactions.hpp
2Provides yet another mechanism for serialising memory
3(C) 2013 Niall Douglas http://www.nedprod.com/
4File Created: Sept 2013
5*/
6
7#ifndef BOOST_AFIO_MEMORY_TRANSACTIONS_HPP
8#define BOOST_AFIO_MEMORY_TRANSACTIONS_HPP
9
10// Turn this on if you have a compiler which understands __transaction_relaxed
11//#define BOOST_HAVE_TRANSACTIONAL_MEMORY_COMPILER
12
13#ifndef BOOST_AFIO_COMPILING_FOR_GCOV // transaction support murders poor old gcov
14// Turn this on if you want to use Haswell TSX where available
15#if (defined(_MSC_VER) && _MSC_VER >= 1700 && ( defined(_M_IX86) || defined(_M_X64) )) || (defined(__GNUC__) && ( defined(__i386__) || defined(__x86_64__) ))
16#define BOOST_USING_INTEL_TSX
17#endif
18#endif
19
20#include "std_atomic_mutex_chrono.hpp"
21
22#ifndef BOOST_SMT_PAUSE
23#if defined(_MSC_VER) && _MSC_VER >= 1310 && ( defined(_M_IX86) || defined(_M_X64) )
24
25extern "C" void _mm_pause();
26#pragma intrinsic( _mm_pause )
27
28#define BOOST_SMT_PAUSE _mm_pause();
29
30#elif defined(__GNUC__) && ( defined(__i386__) || defined(__x86_64__) )
31
32#define BOOST_SMT_PAUSE __asm__ __volatile__( "rep; nop" : : : "memory" );
33
34#endif
35#endif
36
37namespace boost
38{
39 namespace afio
40 {
41 namespace detail
42 {
43 /*! \class spinlock
44
45 So what's wrong with boost/smart_ptr/detail/spinlock.hpp then, and why
46 reinvent the wheel?
47
48 1. Non-configurable spin. AFIO needs a bigger spin than smart_ptr provides.
49
50 2. AFIO is C++ 11, and therefore can implement this in pure C++ 11 atomics.
51
52 3. I don't much care for doing writes during the spin. It generates an
53 unnecessary amount of cache line invalidation traffic. Better to spin-read
54 and only write when the read suggests you might have a chance.
55
56 4. The other spin lock doesn't use Intel TSX yet.
57 */
58 template<typename T> struct spinlockbase
59 {
60 volatile atomic<T> v;
61 spinlockbase() BOOST_NOEXCEPT_OR_NOTHROW : v(0) { }
62 bool try_lock() BOOST_NOEXCEPT_OR_NOTHROW
63 {
64 if(v.load()) // Avoid unnecessary cache line invalidation traffic
65 return false;
66 T expected=0;
67 return v.compare_exchange_weak(expected, 1);
68 }
69 void unlock() BOOST_NOEXCEPT_OR_NOTHROW
70 {
71 v.store(0);
72 }
73 bool int_yield(size_t) BOOST_NOEXCEPT_OR_NOTHROW{ return false; }
74 };
75 template<size_t spins> struct spins_to_transact
76 {
77 template<class parenttype> struct policy : parenttype
78 {
79 static BOOST_CONSTEXPR_OR_CONST size_t spins_to_transact=spins;
80 };
81 };
82 template<size_t spins, bool use_pause=true> struct spins_to_loop
83 {
84 template<class parenttype> struct policy : parenttype
85 {
86 static BOOST_CONSTEXPR_OR_CONST size_t spins_to_loop=spins;
87 bool int_yield(size_t n) BOOST_NOEXCEPT_OR_NOTHROW
88 {
89 if(parenttype::int_yield(n)) return true;
90 if(n>=spins) return false;
91 if(use_pause)
92 {
93#ifdef BOOST_SMT_PAUSE
94 BOOST_SMT_PAUSE;
95#endif
96 }
97 return true;
98 }
99 };
100 };
101 template<size_t spins> struct spins_to_yield
102 {
103 template<class parenttype> struct policy : parenttype
104 {
105 static BOOST_CONSTEXPR_OR_CONST size_t spins_to_yield=spins;
106 bool int_yield(size_t n) BOOST_NOEXCEPT_OR_NOTHROW
107 {
108 if(parenttype::int_yield(n)) return true;
109 if(n>=spins) return false;
110 boost::afio::this_thread::yield();
111 return true;
112 }
113 };
114 };
115 struct spins_to_sleep
116 {
117 template<class parenttype> struct policy : parenttype
118 {
119 bool int_yield(size_t n) BOOST_NOEXCEPT_OR_NOTHROW
120 {
121 if(parenttype::int_yield(n)) return true;
122 boost::afio::this_thread::sleep_for(boost::afio::chrono::milliseconds(1));
123 return true;
124 }
125 };
126 };
127 struct null_spin_policy
128 {
129 template<class parenttype> struct policy : parenttype
130 {
131 };
132 };
133 template<typename T, template<class> class spinpolicy1=spins_to_transact<5>::policy, template<class> class spinpolicy2=spins_to_loop<125>::policy, template<class> class spinpolicy3=spins_to_yield<250>::policy, template<class> class spinpolicy4=spins_to_sleep::policy> class spinlock : public spinpolicy4<spinpolicy3<spinpolicy2<spinpolicy1<spinlockbase<T>>>>>
134 {
135 typedef spinpolicy4<spinpolicy3<spinpolicy2<spinpolicy1<spinlockbase<T>>>>> parenttype;
136 public:
137 void lock() BOOST_NOEXCEPT_OR_NOTHROW
138 {
139 for(size_t n=0;; n++)
140 {
141 if(parenttype::try_lock())
142 return;
143 parenttype::int_yield(n);
144 }
145 }
146 };
147
148#ifndef BOOST_BEGIN_MEMORY_TRANSACTION
149#ifdef BOOST_HAVE_TRANSACTIONAL_MEMORY_COMPILER
150#define BOOST_BEGIN_MEMORY_TRANSACTION(lockable) __transaction_relaxed
151#define BOOST_END_MEMORY_TRANSACTION(lockable)
152#elif defined(BOOST_USING_INTEL_TSX)
153
154#define BOOST_AFIO_XBEGIN_STARTED (~0u)
155#define BOOST_AFIO_XABORT_EXPLICIT (1 << 0)
156#define BOOST_AFIO_XABORT_RETRY (1 << 1)
157#define BOOST_AFIO_XABORT_CONFLICT (1 << 2)
158#define BOOST_AFIO_XABORT_CAPACITY (1 << 3)
159#define BOOST_AFIO_XABORT_DEBUG (1 << 4)
160#define BOOST_AFIO_XABORT_NESTED (1 << 5)
161#define BOOST_AFIO_XABORT_CODE(x) ((unsigned char)(((x) >> 24) & 0xFF))
162
163#if defined(_MSC_VER)
164 // Declare MSVC intrinsics
165 extern "C" unsigned int _xbegin(void);
166 extern "C" void _xend(void);
167 extern "C" void _xabort(const unsigned int);
168 extern "C" unsigned char _xtest(void);
169#define BOOST_AFIO_XBEGIN(...) _xbegin(__VA_ARGS__)
170#define BOOST_AFIO_XEND(...) _xend(__VA_ARGS__)
171#define BOOST_AFIO_XABORT(...) _xabort(__VA_ARGS__)
172#define BOOST_AFIO_XTEST(...) _xtest(__VA_ARGS__)
173
174#elif defined(__GNUC__) && ( defined(__i386__) || defined(__x86_64__) )
175
176 // Hack the bytes codes in for older compilers to avoid needing to compile with -mrtm
177 namespace { // prevent any collisions with <immintrin.h>
178 static __attribute__((__always_inline__)) inline unsigned int _xbegin() BOOST_NOEXCEPT_OR_NOTHROW
179 {
180 unsigned int ret = BOOST_AFIO_XBEGIN_STARTED;
181 asm volatile(".byte 0xc7,0xf8 ; .long 0" : "+a" (ret) :: "memory");
182 return ret;
183 }
184
185 static __attribute__((__always_inline__)) inline unsigned char _xtest() BOOST_NOEXCEPT_OR_NOTHROW
186 {
187 unsigned char out;
188 asm volatile(".byte 0x0f,0x01,0xd6 ; setnz %0" : "=r" (out) :: "memory");
189 return out;
190 }
191 }
192#define BOOST_AFIO_XBEGIN(...) _xbegin(__VA_ARGS__)
193#define BOOST_AFIO_XEND(...) asm volatile(".byte 0x0f,0x01,0xd5" ::: "memory")
194#define BOOST_AFIO_XABORT(status) asm volatile(".byte 0xc6,0xf8,%P0" :: "i" (status) : "memory")
195#define BOOST_AFIO_XTEST(...) _xtest(__VA_ARGS__)
196#endif
197
198 // Adapted from http://software.intel.com/en-us/articles/how-to-detect-new-instruction-support-in-the-4th-generation-intel-core-processor-family
199 namespace intel_stuff
200 {
201 inline void run_cpuid(uint32_t eax, uint32_t ecx, uint32_t* abcd) BOOST_NOEXCEPT_OR_NOTHROW
202 {
203#if defined(_MSC_VER)
204 __cpuidex((int *) abcd, eax, ecx);
205#else
206 uint32_t ebx=0, edx=0;
207# if defined( __i386__ ) && defined ( __PIC__ )
208 /* in case of PIC under 32-bit EBX cannot be clobbered */
209 __asm__("movl %%ebx, %%edi \n\t cpuid \n\t xchgl %%ebx, %%edi" : "=D" (ebx),
210# else
211 __asm__("cpuid" : "+b" (ebx),
212# endif
213 "+a" (eax), "+c" (ecx), "=d" (edx));
214 abcd[0] = eax; abcd[1] = ebx; abcd[2] = ecx; abcd[3] = edx;
215#endif
216 }
217 inline bool have_intel_tsx_support() BOOST_NOEXCEPT_OR_NOTHROW
218 {
219 static int result;
220 if(result) return result==2;
221
222 uint32_t abcd[4];
223 uint32_t rtm_mask = (1 << 11);
224
225 /* CPUID.(EAX=07H, ECX=0H):EBX.RTM[bit 11]==1 */
226 run_cpuid(7, 0, abcd);
227 if((abcd[1] & rtm_mask) != rtm_mask)
228 result=1;
229 else
230 result=2;
231 return result==2;
232 }
233 }
234
235 template<class T> struct get_spins_to_transact
236 {
237 static BOOST_CONSTEXPR_OR_CONST size_t value=4;
238 };
239 template<class T, template<class> class spinpolicy1, template<class> class spinpolicy2, template<class> class spinpolicy3, template<class> class spinpolicy4> struct get_spins_to_transact<spinlock<T, spinpolicy1, spinpolicy2, spinpolicy3, spinpolicy4>>
240 {
241 static BOOST_CONSTEXPR_OR_CONST size_t value=spinlock<T, spinpolicy1, spinpolicy2, spinpolicy3, spinpolicy4>::spins_to_transact;
242 };
243 template<class T> inline bool is_lockable_locked(T &lockable) BOOST_NOEXCEPT_OR_NOTHROW
244 {
245 if(lockable.try_lock())
246 {
247 lockable.unlock();
248 return true;
249 }
250 return false;
251 }
252 template<class T, template<class> class spinpolicy1, template<class> class spinpolicy2, template<class> class spinpolicy3, template<class> class spinpolicy4> inline bool is_lockable_locked(spinlock<T, spinpolicy1, spinpolicy2, spinpolicy3, spinpolicy4> &lockable) BOOST_NOEXCEPT_OR_NOTHROW
253 {
254 return 1==lockable.v.load();
255 }
256 template<class T> struct intel_tsx_transaction
257 {
258 T &lockable;
259 int dismissed; // 0=disabled, 1=abort on exception throw, 2=commit, 3=traditional locks
260 intel_tsx_transaction(T &_lockable) : lockable(_lockable), dismissed(0)
261 {
262 // Try four times
263 size_t spins_to_transact=get_spins_to_transact<T>::value;
264 for(size_t n=0; n<spins_to_transact; n++)
265 {
266 unsigned state=BOOST_AFIO_XABORT_CAPACITY;
267 if(intel_stuff::have_intel_tsx_support())
268 state=BOOST_AFIO_XBEGIN(); // start transaction, or cope with abort
269 if(BOOST_AFIO_XBEGIN_STARTED==state)
270 {
271 if(!is_lockable_locked(lockable))
272 {
273 // Lock is free, so we can proceed with the transaction
274 dismissed=1; // set to abort on exception throw
275 return;
276 }
277 // If lock is not free, we need to abort transaction as something else is running
278#if 1
279 BOOST_AFIO_XABORT(0x79);
280#else
281 BOOST_AFIO_XEND();
282#endif
283 continue;
284 // Never reaches this point
285 }
286 //std::cerr << "A=" << std::hex << state << std::endl;
287 // Transaction aborted due to too many locks or hard abort?
288 if((state & BOOST_AFIO_XABORT_CAPACITY) || !(state & BOOST_AFIO_XABORT_RETRY))
289 {
290 // Fall back onto pure locks
291 break;
292 }
293 // Was it me who aborted?
294 if((state & BOOST_AFIO_XABORT_EXPLICIT) && !(state & BOOST_AFIO_XABORT_NESTED))
295 {
296 switch(BOOST_AFIO_XABORT_CODE(state))
297 {
298 case 0x78: // exception thrown
299 throw std::runtime_error("Unknown exception thrown inside Intel TSX memory transaction");
300 case 0x79: // my lock was held by someone else, so repeat
301 break;
302 default: // something else aborted. Best fall back to locks
303 n=(size_t) 1<<(4*sizeof(n));
304 break;
305 }
306 }
307 }
308 // If the loop exited, we're falling back onto traditional locks
309 lockable.lock();
310 dismissed=3;
311 }
312 private:
313 intel_tsx_transaction(const intel_tsx_transaction &);
314 public:
315 intel_tsx_transaction(intel_tsx_transaction &&o) BOOST_NOEXCEPT_OR_NOTHROW : lockable(o.lockable), dismissed(o.dismissed)
316 {
317 o.dismissed=0; // disable original
318 }
319 ~intel_tsx_transaction() BOOST_NOEXCEPT_OR_NOTHROW
320 {
321 if(dismissed)
322 {
323 if(1==dismissed)
324 BOOST_AFIO_XABORT(0x78);
325 else if(2==dismissed)
326 {
327 BOOST_AFIO_XEND();
328 //std::cerr << "TC" << std::endl;
329 }
330 else if(3==dismissed)
331 lockable.unlock();
332 }
333 }
334 void commit() BOOST_NOEXCEPT_OR_NOTHROW
335 {
336 if(1==dismissed)
337 dismissed=2; // commit transaction
338 }
339 };
340 template<class T> inline intel_tsx_transaction<T> make_intel_tsx_transaction(T &lockable) BOOST_NOEXCEPT_OR_NOTHROW
341 {
342 return intel_tsx_transaction<T>(lockable);
343 }
344#define BOOST_BEGIN_MEMORY_TRANSACTION(lockable) { auto __tsx_transaction=boost::afio::detail::make_intel_tsx_transaction(lockable); {
345#define BOOST_END_MEMORY_TRANSACTION(lockable) } __tsx_transaction.commit(); }
346
347#endif // BOOST_USING_INTEL_TSX
348#endif // BOOST_BEGIN_MEMORY_TRANSACTION
349
350#ifndef BOOST_BEGIN_MEMORY_TRANSACTION
351#define BOOST_BEGIN_MEMORY_TRANSACTION(lockable) { boost::lock_guard<decltype(lockable)> __tsx_transaction(lockable);
352#define BOOST_END_MEMORY_TRANSACTION(lockable) }
353#endif // BOOST_BEGIN_MEMORY_TRANSACTION
354
355 }
356 }
357}
358
359#endif // BOOST_AFIO_MEMORY_TRANSACTIONS_HPP