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

Win32ThreadPoolNativeOverlapped.cs « Threading « System « src « System.Private.CoreLib « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 3249e50374e07ca6fdde4439f408d8495605f2eb (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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace System.Threading
{
    [StructLayout(LayoutKind.Sequential)]
    internal partial struct Win32ThreadPoolNativeOverlapped
    {
        // Per-thread cache of the args object, so we don't have to allocate a new one each time.
        [ThreadStatic]
        private static ExecutionContextCallbackArgs t_executionContextCallbackArgs;

        private static ContextCallback s_executionContextCallback;
        private static OverlappedData[] s_dataArray;
        private static int s_dataCount;   // Current number of valid entries in _dataArray
        private static IntPtr s_freeList; // Lock-free linked stack of free ThreadPoolNativeOverlapped instances.

        private NativeOverlapped _overlapped; // must be first, so we can cast to and from NativeOverlapped.
        private IntPtr _nextFree; // if this instance if free, points to the next free instance.
        private int _dataIndex; // Index in _dataArray of this instance's OverlappedData.

#if MONO
        static Win32ThreadPoolNativeOverlapped()
        {
            if (!Environment.IsRunningOnWindows)
                throw new PlatformNotSupportedException();
        }
#endif

        internal OverlappedData Data
        {
            get { return s_dataArray[_dataIndex]; }
        }

        internal static unsafe Win32ThreadPoolNativeOverlapped* Allocate(IOCompletionCallback callback, object state, object pinData, PreAllocatedOverlapped preAllocated)
        {
            Win32ThreadPoolNativeOverlapped* overlapped = AllocateNew();
            try
            {
                overlapped->SetData(callback, state, pinData, preAllocated);
            }
            catch
            {
                Free(overlapped);
                throw;
            }
            return overlapped;
        }

        private static unsafe Win32ThreadPoolNativeOverlapped* AllocateNew()
        {
            IntPtr freePtr;
            Win32ThreadPoolNativeOverlapped* overlapped;
            OverlappedData data;

            // Find a free Overlapped
            while ((freePtr = Volatile.Read(ref s_freeList)) != IntPtr.Zero)
            {
                overlapped = (Win32ThreadPoolNativeOverlapped*)freePtr;

                if (Interlocked.CompareExchange(ref s_freeList, overlapped->_nextFree, freePtr) != freePtr)
                    continue;

                overlapped->_nextFree = IntPtr.Zero;
                return overlapped;
            }

            // None are free; allocate a new one.
            overlapped = (Win32ThreadPoolNativeOverlapped*)Interop.MemAlloc((UIntPtr)sizeof(Win32ThreadPoolNativeOverlapped));
            *overlapped = default(Win32ThreadPoolNativeOverlapped);

            // Allocate a OverlappedData object, and an index at which to store it in _dataArray.
            data = new OverlappedData();
            int dataIndex = Interlocked.Increment(ref s_dataCount) - 1;

            // Make sure we didn't wrap around.
            if (dataIndex < 0)
                Environment.FailFast("Too many outstanding Win32ThreadPoolNativeOverlapped instances");

            while (true)
            {
                OverlappedData[] dataArray = Volatile.Read(ref s_dataArray);
                int currentLength = dataArray == null ? 0 : dataArray.Length;

                // If the current array is too small, create a new, larger one.
                if (currentLength <= dataIndex)
                {
                    int newLength = currentLength;
                    if (newLength == 0)
                        newLength = 128;
                    while (newLength <= dataIndex)
                        newLength = (newLength * 3) / 2;

                    OverlappedData[] newDataArray = dataArray;
                    Array.Resize(ref newDataArray, newLength);

                    if (Interlocked.CompareExchange(ref s_dataArray, newDataArray, dataArray) != dataArray)
                        continue; // Someone else got the free one, try again

                    dataArray = newDataArray;
                }

                // If we haven't stored this object in the array yet, do so now.  Then we need to make another pass through
                // the loop, in case another thread resized the array before we made this update.
                if (s_dataArray[dataIndex] == null)
                {
                    // Full fence so this write can't move past subsequent reads.
                    Interlocked.Exchange(ref dataArray[dataIndex], data);
                    continue;
                }

                // We're already in the array, so we're done.
                Debug.Assert(dataArray[dataIndex] == data);
                overlapped->_dataIndex = dataIndex;
                return overlapped;
            }
        }

        private void SetData(IOCompletionCallback callback, object state, object pinData, PreAllocatedOverlapped preAllocated)
        {
            Debug.Assert(callback != null);

            OverlappedData data = Data;

            data._callback = callback;
            data._state = state;
            data._executionContext = ExecutionContext.Capture();
            data._preAllocated = preAllocated;

            //
            // pinData can be any blittable type to be pinned, *or* an instance of object[] each element of which refers to
            // an instance of a blittable type to be pinned.
            //
            if (pinData != null)
            {
                object[] objArray = pinData as object[];
                if (objArray != null && objArray.GetType() == typeof(object[]))
                {
                    if (data._pinnedData == null || data._pinnedData.Length < objArray.Length)
                        Array.Resize(ref data._pinnedData, objArray.Length);

                    for (int i = 0; i < objArray.Length; i++)
                    {
                        if (!data._pinnedData[i].IsAllocated)
                            data._pinnedData[i] = GCHandle.Alloc(objArray[i], GCHandleType.Pinned);
                        else
                            data._pinnedData[i].Target = objArray[i];
                    }
                }
                else
                {
                    if (data._pinnedData == null)
                        data._pinnedData = new GCHandle[1];

                    if (!data._pinnedData[0].IsAllocated)
                        data._pinnedData[0] = GCHandle.Alloc(pinData, GCHandleType.Pinned);
                    else
                        data._pinnedData[0].Target = pinData;
                }
            }
        }

        internal static unsafe void Free(Win32ThreadPoolNativeOverlapped* overlapped)
        {
            // Reset all data.
            overlapped->Data.Reset();
            overlapped->_overlapped = default(NativeOverlapped);

            // Add to the free list.
            while (true)
            {
                IntPtr freePtr = Volatile.Read(ref s_freeList);
                overlapped->_nextFree = freePtr;

                if (Interlocked.CompareExchange(ref s_freeList, (IntPtr)overlapped, freePtr) == freePtr)
                    break;
            }
        }

        internal static unsafe NativeOverlapped* ToNativeOverlapped(Win32ThreadPoolNativeOverlapped* overlapped)
        {
            return (NativeOverlapped*)overlapped;
        }

        internal static unsafe Win32ThreadPoolNativeOverlapped* FromNativeOverlapped(NativeOverlapped* overlapped)
        {
            return (Win32ThreadPoolNativeOverlapped*)overlapped;
        }

        internal static unsafe void CompleteWithCallback(uint errorCode, uint bytesWritten, Win32ThreadPoolNativeOverlapped* overlapped)
        {
            OverlappedData data = overlapped->Data;

            Debug.Assert(!data._completed);
            data._completed = true;

            ContextCallback callback = s_executionContextCallback;
            if (callback == null)
                s_executionContextCallback = callback = OnExecutionContextCallback;

            // Get an args object from the per-thread cache.
            ExecutionContextCallbackArgs args = t_executionContextCallbackArgs;
            if (args == null)
                args = new ExecutionContextCallbackArgs();

            t_executionContextCallbackArgs = null;

            args._errorCode = errorCode;
            args._bytesWritten = bytesWritten;
            args._overlapped = overlapped;
            args._data = data;

            ExecutionContext.Run(data._executionContext, callback, args);
        }

        private static unsafe void OnExecutionContextCallback(object state)
        {
            ExecutionContextCallbackArgs args = (ExecutionContextCallbackArgs)state;

            uint errorCode = args._errorCode;
            uint bytesWritten = args._bytesWritten;
            Win32ThreadPoolNativeOverlapped* overlapped = args._overlapped;
            OverlappedData data = args._data;

            // Put the args object back in the per-thread cache, now that we're done with it.
            args._data = null;
            t_executionContextCallbackArgs = args;

            data._callback(errorCode, bytesWritten, ToNativeOverlapped(overlapped));
        }
    }
}