aboutsummaryrefslogtreecommitdiff
path: root/bootloaders/diskloader/src/USBCore.cpp
blob: 142fc790b0f91c4b8149c42fececa40b3da29657 (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
/* Copyright (c) 2010, Peter Barrett  
**  
** Permission to use, copy, modify, and/or distribute this software for  
** any purpose with or without fee is hereby granted, provided that the  
** above copyright notice and this permission notice appear in all copies.  
** 
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL  
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED  
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR  
** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES  
** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,  
** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,  
** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS  
** SOFTWARE.  
*/

#include "Platform.h"

#define CDC_TX CDC_ENDPOINT_IN
#define CDC_RX CDC_ENDPOINT_OUT

#define EP_TYPE_CONTROL				0x00
#define EP_TYPE_BULK_IN				0x81
#define EP_TYPE_BULK_OUT			0x80
#define EP_TYPE_INTERRUPT_IN		0xC1
#define EP_TYPE_INTERRUPT_OUT		0xC0
#define EP_TYPE_ISOCHRONOUS_IN		0x41
#define EP_TYPE_ISOCHRONOUS_OUT		0x40

void Reboot();

//==================================================================
//==================================================================

typedef struct
{
	u32	dwDTERate;
	u8	bCharFormat;
	u8 	bParityType;
	u8 	bDataBits;
	u8	lineState;
} LineInfo;

static volatile LineInfo _usbLineInfo = { 57600, 0x00, 0x00, 0x00, 0x00 };

//==================================================================
//==================================================================

//	4 bytes of RAM
volatile u8 _usbConfiguration;
volatile u8 _ejected;
volatile u16 _timeout;

static inline void WaitIN(void)
{
	while (!(UEINTX & (1<<TXINI)));
}

static inline void ClearIN(void)
{
	UEINTX = ~(1<<TXINI);
}

static inline void WaitOUT(void)
{
	while (!(UEINTX & (1<<RXOUTI)))
		;
}

static inline u8 WaitForINOrOUT()
{
	while (!(UEINTX & ((1<<TXINI)|(1<<RXOUTI))))
		;
	return (UEINTX & (1<<RXOUTI)) == 0;
}

static inline void ClearOUT(void)
{
	UEINTX = ~(1<<RXOUTI);
}

static
void Send(volatile const u8* data, u8 count)
{
	TXLED1;					// light the TX LED
	while (count--)
		UEDATX = *data++;
}

void Recv(volatile u8* data, u8 count)
{
	RXLED1;					// light the RX LED
	while (count--)
		*data++ = UEDATX;
}

static inline u8 Recv8()
{
	RXLED1;					// light the RX LED
	return UEDATX;
}

static inline void Send8(u8 d)
{
	TXLED1;					// light the TX LED
	UEDATX = d;
}

static inline void SetEP(u8 ep)
{
	UENUM = ep;
}

static inline u8 FifoByteCount()
{
	return UEBCLX;
}

static inline u8 ReceivedSetupInt()
{
	return UEINTX & (1<<RXSTPI);
}

static inline void ClearSetupInt()
{
	UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
}

static inline void Stall()
{
	UECONX = (1<<STALLRQ) | (1<<EPEN);
}

static inline u8 ReadWriteAllowed()
{
	return UEINTX & (1<<RWAL);
}

static inline u8 Stalled()
{
	return UEINTX & (1<<STALLEDI);
}

static inline u8 FifoFree()
{
	return UEINTX & (1<<FIFOCON);
}

static inline void ReleaseRX()
{
	UEINTX = 0x6B;	// FIFOCON=0 NAKINI=1 RWAL=1 NAKOUTI=0 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=1
}

static inline void ReleaseTX()
{
	UEINTX = 0x3A;	// FIFOCON=0 NAKINI=0 RWAL=1 NAKOUTI=1 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=0
}

static inline u8 FrameNumber()
{
	return UDFNUML;
}

//==================================================================
//==================================================================

#define EP_SINGLE_64 0x32	// EP0
#define EP_DOUBLE_64 0x36	// Other endpoints

static void InitEP(u8 index, u8 type, u8 size)
{
	UENUM = index;
	UECONX = 1;
	UECFG0X = type;
	UECFG1X = size;
}

//	API
void USBInit(void)
{
	_timeout = 0;
	_usbConfiguration = 0;
	_ejected = 0;
	
	UHWCON = 0x01;						// power internal reg (don't need this?)
	USBCON = (1<<USBE)|(1<<FRZCLK);		// clock frozen, usb enabled
	PLLCSR = 0x12;						// Need 16 MHz xtal
	while (!(PLLCSR & (1<<PLOCK)))		// wait for lock pll
		;
	USBCON = ((1<<USBE)|(1<<OTGPADE));	// start USB clock
	UDCON = 0;							// enable attach resistor
}

u8 USBGetConfiguration(void)
{
	return _usbConfiguration;
}

u8 HasData(u8 ep)
{
	SetEP(ep);
	return ReadWriteAllowed();	// count in fifo
}

int USBGetChar();
void Recv(u8 ep, u8* dst, u8 len)
{
	SetEP(ep);
	while (len--)
	{
		while (!ReadWriteAllowed())
			;
		*dst++ = Recv8();
		if (!ReadWriteAllowed())	// release empty buffer
			ReleaseRX();
	}
}

//	Transmit a packet to endpoint
void Transfer(u8 ep, const u8* data, int len)
{
	u8 zero = ep & TRANSFER_ZERO;
	SetEP(ep & 7);
	while (len--)
	{
		while (!ReadWriteAllowed())
			;	// TODO Check for STALL etc

		u8 d = (ep & TRANSFER_PGM) ? pgm_read_byte(data) : data[0];
		data++;
		if (zero)
			d = 0;
		Send8(d);

		if (!ReadWriteAllowed())
			ReleaseTX();
	}
	if (ep & TRANSFER_RELEASE)
		ReleaseTX();
}

extern const u8 _initEndpoints[] PROGMEM;
const u8 _initEndpoints[] = 
{
	0,

#ifdef CDC_ENABLED
	EP_TYPE_INTERRUPT_IN,		// CDC_ENDPOINT_ACM
	EP_TYPE_BULK_OUT,			// CDC_ENDPOINT_OUT
	EP_TYPE_BULK_IN,			// CDC_ENDPOINT_IN
#endif

	EP_TYPE_INTERRUPT_IN,		// HID_ENDPOINT_INT
};

static void InitEndpoints()
{
	for (u8 i = 1; i < sizeof(_initEndpoints); i++)
	{
		UENUM = i;
		UECONX = 1;
		UECFG0X = pgm_read_byte(_initEndpoints+i);
		UECFG1X = EP_DOUBLE_64;
	}
	UERST = 0x7E;	// And reset them
	UERST = 0;
}

typedef struct
{
	u8 bmRequestType;
	u8 bRequest;
	u8 wValueL;
	u8 wValueH;
	u16 wIndex;
	u16 wLength;
} Setup;
Setup _setup;

//bool USBHook(Setup& setup)
bool USBHook()
{
	Setup& setup = _setup;
	u8 r = setup.bRequest;

	//	CDC Requests
	if (CDC_GET_LINE_CODING == r)
	{
		Send((const volatile u8*)&_usbLineInfo,7);
	}

	else if (CDC_SET_LINE_CODING ==  r)
	{
		WaitOUT();
		Recv((volatile u8*)&_usbLineInfo,7);
		ClearOUT();
	}

	else if (CDC_SET_CONTROL_LINE_STATE == r)
	{
		_usbLineInfo.lineState = setup.wValueL;
	}

	return true;
}

extern const u8 _rawHID[] PROGMEM;
#define LSB(_x) ((_x) & 0xFF)
#define MSB(_x) ((_x) >> 8)

#define RAWHID_USAGE_PAGE	0xFFC0
#define RAWHID_USAGE		0x0C00
#define RAWHID_TX_SIZE 64
#define RAWHID_RX_SIZE 64

const u8 _rawHID[] =
{
	//	RAW HID
	0x06, LSB(RAWHID_USAGE_PAGE), MSB(RAWHID_USAGE_PAGE),	// 30
	0x0A, LSB(RAWHID_USAGE), MSB(RAWHID_USAGE),

	0xA1, 0x01,				// Collection 0x01
    0x85, 0x03,             // REPORT_ID (3)
	0x75, 0x08,				// report size = 8 bits
	0x15, 0x00,				// logical minimum = 0
	0x26, 0xFF, 0x00,		// logical maximum = 255

	0x95, 64,				// report count TX
	0x09, 0x01,				// usage
	0x81, 0x02,				// Input (array)

	0x95, 64,				// report count RX
	0x09, 0x02,				// usage
	0x91, 0x02,				// Output (array)
	0xC0					// end collection
};

u8 _cdcComposite = 0;

bool SendDescriptor()
{
	Setup& setup = _setup;
	u8 desc_length = 0;
	const u8* desc_addr = 0;

	u8 t = setup.wValueH;
	if (0x22 == t)
	{
		desc_addr = _rawHID;
		desc_length = sizeof(desc_length);
	} else if (USB_DEVICE_DESCRIPTOR_TYPE == t)
	{
		if (setup.wLength == 8)
			_cdcComposite = 1;
		desc_addr = _cdcComposite ?  (const u8*)&USB_DeviceDescriptorA : (const u8*)&USB_DeviceDescriptor;
	}
	else if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t)
	{
		desc_addr = (const u8*)&USB_ConfigDescriptor;
		desc_length = sizeof(USB_ConfigDescriptor);
	}
	else if (USB_STRING_DESCRIPTOR_TYPE == t)
	{
		if (setup.wValueL == 0)
			desc_addr = (const u8*)&STRING_LANGUAGE;
		else
			return false;
	} else 
		return false;

	if (desc_length == 0)
		desc_length = pgm_read_byte(desc_addr);
	if ((u8)setup.wLength < desc_length)		// bit of a cheat limiting to 255 bytes TODO (saved 8 bytes)
		desc_length = (u8)setup.wLength;

	//	Send descriptor
	//	EP0 is 64 bytes long
	//	RWAL and FIFOCON don't work on EP0
	u8 n = 0;
	do
	{
		if (!WaitForINOrOUT())
			return false;
		Send8(pgm_read_byte(&desc_addr[n++]));
		u8 clr = n & 0x3F;
		if (!clr)
			ClearIN();	// Fifo is full, release this packet
	} while (n < desc_length);
	return true;
}

