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

Fel.cs « FelLib - github.com/ClusterM/hakchi2.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1111d00e941ac786e4e07bac3a43599a9a71211d (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
using LibUsbDotNet;
using LibUsbDotNet.Main;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace com.clusterrr.FelLib
{
    public class Fel : IDisposable
    {
        public byte[] Fes1Bin;
        byte[] uBootBin;

        public enum CurrentAction { RunningCommand, ReadingMemory, WritingMemory }
        public delegate void OnFelProgress(CurrentAction action, string command);

        UsbDevice device = null;
        UsbEndpointReader epReader = null;
        UsbEndpointWriter epWriter = null;
        const int ReadTimeout = 1000;
        const int WriteTimeout = 1000;
        public const int MaxBulkSize = 0x10000;
        UInt16 vid, pid;
        bool DramInitDone = false;

        int cmdOffset = -1;
        public const UInt32 fes1_base_m = 0x2000;
        public const UInt32 dram_base = 0x40000000;
        public const UInt32 uboot_base_m = dram_base + 0x7000000u;
        public const UInt32 uboot_base_f = 0x100000u;
        public const UInt32 sector_size = 0x20000u;
        public const UInt32 uboot_maxsize_f = (sector_size * 0x10);
        public const UInt32 kernel_base_f = sector_size * 0x30;
        public const UInt32 kernel_max_size = sector_size * 0x20;
        public const UInt32 transfer_base_m = dram_base + 0x7400000u;
        public const UInt32 transfer_max_size = sector_size * 0x100;
        const string fastboot = "efex_test";

        public byte[] UBootBin
        {
            get
            {
                return uBootBin;
            }

            set
            {
                uBootBin = value;
                var prefix = "bootcmd=";
                for (int i = 0; i < uBootBin.Length - prefix.Length; i++)
                    if (Encoding.ASCII.GetString(uBootBin, i, prefix.Length) == prefix)
                    {
                        cmdOffset = i + prefix.Length;
                        break;
                    }
            }
        }

        public static bool DeviceExists(UInt16 vid, UInt16 pid)
        {
            var fel = new Fel();
            try
            {
                if (fel.Open(vid, pid))
                {
                    Debug.WriteLine("Device detection successful");
                    return true;
                }
                else
                {
                    return false;
                }
            }
            finally
            {
                fel.Close();
            }
        }

        public bool Open(UInt16 vid, UInt16 pid)
        {
            try
            {
                this.vid = vid;
                this.pid = pid;
                Close();
                //Debug.WriteLine("Trying to open device...");
                var devices = UsbDevice.AllDevices;
                device = null;
                foreach (UsbRegistry regDevice in devices)
                {
                    if (regDevice.Vid == vid && regDevice.Pid == pid)
                    {
                        regDevice.Open(out device);
                        break;
                    }
                }
                if (device == null)
                {
#if VERY_DEBUG
                Debug.WriteLine("Device with such VID and PID not found");
#endif
                    return false;
                }

                IUsbDevice wholeUsbDevice = device as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used, 
                    // the desired configuration and interface must be selected.

                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                int inEndp = -1;
                int outEndp = -1;
                int inMax = 0;
                int outMax = 0;
                Debug.WriteLine("Checking USB endpoints...");
                foreach (var config in device.Configs)
                    foreach (var @interface in config.InterfaceInfoList)
                        foreach (var endp in @interface.EndpointInfoList)
                        {
                            if ((endp.Descriptor.EndpointID & 0x80) != 0)
                            {
                                inEndp = endp.Descriptor.EndpointID;
                                inMax = endp.Descriptor.MaxPacketSize;
                                Debug.WriteLine("IN endpoint found: " + inEndp);
                                Debug.WriteLine("IN endpoint maxsize: " + inMax);
                            }
                            else
                            {
                                outEndp = endp.Descriptor.EndpointID;
                                outMax = endp.Descriptor.MaxPacketSize;
                                Debug.WriteLine("OUT endpoint found: " + outEndp);
                                Debug.WriteLine("OUT endpoint maxsize: " + outMax);
                            }
                        }
                if (inEndp != 0x82 || outEndp != 0x01)
                {
                    Debug.WriteLine("Uncorrect FEL device/mode");
                    return false;
                }
                epReader = device.OpenEndpointReader((ReadEndpointID)inEndp, 65536);
                epWriter = device.OpenEndpointWriter((WriteEndpointID)outEndp);

                Debug.WriteLine("Trying to verify device");
                if (VerifyDevice().Board != 0x00166700)
                {
                    Debug.WriteLine("Invalid board ID: " + VerifyDevice().Board);
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error: " + ex.Message + ex.StackTrace);
                return false;
            }
        }
        public void Close()
        {
            if (device != null)
                device.Close();
            device = null;
            if (epReader != null)
                epReader.Dispose();
            epReader = null;
            if (epWriter != null)
                epWriter.Dispose();
            epWriter = null;
        }

        private void WriteToUSB(byte[] buffer)
        {
#if VERY_DEBUG
            Debug.WriteLine("->[FEL] " + BitConverter.ToString(buffer));
#endif
            Debug.WriteLine(string.Format("-> {0} bytes", buffer.Length));
            int pos = 0;
            int l;
            while (pos < buffer.Length)
            {
                epWriter.Write(buffer, pos, buffer.Length - pos, WriteTimeout, out l);
                if (l > 0)
                    pos += l;
                else
                    throw new Exception("Can't write to USB");
            }
        }

        private int ReadFromUSB(byte[] buffer, int offset, int length)
        {
            int l;
            var result = epReader.Read(buffer, offset, length, ReadTimeout, out l);
            if (result != ErrorCode.Ok)
                throw new Exception("USB read error: " + result.ToString());
#if VERY_DEBUG
            Debug.WriteLine("<-[FEL] " + BitConverter.ToString(buffer));
#endif
            Debug.WriteLine(string.Format("<- {0} bytes", length));
            return l;
        }
        private byte[] ReadFromUSB(UInt32 length)
        {
            var result = new byte[length];
            int pos = 0;
            while (pos < length)
            {
                pos += ReadFromUSB(result, pos, (int)(length - pos));
            }
            return result;
        }

        private void FelWrite(byte[] buffer)
        {
            var req = new AWUSBRequest();
            req.Cmd = AWUSBRequest.RequestType.AW_USB_WRITE;
            req.Len = (uint)buffer.Length;
            WriteToUSB(req.Data);
            WriteToUSB(buffer);
            var resp = new AWUSBResponse(ReadFromUSB(13));
            if (resp.CswStatus != 0) throw new FelException("FEL write error");
        }

        private byte[] FelRead(UInt32 length)
        {
            var req = new AWUSBRequest();
            req.Cmd = AWUSBRequest.RequestType.AW_USB_READ;
            req.Len = length;
            WriteToUSB(req.Data);

            var result = ReadFromUSB(length);
            var resp = new AWUSBResponse(ReadFromUSB(13));
            if (resp.CswStatus != 0) throw new FelException("FEL read error");
            return result;
        }

        private void FelRequest(AWFELStandardRequest.RequestType command)
        {
            var req = new AWFELStandardRequest();
            req.Cmd = command;
            FelWrite(req.Data);
        }

        private void FelRequest(AWFELStandardRequest.RequestType command, UInt32 address, UInt32 length)
        {
            var req = new AWFELMessage();
            req.Cmd = command;
            req.Address = address;
            req.Len = length;
            FelWrite(req.Data);
        }

        public AWFELVerifyDeviceResponse VerifyDevice()
        {
            FelRequest(AWFELStandardRequest.RequestType.FEL_VERIFY_DEVICE);
            byte[] resp;
            try
            {
                resp = FelRead(32);
            }
            catch
            {
                resp = new byte[32];
            }
            var status = new AWFELStatusResponse(FelRead(8));
            return new AWFELVerifyDeviceResponse(resp);
        }

        public void WriteMemory(UInt32 address, byte[] buffer, OnFelProgress callback = null)
        {
            if (address >= dram_base)
                InitDram();

            UInt32 length = (UInt32)buffer.Length;
            if (length != (length & ~((UInt32)3)))
            {
                length = (length + 3) & ~((UInt32)3);
                var newBuffer = new byte[length];
                Array.Copy(buffer, 0, newBuffer, 0, buffer.Length);
                buffer = newBuffer;
            }

            int pos = 0;
            while (pos < buffer.Length)
            {
                callback?.Invoke(CurrentAction.WritingMemory, null);
                var buf = new byte[Math.Min(buffer.Length - pos, MaxBulkSize)];
                Array.Copy(buffer, pos, buf, 0, buf.Length);
                FelRequest(AWFELStandardRequest.RequestType.FEL_DOWNLOAD, (UInt32)(address + pos), (uint)buf.Length);
                FelWrite(buf);
                var status = new AWFELStatusResponse(FelRead(8));
                if (status.State != 0) throw new FelException("FEL write error");
                pos += buf.Length;
            }
        }

        private byte[] ReadMemory(UInt32 address, UInt32 length, OnFelProgress callback = null)
        {
            if (address >= dram_base)
                InitDram();

            length = (length + 3) & ~((UInt32)3);

            var result = new List<byte>();
            while (length > 0)
            {
                callback?.Invoke(CurrentAction.ReadingMemory, null);
                var l = Math.Min(length, MaxBulkSize);
                FelRequest(AWFELStandardRequest.RequestType.FEL_UPLOAD, address, l);
                var r = FelRead((UInt32)l);
                result.AddRange(r);
                var status = new AWFELStatusResponse(FelRead(8));
                if (status.State != 0) throw new FelException("FEL read error");
                length -= l;
                address += l;
            }
            return result.ToArray();
        }

        public bool InitDram(bool force = false)
        {
            if (DramInitDone && !force) return true;
            if (DramInitDone) return true;
            const UInt32 testSize = 0x80;
            if (Fes1Bin == null || Fes1Bin.Length < testSize)
                throw new FelException("Can't init DRAM, incorrect Fes1 binary");
            var buf = ReadMemory((UInt32)(fes1_base_m + Fes1Bin.Length - testSize), testSize);
            var buf2 = new byte[testSize];
            Array.Copy(Fes1Bin, Fes1Bin.Length - buf.Length, buf2, 0, testSize);
            if (buf.SequenceEqual(buf2))
            {
                return DramInitDone = true;
            }
            WriteMemory(fes1_base_m, Fes1Bin);
            Exec(fes1_base_m);
            Thread.Sleep(2000);
            return DramInitDone = true;
        }

        public byte[] ReadFlash(UInt32 address, UInt32 length, OnFelProgress callback = null)
        {
            var result = new List<byte>();
            string command;
            if ((address % sector_size) != 0)
                throw new FelException(string.Format("Invalid flash address : 0x{0:X8}", address));
            if ((length % sector_size) != 0)
                throw new FelException(string.Format("Invalid flash length: 0x{0:X8}", length));
            while (length > 0)
            {
                var reqLen = Math.Min(length, transfer_max_size);
                command = string.Format("sunxi_flash phy_read {0:x} {1:x} {2:x};{3}", transfer_base_m, address / sector_size, (int)Math.Floor((double)reqLen / (double)sector_size), fastboot);
                RunUbootCmd(command, false, callback);
                var buf = ReadMemory(transfer_base_m + address % sector_size, reqLen, callback);
                result.AddRange(buf);
                address += (uint)buf.Length;
                length -= (uint)buf.Length;
            }
            return result.ToArray();
        }

        public void WriteFlash(UInt32 address, byte[] buffer, OnFelProgress callback = null)
        {
            var length = (uint)buffer.Length;
            uint pos = 0;
            if ((address % sector_size) != 0)
                throw new FelException(string.Format("Invalid flash address : 0x{0:X8}", address));
            if ((length % sector_size) != 0)
                throw new FelException(string.Format("Invalid flash length: 0x{0:X8}", length));
            while (length > 0)
            {
                var wrLength = Math.Min(length, transfer_max_size / 8);
                var newBuf = new byte[wrLength];
                Array.Copy(buffer, pos, newBuf, 0, wrLength);
                WriteMemory(transfer_base_m, newBuf, callback);
                var command = string.Format("sunxi_flash phy_write {0:x} {1:x} {2:x};{3}", transfer_base_m, address / sector_size, (int)Math.Floor((double)wrLength / (double)sector_size), fastboot);
                RunUbootCmd(command, false, callback);
                pos += (uint)wrLength;
                address += (uint)wrLength;
                length -= (uint)wrLength;
            }
        }

        public void Exec(UInt32 address)
        {
            FelRequest(AWFELStandardRequest.RequestType.FEL_RUN, address, 0);
            var status = new AWFELStatusResponse(FelRead(8));
            if (status.State != 0) throw new FelException("FEL run error");
        }

        public void RunUbootCmd(string command, bool noreturn = false, OnFelProgress callback = null)
        {
            callback?.Invoke(CurrentAction.RunningCommand, command);
            if (cmdOffset < 0) throw new Exception("Invalid Uboot binary, command variable not found");
            const UInt32 testSize = 0x20;
            if (UBootBin == null || UBootBin.Length < testSize)
                throw new FelException("Can't init Uboot, incorrect Uboot binary");
            var buf = ReadMemory(uboot_base_m, testSize);
            var buf2 = new byte[testSize];
            Array.Copy(UBootBin, 0, buf2, 0, testSize);
            if (!buf.SequenceEqual(buf2))
                WriteMemory(uboot_base_m, UBootBin);
            var cmdBuff = Encoding.ASCII.GetBytes(command + "\0");
            WriteMemory((uint)(uboot_base_m + cmdOffset), cmdBuff);
            Exec((uint)uboot_base_m);
            if (noreturn) return;
            Close();
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(500);
                callback?.Invoke(CurrentAction.RunningCommand, command);
            }
            int errorCount = 0;
            while (true)
            {
                if (!Open(vid, pid))
                {
                    errorCount++;
                    if (errorCount >= 10)
                    {
                        Close();
                        throw new Exception("No answer from device");
                    }
                    Thread.Sleep(2000);
                }
                else break;
            }
        }

        public void Dispose()
        {
            Close();
        }
    }
}