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: 549e71b86289bd5b484b4f3aa5f6a90b358ddecb (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
using MadWizard.WinUSBNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace com.clusterrr.FelLib
{
    public class Fel
    {
        public byte[] Fes1Bin;
        public byte[] UBootBin;

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

        USBDevice device = null;
        byte inEndp = 0;
        byte outEndp = 0;
        const int ReadTimeout = 1000;
        const int WriteTimeout = 1000;
        public const int MaxBulkSize = 0x10000;
        UInt16 vid, pid;
        bool DramInitDone = false;

        const UInt32 cmdOffset = 0x604FF;
        const UInt32 fes1_base_m = 0x2000;
        const UInt32 dram_base = 0x40000000;
        const UInt32 flash_mem_base = 0x43800000;
        const UInt32 flash_mem_size = 0x20;
        const UInt32 uboot_base_m = 0x47000000u;
        const UInt32 sector_size = 0x20000;
        const UInt32 uboot_base_f = 0x100000;
        const UInt32 kernel_base_f = (sector_size * 0x30);
        const UInt32 kernel_base_m = flash_mem_base;
        const UInt32 kernel_max_size = (uboot_base_m - flash_mem_base);
        const UInt32 kernel_max_flash_size = (sector_size * 0x20);
        const string fastboot = "fastboot_test";

        public static bool DeviceExists(UInt16 vid, UInt16 pid)
        {
            var fel = new Fel();
            try
            {
                fel.Open(vid, pid);
#if DEBUG
                DebugLog("Device detection successful");
#endif
                return true;
            }
            catch (Exception ex)
            {
#if DEBUG
                DebugLog("Device detection error: " + ex.Message + ex.StackTrace);
#endif
                return false;
            }
            finally
            {
                fel.Close();
            }
        }

        public void Open(UInt16 vid, UInt16 pid)
        {
            this.vid = vid;
            this.pid = pid;
            Close();
#if DEBUG
            DebugLog("Trying to open device...");
#endif
            device = USBDevice.GetSingleDevice(vid, pid);
            if (device == null) throw new FelException("Device with such VID and PID not found");
#if DEBUG
            DebugLog("Checking USB endpoints...");
#endif
            foreach (var pipe in device.Pipes)
            {
                if (pipe.IsIn)
                {
                    inEndp = pipe.Address;
#if DEBUG
                    DebugLog("IN endpoint found: "+ inEndp);
#endif
                }
                else
                {
                    outEndp = pipe.Address;
#if DEBUG
                    DebugLog("Out endpoint found: "+outEndp);
#endif
                }
            }
            device.Pipes[inEndp].Policy.PipeTransferTimeout = ReadTimeout;
            device.Pipes[outEndp].Policy.PipeTransferTimeout = WriteTimeout;
#if DEBUG
            DebugLog("Trying to verify device");
#endif
            if (VerifyDevice().Board != 0x00166700) throw new FelException("Invalid board ID: " + VerifyDevice().Board);
        }
        public void Close()
        {
            if (device != null)
            {
                try
                {
                    device.Pipes[inEndp].Abort();
                }
                catch { }
                try
                {
                    device.Pipes[outEndp].Abort();
                }
                catch
                {
                }
                device.Dispose();
                device = null;
            }
        }

        private void WriteToUSB(byte[] buffer)
        {
#if DEBUG
            DebugLog("-> " + BitConverter.ToString(buffer));
#endif

            device.Pipes[outEndp].Write(buffer);
        }

        private int ReadFromUSB(byte[] buffer, int offset, int length)
        {
            var data = device.Pipes[inEndp].Read(buffer, offset, length);
#if DEBUG
            DebugLog("<- " + BitConverter.ToString(buffer));
#endif
            return data;
        }
        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)
            {
                if (callback != null) callback(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)
            {
                if (callback != null) callback(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>();
            while (((length + address % sector_size + sector_size - 1) / sector_size) > flash_mem_size)
            {
                var sectors = (length + address % sector_size + sector_size - 1) / sector_size - flash_mem_size;
                var buf = ReadFlash(address, sectors * sector_size - address % sector_size, callback);
                address += (uint)buf.Length;
                length -= (uint)buf.Length;
                result.AddRange(buf);
            }
            if (result.Count > 0) return result.ToArray();
            var command = string.Format("sunxi_flash phy_read {0:x} {1:x} {2:x};{3}", flash_mem_base, address / sector_size, (length + address % sector_size + sector_size - 1) / sector_size, fastboot);
            RunUbootCmd(command, false, callback);
            result.AddRange(ReadMemory(flash_mem_base + address % sector_size, length, callback));
            return result.ToArray();
        }

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

        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)
        {
            if (callback != null) callback(CurrentAction.RunningCommand, command);
            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(1000);
                if (callback != null) callback(CurrentAction.RunningCommand, command);
            }
            int errorCount = 0;
            while (true)
            {
                try
                {
                    Open(vid, pid);
                    break;
                }
                catch (Exception ex)
                {
                    errorCount++;
                    if (errorCount >= 10)
                    {
                        Close();
                        throw ex;
                    }
                    Thread.Sleep(2000);
                }
            }
        }

#if DEBUG
        public static void DebugLog(string text)
        {
            Console.WriteLine(text);
            try
            {
                File.AppendAllText("debug.txt", DateTime.Now + ": " + text + "\r\n");
            }
            catch { }
        }
#endif
    }
}