void USBSetupInterrupt()
{
    SetEP(0);
	if (!ReceivedSetupInt())
		return;

	Setup& setup = _setup;	// global saves ~30 bytes
	Recv((u8*)&setup,8);
	ClearSetupInt();

	if (setup.bmRequestType & DEVICETOHOST)
		WaitIN();
	else
		ClearIN();

    bool ok = true;
	u8 r = setup.bRequest;
	if (SET_ADDRESS == r)
	{
		WaitIN();
		UDADDR = setup.wValueL | (1<<ADDEN);
	}
	else if (SET_CONFIGURATION == r)
	{
		_usbConfiguration = setup.wValueL;
		InitEndpoints();
	}
	else if (GET_CONFIGURATION == r)
	{
		Send8(_usbConfiguration);
	}
	else if (GET_STATUS == r)
	{
		Send8(0);		// All good as far as I know
	}
	else if (GET_DESCRIPTOR == r)
	{
		ok = SendDescriptor();
	}
	else
	{
		ok = USBHook();
	}

	if (ok)
		ClearIN();
	else
		Stall();
}

void USBGeneralInterrupt()
{
	u8 udint = UDINT;
	UDINT = 0;

	//	End of Reset
	if (udint & (1<<EORSTI))
	{
		InitEP(0,EP_TYPE_CONTROL,EP_SINGLE_64);	// init ep0
		_usbConfiguration = 0;			// not configured yet
		//UEIENX = 1 << RXSTPE;
	}

	//	Start of Frame
	if (udint & (1<<SOFI))
	{
		if (!_ejected)
			_timeout = 0;
	}
}

void LEDPulse();
int USBGetChar()
{
	for(;;)
	{
		USBSetupInterrupt();
		USBGeneralInterrupt();

		//	Read a char
		if (HasData(CDC_RX))
		{
			u8 c = Recv8();
			if (!ReadWriteAllowed())
				ReleaseRX();
			return c;
		} else {
			u8 temp = 0;
			for (temp=100; temp; temp--) 
				asm volatile("nop\n\t" "nop\n\t" "nop\n\t" "nop\n\t"::);			
			RXLED0;		// we turn the RX and TX LEDs on in the relevant Send or Recv instruction
			TXLED0;		// we turn them off here after some time has passed to ensure a minimum on time.  
		}

		if (!--_timeout) {
			TXLED0;		// switch off the RX and TX LEDs before starting the user sketch
			RXLED0;
			Reboot();	// USB not connected, run firmware
		}

		LEDPulse();
	}
	return -1;
}