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

UsbTransfer.cs « Main « LibWinUsb - github.com/ClusterM/hakchi2.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 52646d1f40df161a3ae5e199eeda7de0810620f0 (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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
// Copyright © 2006-2010 Travis Robinson. All rights reserved.
// 
// website: http://sourceforge.net/projects/libusbdotnet
// e-mail:  libusbdotnet@gmail.com
// 
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or 
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
// for more details.
// 
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. or 
// visit www.gnu.org.
// 
// 
using System;
using System.Diagnostics;
using System.Threading;

namespace LibUsbDotNet.Main
{
    /// <summary>
    /// Base class for async transfer context.
    /// </summary>
    public abstract class UsbTransfer : IDisposable,IAsyncResult
    {
        private readonly UsbEndpointBase mEndpointBase;

        private IntPtr mBuffer;
        private int mCurrentOffset;
        private int mCurrentRemaining;
        private int mCurrentTransmitted;

        /// <summary></summary>
        protected int mIsoPacketSize;

        /// <summary></summary>
        protected int mOriginalCount;
        /// <summary></summary>
        protected int mOriginalOffset;
        private PinnedHandle mPinnedHandle;

        /// <summary></summary>
        protected int mTimeout;

        /// <summary></summary>
        protected bool mHasWaitBeenCalled = true;

        /// <summary></summary>
        protected readonly object mTransferLOCK = new object();

        /// <summary></summary>
        protected ManualResetEvent mTransferCancelEvent = new ManualResetEvent(false);
        /// <summary></summary>
        protected internal ManualResetEvent mTransferCompleteEvent = new ManualResetEvent(true);

        /// <summary></summary>
        protected UsbTransfer(UsbEndpointBase endpointBase) { mEndpointBase = endpointBase; }

        /// <summary>
        /// Returns the <see cref="UsbEndpointReader"/> or <see cref="UsbEndpointWriter"/> this transfer context is associated with.
        /// </summary>
        public UsbEndpointBase EndpointBase
        {
            get { return mEndpointBase; }
        }

        /// <summary>
        /// Number of bytes that will be requested for the next transfer.
        /// </summary>
        protected int RequestCount
        {
            get { return (mCurrentRemaining > UsbEndpointBase.MaxReadWrite ? UsbEndpointBase.MaxReadWrite : mCurrentRemaining); }
        }

        ///// <summary></summary>
        //protected int FailRetries
        //{
        //    get { return mFailRetries; }
        //}

        /// <summary></summary>
        protected IntPtr NextBufPtr
        {
            get { return new IntPtr(mBuffer.ToInt64() + mCurrentOffset); }
        }

        ///<summary>
        /// True if the transfer has been cacelled with <see cref="Cancel"/>.
        ///</summary>
        public bool IsCancelled
        {
            get { return mTransferCancelEvent.WaitOne(0, UsbConstants.EXIT_CONTEXT); }
        }

        /// <summary>
        /// Gets the <see cref="WaitHandle"/> for the cancel event.
        /// </summary>
        public WaitHandle CancelWaitHandle
        {
            get { return mTransferCancelEvent; }
        }

        /// <summary>
        /// Gets the size of each isochronous packet.
        /// </summary>
        /// <remarks>
        /// To change the packet size see <see cref="Fill(System.IntPtr,int,int,int,int)"/>
        /// </remarks>
        public int IsoPacketSize
        {
            get { return mIsoPacketSize; }
        }


        #region IDisposable Members

        /// <summary>
        /// Cancels any pending transfer and frees resources.
        /// </summary>
        public virtual void Dispose()
        {
            if (!IsCancelled) Cancel();

            int dummy;
            if (!mHasWaitBeenCalled) Wait(out dummy);
            if (mPinnedHandle != null) mPinnedHandle.Dispose();
            mPinnedHandle = null;
        }

        #endregion

        ~UsbTransfer() { Dispose(); }

        /// <summary>
        /// Cancels a pending transfer that was previously submitted with <see cref="Submit"/>.
        /// </summary>
        /// <returns></returns>
        public virtual ErrorCode Cancel()
        {
            mTransferCancelEvent.Set();
            mTransferCompleteEvent.WaitOne(5000, false);

            return ErrorCode.Success;
        }

        /// <summary>
        /// Submits the transfer.
        /// </summary>
        /// <remarks>
        /// This functions submits the USB transfer and return immediately.
        /// </remarks>
        /// <returns>
        /// <see cref="ErrorCode.Success"/> if the submit succeeds, 
        /// otherwise one of the other <see cref="ErrorCode"/> codes.
        /// </returns>
        public abstract ErrorCode Submit();

        /// <summary>
        /// Wait for the transfer to complete, timeout, or get cancelled.
        /// </summary>
        /// <param name="transferredCount">The number of bytes transferred on <see cref="ErrorCode.Success"/>.</param>
        /// <param name="cancel">If true, the transfer is cancelled if it does not complete within the time specified in <see cref="Timeout"/>.</param>
        /// <returns><see cref="ErrorCode.Success"/> if the transfer completes successfully, otherwise one of the other <see cref="ErrorCode"/> codes.</returns>
        public abstract ErrorCode Wait(out int transferredCount, bool cancel);

        /// <summary>
        /// Wait for the transfer to complete, timeout, or get cancelled.
        /// </summary>
        /// <param name="transferredCount">The number of bytes transferred on <see cref="ErrorCode.Success"/>.</param>
        /// <returns><see cref="ErrorCode.Success"/> if the transfer completes successfully, otherwise one of the other <see cref="ErrorCode"/> codes.</returns>
        public ErrorCode Wait(out int transferredCount) { return Wait(out transferredCount, true); }

        /// <summary>
        /// Fills the transfer with the data to <see cref="Submit"/>.
        /// </summary>
        /// <param name="buffer">The buffer; See <see cref="PinnedHandle"/> for more details.</param>
        /// <param name="offset">The offset on the buffer where the transfer should read/write.</param>
        /// <param name="count">The number of bytes to transfer.</param>
        /// <param name="timeout">Time (milliseconds) to wait before the transfer times out.</param>
        public virtual void Fill(object buffer, int offset, int count, int timeout)
        {
            if (mPinnedHandle != null) mPinnedHandle.Dispose();
            mPinnedHandle = new PinnedHandle(buffer);
            Fill(mPinnedHandle.Handle, offset, count, timeout);
        }
        /// <summary>
        /// Fills the transfer with the data to <see cref="Submit"/> an isochronous transfer.
        /// </summary>
        /// <param name="buffer">The buffer; See <see cref="PinnedHandle"/> for more details.</param>
        /// <param name="offset">The offset on the buffer where the transfer should read/write.</param>
        /// <param name="count">The number of bytes to transfer.</param>
        /// <param name="timeout">Time (milliseconds) to wait before the transfer times out.</param>
        /// <param name="isoPacketSize">Size of each isochronous packet.</param>
        public virtual void Fill(object buffer, int offset, int count, int timeout, int isoPacketSize)
        {
            if (mPinnedHandle != null) mPinnedHandle.Dispose();
            mPinnedHandle = new PinnedHandle(buffer);
            Fill(mPinnedHandle.Handle, offset, count, timeout, isoPacketSize);
        }
        /// <summary>
        /// Fills the transfer with the data to <see cref="Submit"/>.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <param name="offset">The offset on the buffer where the transfer should read/write.</param>
        /// <param name="count">The number of bytes to transfer.</param>
        /// <param name="timeout">Time (milliseconds) to wait before the transfer times out.</param>
        public virtual void Fill(IntPtr buffer, int offset, int count, int timeout)
        {
            mBuffer = buffer;

            mOriginalOffset = offset;
            mOriginalCount = count;
            mTimeout = timeout;
            Reset();
        }
        /// <summary>
        /// Fills the transfer with the data to <see cref="Submit"/> an isochronous transfer.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <param name="offset">The offset on the buffer where the transfer should read/write.</param>
        /// <param name="count">The number of bytes to transfer.</param>
        /// <param name="timeout">Time (milliseconds) to wait before the transfer times out.</param>
        /// <param name="isoPacketSize">Size of each isochronous packet.</param>
        public virtual void Fill(IntPtr buffer, int offset, int count, int timeout, int isoPacketSize)
        {
            mBuffer = buffer;

            mOriginalOffset = offset;
            mOriginalCount = count;
            mTimeout = timeout;
            mIsoPacketSize = isoPacketSize;
            Reset();
        }
        internal static ErrorCode SyncTransfer(UsbTransfer transferContext,
                                       IntPtr buffer,
                                       int offset,
                                       int length,
                                       int timeout,
                                       out int transferLength)
        {
            return SyncTransfer(transferContext, buffer, offset, length, timeout, 0, out transferLength);
        }
        internal static ErrorCode SyncTransfer(UsbTransfer transferContext,
                                               IntPtr buffer,
                                               int offset,
                                               int length,
                                               int timeout,
                                               int isoPacketSize,
                                               out int transferLength)
        {
            if (ReferenceEquals(transferContext, null)) throw new NullReferenceException("Invalid transfer context.");
            if (offset < 0) throw new ArgumentException("must be >=0", "offset");
            if (isoPacketSize == 0 && transferContext.EndpointBase.Type == EndpointType.Isochronous)
            {
                Info.UsbEndpointInfo endpointInfo = transferContext.EndpointBase.EndpointInfo;
                if (endpointInfo!=null)
                    isoPacketSize = endpointInfo.Descriptor.MaxPacketSize;
            }
            lock (transferContext.mTransferLOCK)
            {
                transferLength = 0;

                int transferred;
                ErrorCode ec;
                transferContext.Fill(buffer, offset, length, timeout, isoPacketSize);

                while (true)
                {
                    ec = transferContext.Submit();
                    if (ec != ErrorCode.Success) return ec;

                    ec = transferContext.Wait(out transferred);
                    if (ec != ErrorCode.Success) return ec;

                    transferLength += transferred;

                    if ((ec != ErrorCode.None || transferred != UsbEndpointBase.MaxReadWrite) ||
                        !transferContext.IncrementTransfer(transferred))
                        break;
                }

                return ec;
            }
        }

        /// <summary>
        /// Increments the internal counters to the next transfer batch (for transfers greater than <see cref="UsbEndpointBase.MaxReadWrite"/>)
        /// </summary>
        /// <param name="amount">This will usually be the total transferred on the previous batch.</param>
        /// <returns>True if the buffer still has data available and internal counters were successfully incremented.</returns>
        public bool IncrementTransfer(int amount)
        {
            mCurrentTransmitted += amount;
            mCurrentRemaining -= amount;
            mCurrentOffset += amount;

            if ((mCurrentRemaining) <= 0)
            {
                Debug.Assert(mCurrentRemaining == 0);
                return false;
            }

            return true;
        }

        /// <summary>
        /// Totoal number of bytes transferred.
        /// </summary>
        public int Transmitted
        {
            get
            {
                return mCurrentTransmitted;
            }
        }

        /// <summary>
        /// Remaining bytes in the transfer data buffer.
        /// </summary>
        public int Remaining
        {
            get
            {
                return mCurrentRemaining;
            }
        }
        /// <summary>
        /// Resets the transfer to its orignal state.
        /// </summary>
        /// <remarks>
        /// Prepares a <see cref="UsbTransfer"/> to be resubmitted.
        /// </remarks>
        public void Reset()
        {
            mCurrentOffset = mOriginalOffset;
            mCurrentRemaining = mOriginalCount;
            mCurrentTransmitted = 0;

            mTransferCancelEvent.Reset();
        }

        /// <summary>
        /// Gets an indication whether the asynchronous operation has completed.
        /// </summary>
        /// <returns>
        /// true if the operation is complete; otherwise, false.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        public bool IsCompleted
        {
            get { return mTransferCompleteEvent.WaitOne(0, UsbConstants.EXIT_CONTEXT); }
        }


        /// <summary>
        /// Gets a <see cref="T:System.Threading.WaitHandle"/> that is used to wait for an asynchronous operation to complete.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Threading.WaitHandle"/> that is used to wait for an asynchronous operation to complete.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        public WaitHandle AsyncWaitHandle
        {
            get { return mTransferCompleteEvent; }
        }

        /// <summary>
        /// Gets a user-defined object that qualifies or contains information about an asynchronous operation.
        /// </summary>
        /// <returns>
        /// A user-defined object that qualifies or contains information about an asynchronous operation.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        public object AsyncState
        {
            get { throw new NotImplementedException(); }
        }

        /// <summary>
        /// Gets an indication of whether the asynchronous operation completed synchronously.
        /// </summary>
        /// <returns>
        /// true if the asynchronous operation completed synchronously; otherwise, false.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        public bool CompletedSynchronously
        {
            get { return false; }
        }
    }

    /// <summary>
    /// Helper class for maintaining a user defined number of outstanding aync transfers on an endpoint.
    /// </summary>
    public class UsbTransferQueue
    {
        /// <summary>
        /// Creates a new transfer queue instance.
        /// </summary>
        /// <param name="endpointBase">The endpoint to transfer data to/from.</param>
        /// <param name="maxOutstandingIO">The number of transfers to <see cref="UsbTransfer.Submit"/> before waiting for a completion.</param>
        /// <param name="bufferSize">The size of each data buffer.</param>
        /// <param name="timeout">The maximum time to wait for each transfer.</param>
        /// <param name="isoPacketSize">For isochronous use only.  The iso packet size.  If 0, the endpoints max packet size is used.</param>
        public UsbTransferQueue(UsbEndpointBase endpointBase, int maxOutstandingIO, int bufferSize, int timeout, int isoPacketSize)
        {
            EndpointBase = endpointBase;
            IsoPacketSize = isoPacketSize;
            Timeout = timeout;
            BufferSize = bufferSize;
            MaxOutstandingIO = maxOutstandingIO;

            mTransferHandles = new Handle[maxOutstandingIO];

            mBuffer = new byte[maxOutstandingIO][];
            for(int i=0; i < maxOutstandingIO; i++) 
                mBuffer[i] = new byte[bufferSize];

            IsoPacketSize = isoPacketSize > 0 ? isoPacketSize : endpointBase.EndpointInfo.Descriptor.MaxPacketSize;
        }

        /// <summary>
        /// Endpoint for I/O operations.
        /// </summary>
        public readonly UsbEndpointBase EndpointBase;

        /// <summary>
        /// Maximum outstanding I/O operations before waiting for a completion.
        /// This is also the number of data buffers allocated for this transfer queue.
        /// </summary>
        public readonly int MaxOutstandingIO;

        /// <summary>
        /// Size (in bytes) of each data buffer in this transfer queue.
        /// </summary>
        public readonly int BufferSize;

        /// <summary>
        /// Time (in milliseconds) to wait for a transfer to complete before returning <see cref="ErrorCode.IoTimedOut"/>.
        /// </summary>
        public readonly int Timeout;

        /// <summary>
        /// For isochronous use only.  The iso packet size.
        /// </summary>
        public readonly int IsoPacketSize;

        private int mOutstandingTransferCount;
        private readonly Handle[] mTransferHandles;
        private readonly byte[][] mBuffer;
        private int mTransferHandleNextIndex;
        private int mTransferHandleWaitIndex;

        /// <summary>
        /// A transfer queue handle.
        /// </summary>
        public class Handle
        {
            internal Handle(UsbTransfer context, byte[] data)
            {
                Context = context;
                Data = data;

            }

            /// <summary>
            /// Transfer context.
            /// </summary>
            public readonly UsbTransfer Context;

            /// <summary>
            /// Data buffer.
            /// </summary>
            public readonly byte[] Data;

            /// <summary>
            /// Number of bytes sent/received.
            /// </summary>
            public int Transferred;

            internal bool InUse;

        }

        /// <summary>
        /// Gets the transfer data buffer at the specified index.
        /// </summary>
        /// <param name="index">The index of the buffer to retrieve.</param>
        /// <returns>The byte array for a transfer.</returns>
        public byte[] this[int index]
        {
            get{ return mBuffer[index]; }
        }

        /// <summary>
        /// Gets a two dimensional array of data buffers. The first index represents the transfer the second represents the data buffer.
        /// </summary>
        public byte[][] Buffer
        {
            get { return mBuffer; }
        }

        private static void IncWithRoll(ref int incField, int rollOverValue)
        {
            if ((++incField) >= rollOverValue)
                incField = 0;
        }

        /// <summary>
        /// Submits transfers until <see cref="MaxOutstandingIO"/> is reached then waits for the oldest transfer to complete.  
        /// </summary>
        /// <param name="handle">The queue handle to the <see cref="UsbTransfer"/> that completed.</param>
        /// <returns><see cref="ErrorCode.Success"/> if data was transferred, or another <see cref="ErrorCode"/> on error.</returns>
        public ErrorCode Transfer(out Handle handle)
        {
            return transfer(this, out handle);
        }
        private static ErrorCode transfer(UsbTransferQueue transferParam, out Handle handle)
        {
            handle = null;
            ErrorCode ret = ErrorCode.Success;

            // Submit transfers until the maximum number of outstanding transfer(s) is reached.
            while (transferParam.mOutstandingTransferCount < transferParam.MaxOutstandingIO)
            {
                if (ReferenceEquals(transferParam.mTransferHandles[transferParam.mTransferHandleNextIndex], null))
                {
                    handle = transferParam.mTransferHandles[transferParam.mTransferHandleNextIndex] =
                        new Handle(transferParam.EndpointBase.NewAsyncTransfer(), transferParam.mBuffer[transferParam.mTransferHandleNextIndex]);

                    // Get the next available benchmark transfer handle.
                    handle.Context.Fill(handle.Data, 0, handle.Data.Length, transferParam.Timeout, transferParam.IsoPacketSize);
                }
                else
                {
                    // Get the next available benchmark transfer handle.
                    handle = transferParam.mTransferHandles[transferParam.mTransferHandleNextIndex];

                }

                handle.Transferred = 0;

                // Submit this transfer now.
                handle.Context.Reset();
                ret = handle.Context.Submit();
                if (ret != ErrorCode.Success) goto Done;

                // Mark this handle has InUse.
                handle.InUse = true;

                // When transfers ir successfully submitted, OutstandingTransferCount goes up; when
                // they are completed it goes down.
                //
                transferParam.mOutstandingTransferCount++;

                // Move TransferHandleNextIndex to the next available transfer.
                IncWithRoll(ref transferParam.mTransferHandleNextIndex, transferParam.MaxOutstandingIO);
            }

            // If the number of outstanding transfers has reached the limit, wait for the 
            // oldest outstanding transfer to complete.
            //
            if (transferParam.mOutstandingTransferCount == transferParam.MaxOutstandingIO)
            {
                // TransferHandleWaitIndex is the index of the oldest outstanding transfer.
                handle = transferParam.mTransferHandles[transferParam.mTransferHandleWaitIndex];
                ret = handle.Context.Wait(out handle.Transferred, false);
                if (ret != ErrorCode.Success)
                    goto Done;

                // Mark this handle has no longer InUse.
                handle.InUse = false;

                // When transfers ir successfully submitted, OutstandingTransferCount goes up; when
                // they are completed it goes down.
                //
                transferParam.mOutstandingTransferCount--;

                // Move TransferHandleWaitIndex to the oldest outstanding transfer.
                IncWithRoll(ref transferParam.mTransferHandleWaitIndex, transferParam.MaxOutstandingIO);

                return ErrorCode.Success;
            }

        Done:
            return ret;
        }

        /// <summary>
        /// Cancels and frees all oustanding transfers.
        /// </summary>
        public void Free()
        {
            free(this);
        }

        private static void free(UsbTransferQueue transferParam)
        {
            for (int i = 0; i < transferParam.MaxOutstandingIO; i++)
            {
                if (!ReferenceEquals(transferParam.mTransferHandles[i], null))
                {
                    if (transferParam.mTransferHandles[i].InUse)
                    {
                        if (!transferParam.mTransferHandles[i].Context.IsCompleted)
                        {
                            transferParam.EndpointBase.Abort();
                            Thread.Sleep(1);
                        }

                        transferParam.mTransferHandles[i].InUse = false;
                        transferParam.mTransferHandles[i].Context.Dispose();
                    }
                    transferParam.mTransferHandles[i] = null;
                }
            }
            transferParam.mOutstandingTransferCount = 0;
            transferParam.mTransferHandleNextIndex = 0;
            transferParam.mTransferHandleWaitIndex = 0;
        }
    }
}