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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
#include "global.h"
#include "synopsysotg.h"

#define SYNOPSYSOTG_AHB_BURST_LEN 5
#define SYNOPSYSOTG_AHB_THRESHOLD 8
#define SYNOPSYSOTG_TURNAROUND 3
#define SYNOPSYSOTG_HS_FIFO_SIZE
#define SYNOPSYSOTG_FS_FIFO_SIZE

static const struct synopsysotg_data* synopsysotg_fsdata;
static const struct synopsysotg_data* synopsysotg_hsdata;

static void synopsysotg_flush_ints(const struct synopsysotg_data* data)
{
	int i;
	for (i = 0; i < 16; i++)
	{
		data->core->OUTEP_REGS[i].DOEPINT = data->core->OUTEP_REGS[i].DOEPINT;
		data->core->INEP_REGS[i].DIEPINT = data->core->INEP_REGS[i].DIEPINT;
	}
	data->core->GREGS.GINTSTS = data->core->GREGS.GINTSTS;
}

void synopsysotg_start_rx(const struct synopsysotg_data* data, union synopsysotg_endpoint_number ep, void* buf, int size)
{
	// Find the appropriate set of endpoint registers
	volatile USB_OTG_OUTEPREGS* regs = &data->core->OUTEP_REGS[ep.number];

	// Calculate number of packets (if size == 0 an empty packet will be sent)
	int maxpacket = regs->DOEPCTL.b.mps;
	int packets = (size + maxpacket - 1) / maxpacket;
	if (!packets) packets = 1;

	// Set up data desination
	if (data->use_dma) regs->DOEPDMA = buf;
	else data->state->endpoints[ep.number].rxaddr = (u32*)buf;
	USB_OTG_DEPXFRSIZ_TypeDef deptsiz = { .b = { .pktcnt = packets, .xfersize = size } };
	regs->DOEPTSIZ = deptsiz;

	// Enable the endpoint
	USB_OTG_DEPCTL_TypeDef depctl = regs->DOEPCTL;
	depctl.b.epena = 1;
	depctl.b.cnak = 1;
	regs->DOEPCTL = depctl;
}

void synopsysotg_start_tx(const struct synopsysotg_data* data, union synopsysotg_endpoint_number ep, const void* buf, int size)
{
	// Find the appropriate set of endpoint registers
	volatile USB_OTG_INEPREGS* regs = &data->core->INEP_REGS[ep.number];

	// Calculate number of packets (if size == 0 an empty packet will be sent)
	int maxpacket = regs->DIEPCTL.b.mps;
	int packets = (size + maxpacket - 1) / maxpacket;
	if (!packets) packets = 1;

	// Set up data desination
	if (data->use_dma) regs->DIEPDMA = buf;
	else data->state->endpoints[ep.number].txaddr = (u32*)buf;
	USB_OTG_DEPXFRSIZ_TypeDef deptsiz = { .b = { .pktcnt = packets, .xfersize = size } };
	regs->DIEPTSIZ = deptsiz;

	// Enable the endpoint
	USB_OTG_DEPCTL_TypeDef depctl = regs->DIEPCTL;
	depctl.b.epena = 1;
	depctl.b.cnak = 1;
	regs->DIEPCTL = depctl;

	// Start pushing data into the FIFO (must be done after enabling the endpoint)
	if (!data->use_dma) data->core->DREGS.DIEPEMPMSK.ep.in |= (1 << ep.number);
}

void synopsysotg_set_stall(const struct synopsysotg_data* data, union synopsysotg_endpoint_number ep, int stall)
{
	if (ep.direction == SYNOPSYSOTG_ENDPOINT_DIRECTION_IN)
		data->core->INEP_REGS[ep.number].DIEPCTL.b.stall = !!stall;
	else data->core->OUTEP_REGS[ep.number].DOEPCTL.b.stall = !!stall;
}

void synopsysotg_unconfigure_ep(const struct synopsysotg_data* data, union synopsysotg_endpoint_number ep)
{
	USB_OTG_DEPCTL_TypeDef depctl = { .b = { } };
	if (ep.direction == SYNOPSYSOTG_ENDPOINT_DIRECTION_IN)
	{
		if (data->core->INEP_REGS[ep.number].DIEPCTL.b.epena)
		{
			// Urgh, someone was still babbling on our IN pipe, and now we have some
			// old crap in the FIFO. Disable the endpoint, to make sure nobody will
			// fetch any more old crap while we're trying to get rid of it.
			data->core->INEP_REGS[ep.number].DIEPCTL.b.epdis = 1;
			while (!(data->core->INEP_REGS[ep.number].DIEPINT.b.epdisabled));
			// Wait for any DMA activity to stop, to make sure nobody will touch the FIFO.
			while (!data->core->GREGS.GRSTCTL.b.ahbidle);
			// Flush it all the way down!
			USB_OTG_GRSTCTL_TypeDef grstctl = { .b = { .txfnum = ep.number, .txfflsh = 1 } };
			data->core->GREGS.GRSTCTL = grstctl;
			while (data->core->GREGS.GRSTCTL.b.txfflsh);
		}
		// Reset the transfer size register. Not strictly neccessary, but can't hurt.
		data->core->INEP_REGS[ep.number].DIEPTSIZ.d32 = 0;
		data->core->INEP_REGS[ep.number].DIEPCTL = depctl;
		// Mask interrupts for this endpoint
		data->core->DREGS.DAINTMSK.ep.in &= ~(1 << ep.number);
	}
	else
	{
		// We can't really do much about in-flight OUT requests except for ignoring them.
		data->core->OUTEP_REGS[ep.number].DOEPTSIZ.d32 = 0;
		data->core->OUTEP_REGS[ep.number].DOEPCTL = depctl;
		// Mask interrupts for this endpoint
		data->core->DREGS.DAINTMSK.ep.out &= ~(1 << ep.number);
	}
}

void synopsysotg_configure_ep(const struct synopsysotg_data* data, union synopsysotg_endpoint_number ep,
		                      enum synopsysotg_endpoint_type type, int maxpacket)
{
	// Reset the endpoint, just in case someone left it in a dirty state.
	synopsysotg_unconfigure_ep(data, ep);

	// Write the new configuration and unmask interrupts for the endpoint
	USB_OTG_DEPCTL_TypeDef depctl = { .b = { .usbactep = 1, .eptype = type, .mps = maxpacket, .txfnum = ep.number } };
	if (ep.direction == SYNOPSYSOTG_ENDPOINT_DIRECTION_IN)
	{
		data->core->INEP_REGS[ep.number].DIEPCTL = depctl;
		data->core->DREGS.DAINTMSK.ep.in |= (1 << ep.number);
	}
	else
	{
		data->core->OUTEP_REGS[ep.number].DOEPCTL = depctl;
		data->core->DREGS.DAINTMSK.ep.out |= (1 << ep.number);
	}
}

void synopsysotg_ep0_start_rx(const struct synopsysotg_data* data, int non_setup)
{
	// If we don't expect a non-SETUP packet, we can stall the OUT pipe,
	// SETUP packets will ignore that.
	if (!non_setup)	data->core->OUTEP_REGS[0].DOEPCTL.b.stall = 1;

	// Set up data desination
	if (data->use_dma) data->core->OUTEP_REGS[0].DOEPDMA = data->buffer;
	else data->state->endpoints[0].rxaddr = (u32*)data->buffer;
	USB_OTG_DEP0XFRSIZ_TypeDef deptsiz = { .b = { .supcnt = 3, .pktcnt = !!non_setup, .xfersize = 64 } };
	data->core->OUTEP_REGS[0].DOEPTSIZ.d32 = deptsiz.d32;

	// Enable the endpoint
	USB_OTG_DEPCTL_TypeDef depctl = data->core->OUTEP_REGS[0].DOEPCTL;
	depctl.b.epena = 1;
	depctl.b.cnak = 1;
	data->core->OUTEP_REGS[0].DOEPCTL = depctl;
}

void synopsysotg_ep0_send_response(const struct synopsysotg_data* data, const void* buf, int len)
{
	// Expect zero-length ACK
	synopsysotg_ep0_start_rx(data, 1);

	// Set up data source
	if (data->use_dma) data->core->INEP_REGS[0].DIEPDMA = buf;
	else data->state->endpoints[0].txaddr = buf;
	USB_OTG_DEP0XFRSIZ_TypeDef deptsiz = { .b = { .pktcnt = (len + 63) >> 6, .xfersize = len } };
	data->core->INEP_REGS[0].DIEPTSIZ.d32 = deptsiz.d32;

	// Enable the endpoint
	USB_OTG_DEPCTL_TypeDef depctl = data->core->INEP_REGS[0].DIEPCTL;
	depctl.b.epena = 1;
	depctl.b.cnak = 1;
	data->core->INEP_REGS[0].DIEPCTL = depctl;

	// Start pushing data into the FIFO (must be done after enabling the endpoint)
	if (!data->use_dma) data->core->DREGS.DIEPEMPMSK.ep.in |= 1;
}

void synopsysotg_ep0_send_ack(const struct synopsysotg_data* data)
{
	// No more data stages to follow, set up the OUT pipe for a SETUP packet.
	synopsysotg_ep0_start_rx(data, 0);

	// Set up the IN pipe for a zero-length packet
	USB_OTG_DEP0XFRSIZ_TypeDef deptsiz = { .b = { .pktcnt = 1 } };
	data->core->INEP_REGS[0].DIEPTSIZ.d32 = deptsiz.d32;

	// Enable the endpoint
	USB_OTG_DEPCTL_TypeDef depctl = data->core->INEP_REGS[0].DIEPCTL;
	depctl.b.epena = 1;
	depctl.b.cnak = 1;
	data->core->INEP_REGS[0].DIEPCTL = depctl;
}

void synopsysotg_ep0_expect_setup(const struct synopsysotg_data* data)
{
	// The next packet needs to be a SETUP, so lock out everything on the IN pipe.
	data->core->INEP_REGS[0].DIEPCTL.b.stall = 1;

	// Set up the OUT pipe for the SETUP packet, STALLing everythin else.
	synopsysotg_ep0_start_rx(data, 0);
}

static void synopsysotg_ep0_init(const struct synopsysotg_data* data)
{
	// Make sure both EP0 pipes are active.
	// (The hardware should take care of that, but who knows...)
	USB_OTG_DEPCTL_TypeDef depctl = { .b = { .usbactep = 1 } };
	data->core->OUTEP_REGS[0].DOEPCTL = depctl;
	data->core->INEP_REGS[0].DIEPCTL = depctl;

	// Prime EP0 for the first setup packet.
	synopsysotg_ep0_expect_setup(data);
}

static void synopsysotg_unconfigure(const struct synopsysotg_data* data)
{
	// Notify a configuration and its active interface altsettings that it was just kicked out.
	int configid = data->state->current_configuration;
	const struct synopsysotg_configuration* configuration = data->configurations[configid - 1];
	int i;
	for (i = 0; i < configuration->interface_count; i++)
	{
		struct synopsysotg_interface* interface = configuration->interfaces[i];
		const struct synopsysotg_altsetting* altsetting = interface->altsettings[interface->current_altsetting];
		if (altsetting->unset_altsetting)
			altsetting->unset_altsetting(data, i, interface->current_altsetting);
	}
	if (configuration->unset_configuration)
		configuration->unset_configuration(data, configid);
}

static void synopsysotg_handle_ep0_setup(const struct synopsysotg_data* data, union synopsysotg_buffer* buffer)
{
	// size < -1: do nothing at all (dangerous, you need to take care of priming EP0 yourself!)
	// size == -1: send STALL
	// size == 0: send ACK
	// size > 0: send <size> bytes at <addr>, then expect ACK
    const void* addr = NULL;
    int size = -1;
    switch (buffer->setup.bmRequestType.type)
	{
	case SYNOPSYSOTG_CTRLREQ_BMREQUESTTYPE_TYPE_STANDARD:
		switch (buffer->setup.bmRequestType.recipient)
		{
		case SYNOPSYSOTG_CTRLREQ_BMREQUESTTYPE_RECIPIENT_DEVICE:
			switch (buffer->setup.bRequest)
			{
			case SYNOPSYSOTG_CTRLREQ_BREQUEST_GET_STATUS:
				if (buffer->setup.wLength != 2 || buffer->setup.wIndex
				 || !data->state->current_address || buffer->setup.wValue) break;
				data->buffer->raw[0] = 0;
				data->buffer->raw[1] = 1;
				addr = data->buffer;
				size = 2;
				break;
			case SYNOPSYSOTG_CTRLREQ_BREQUEST_SET_ADDRESS:
				if (buffer->setup.wLength || buffer->setup.wIndex || buffer->setup.wValue > 127) break;
				data->state->current_address = buffer->setup.wValue;
				// We can already set the address here, the OTG will send the ACK with the old address.
				data->core->DREGS.DCFG.b.devaddr = data->state->current_address;
				size = 0;
				break;
			case SYNOPSYSOTG_CTRLREQ_BREQUEST_GET_DESCRIPTOR:
				if (!buffer->setup.wLength) break;
				switch (buffer->setup.wValue >> 8)
				{
				case SYNOPSYSOTG_DESCRIPTOR_TYPE_DEVICE:
					if ((buffer->setup.wValue & 0xff) || buffer->setup.wIndex) break;
		            addr = data->devicedescriptor;
		            size = data->devicedescriptor->bLength;
		            break;
				case SYNOPSYSOTG_DESCRIPTOR_TYPE_CONFIGURATION:
					if (buffer->setup.wIndex
					 || (buffer->setup.wValue & 0xff) >= data->configuration_count) break;
		            addr = data->configurations[buffer->setup.wValue & 0xff]->descriptor;
		            size = data->configurations[buffer->setup.wValue & 0xff]->descriptor->wTotalLength;
		            break;
				case SYNOPSYSOTG_DESCRIPTOR_TYPE_STRING:
					if ((buffer->setup.wValue & 0xff) > data->stringdescriptor_count) break;
		            addr = data->stringdescriptors[buffer->setup.wValue & 0xff];
		            size = data->stringdescriptors[buffer->setup.wValue & 0xff]->bLength;
		            break;
				}
			    if (size > buffer->setup.wLength) size = buffer->setup.wLength;
		        break;
			case SYNOPSYSOTG_CTRLREQ_BREQUEST_GET_CONFIGURATION:
				if (buffer->setup.wLength != 1 || buffer->setup.wIndex
				 || !data->state->current_address || buffer->setup.wValue) break;
				data->buffer->raw[0] = data->state->current_configuration;
				addr = data->buffer;
				size = 1;
				break;
			case SYNOPSYSOTG_CTRLREQ_BREQUEST_SET_CONFIGURATION:
				if (buffer->setup.wLength || buffer->setup.wIndex || !data->state->current_address
				 || buffer->setup.wValue > data->configuration_count) break;
				if (data->state->current_configuration) synopsysotg_unconfigure(data);
				data->state->current_configuration = buffer->setup.wValue;
				if (data->state->current_configuration)
				{
					// Notify the configuration and its interface default altsettings that it should set up stuff
					int configid = data->state->current_configuration;
					const struct synopsysotg_configuration* configuration = data->configurations[configid - 1];
					if (configuration->set_configuration)
						configuration->set_configuration(data, configid);
					int i;
					for (i = 0; i < configuration->interface_count; i++)
					{
						struct synopsysotg_interface* interface = configuration->interfaces[i];
						interface->current_altsetting = 0;
						const struct synopsysotg_altsetting* altsetting = interface->altsettings[0];
						if (altsetting->set_altsetting) altsetting->set_altsetting(data, i, 0);
					}
				}
				size = 0;
				break;
			default: break;
			}
			break;
		case SYNOPSYSOTG_CTRLREQ_BMREQUESTTYPE_RECIPIENT_INTERFACE:
		{
			if (!data->state->current_configuration) break;
			int configid = data->state->current_configuration;
			const struct synopsysotg_configuration* configuration = data->configurations[configid - 1];
			if (buffer->setup.wIndex >= configuration->interface_count) break;
			int intfid = buffer->setup.wIndex;
			struct synopsysotg_interface* interface = configuration->interfaces[intfid];
			switch (buffer->setup.bRequest)
			{
			case SYNOPSYSOTG_CTRLREQ_BREQUEST_GET_INTERFACE:
				if (buffer->setup.wLength != 1 || buffer->setup.wValue) break;
				data->buffer->raw[0] = interface->current_altsetting;
				addr = data->buffer;
				size = 1;
				break;
			case SYNOPSYSOTG_CTRLREQ_BREQUEST_SET_INTERFACE:
			{
				if (buffer->setup.wLength
				 || buffer->setup.wValue > interface->altsetting_count) break;
				const struct synopsysotg_altsetting* altsetting = interface->altsettings[interface->current_altsetting];
				if (altsetting->unset_altsetting)
					altsetting->unset_altsetting(data, intfid, interface->current_altsetting);
				interface->current_altsetting = buffer->setup.wValue;
				altsetting = interface->altsettings[interface->current_altsetting];
				if (altsetting->set_altsetting)
					altsetting->set_altsetting(data, intfid, interface->current_altsetting);
				break;
			}
			default: break;
			}
			break;
			default: break;
		}
		}
		break;
		default: break;
	}
    // See comment at the top of this function
    if (size == -1) synopsysotg_ep0_expect_setup(data);
    else if (size == 0) synopsysotg_ep0_send_ack(data);
    else if (size > 0) synopsysotg_ep0_send_response(data, addr, size);
}

static void synopsysotg_handle_ep0_data(const struct synopsysotg_data* data, union synopsysotg_buffer* buffer, int size)
{
	// We don't accept any commands that have an OUT payload. Just STALL it, no matter what it was.
	synopsysotg_ep0_expect_setup(data);
}

static const struct synopsysotg_endpoint* synopsysotg_find_endpoint(const struct synopsysotg_data* data,
		                                                            union synopsysotg_endpoint_number ep,
		                                                            int* ifidx, int* epidx)
{
	// Figure out who's currently owning a (hardware) endpoint.
	// Returns a pointer to the synopsysotg_endpoint struct, and sets *epidx to its index within its altsetting.
	// *ifidx will be set to the interface number within the current configuration that the altsetting belongs to.
	// If nobody currently owns the specified endpoint, return NULL (*epidx and *ifidx will contain garbage).
	int configid = data->state->current_configuration;
	if (!configid) return NULL;
	const struct synopsysotg_configuration* configuration = data->configurations[configid - 1];
	for (*ifidx = 0; *ifidx < configuration->interface_count; (*ifidx)++)
	{
		const struct synopsysotg_interface* interface = configuration->interfaces[*ifidx];
		const struct synopsysotg_altsetting* altsetting = interface->altsettings[interface->current_altsetting];
		for (*epidx = 0; *epidx < altsetting->endpoint_count; (*epidx)++)
		{
			const struct synopsysotg_endpoint* endpoint = altsetting->endpoints[*epidx];
			if (endpoint->number.byte == ep.byte) return endpoint;
		}
	}
	return NULL;
}

static void synopsysotg_kill_endpoint(const struct synopsysotg_data* data, union synopsysotg_endpoint_number ep)
{
	// Hm, apparently someone forgot to shut down an endpoint.
	// Let's try our best at cleaning up the mess...
	if (ep.direction == SYNOPSYSOTG_ENDPOINT_DIRECTION_IN)
	{
		USB_OTG_DEPCTL_TypeDef depctl = data->core->INEP_REGS[ep.number].DIEPCTL;
		depctl.b.epdis = 1;
		depctl.b.usbactep = 0;
		data->core->INEP_REGS[ep.number].DIEPCTL = depctl;
		data->core->DREGS.DAINTMSK.ep.in &= ~(1 << ep.number);
	}
	else
	{
		USB_OTG_DEPCTL_TypeDef depctl = data->core->OUTEP_REGS[ep.number].DOEPCTL;
		depctl.b.epdis = 1;
		depctl.b.usbactep = 0;
		data->core->OUTEP_REGS[ep.number].DOEPCTL = depctl;
		data->core->DREGS.DAINTMSK.ep.out &= ~(1 << ep.number);
	}
}

static void synopsysotg_irq(const struct synopsysotg_data* data)
{
	USB_OTG_GINTSTS_TypeDef gintsts = data->core->GREGS.GINTSTS;

    if (gintsts.b.usbreset)
    {
    	data->core->DREGS.DCFG.b.devaddr = 0;
    	synopsysotg_ep0_init(data);
    	data->state->current_address = 0;
		if (data->state->current_configuration) synopsysotg_unconfigure(data);
    	data->state->current_configuration = 0;
    	if (data->bus_reset) data->bus_reset(data, data->core->DREGS.DSTS.b.enumspd == 0);
    }

    if (gintsts.b.rxstsqlvl)
    {
    	// Device to memory part of the "software DMA" implementation, used to receive data if use_dma == 0.
    	// Handle one packet at a time, the IRQ will re-trigger if there's something left.
    	USB_OTG_GRXFSTS_TypeDef rxsts = data->core->GREGS.GRXSTSP;
    	int ep = rxsts.b.chnum;
    	int words = (rxsts.b.bcnt + 3) >> 2;
    	while (words--) *data->state->endpoints[ep].rxaddr++ = data->core->DFIFO[0][0];
    }

	if (gintsts.b.inepintr)
	{
		USB_OTG_DAINT_TypeDef daint = data->core->DREGS.DAINT;
		int ep;
		for (ep = 0; ep < 16; ep++)
			if (daint.ep.in & (1 << ep))
			{
				USB_OTG_DIEPINTn_TypeDef epints = data->core->INEP_REGS[ep].DIEPINT;
				const struct synopsysotg_endpoint* endpoint = NULL;
				union synopsysotg_endpoint_number epnum = { .direction = SYNOPSYSOTG_ENDPOINT_DIRECTION_IN, .number = ep };
				int epidx;
				int ifidx;
				if (ep) endpoint = synopsysotg_find_endpoint(data, epnum, &epidx, &ifidx);
				if (epints.b.emptyintr)
				{
			    	// Memory to device part of the "software DMA" implementation, used to transmit data if use_dma == 0.
					USB_OTG_DEPXFRSIZ_TypeDef deptsiz = data->core->INEP_REGS[ep].DIEPTSIZ;
			    	if (!deptsiz.b.pktcnt) data->core->DREGS.DIEPEMPMSK.ep.in &= ~(1 << ep);
			    	else
			    	{
			    		// Push data into the TX FIFO until we don't have anything left or the FIFO would overflow.
			    		int left = (deptsiz.b.xfersize + 3) >> 2;
			    		while (left)
			    		{
			    			int words = data->core->INEP_REGS[ep].DTXFSTS.b.txfspcavail;
			    			if (words > left) words = left;
			    			if (!words) break;
			    			left -= words;
			    			while (words--) data->core->DFIFO[ep][0] = *data->state->endpoints[ep].txaddr++;
			    		}
			    	}
				}
				int bytesleft = data->core->INEP_REGS[ep].DIEPTSIZ.b.xfersize;
				if (epints.b.timeout)
				{
					// Hm, the host didn't fetch our EP0 IN packet, so we feel a bit offended.
					// Refuse to accept any transfers, until we get a new SETUP token.
					if (!ep) synopsysotg_ep0_expect_setup(data);
					else if (!endpoint) synopsysotg_kill_endpoint(data, epnum);
					else if (endpoint->timeout) endpoint->timeout(data, ifidx, epidx, bytesleft);
				}
				if (epints.b.xfercompl)
				{
					// If this was EP0 IN, stall the pipe. There will only ever be one transfer for each
					// SETUP transaction, and the next SETUP packet will clear the stall.
					if (!ep) data->core->INEP_REGS[0].DIEPCTL.b.stall = 1;
					else if (!endpoint) synopsysotg_kill_endpoint(data, epnum);
					else if (endpoint->xfer_complete) endpoint->xfer_complete(data, ifidx, epidx, bytesleft);
				}
				data->core->INEP_REGS[ep].DIEPINT = epints;
			}
	}

	if (gintsts.b.outepintr)
	{
		USB_OTG_DAINT_TypeDef daint = data->core->DREGS.DAINT;
		int ep;
		for (ep = 0; ep < 16; ep++)
			if (daint.ep.out & (1 << ep))
			{
				USB_OTG_DOEPINTn_TypeDef epints = data->core->OUTEP_REGS[ep].DOEPINT;
				const struct synopsysotg_endpoint* endpoint = NULL;
				union synopsysotg_endpoint_number epnum = { .direction = SYNOPSYSOTG_ENDPOINT_DIRECTION_OUT, .number = ep };
				int epidx;
				int ifidx;
				if (ep) endpoint = synopsysotg_find_endpoint(data, epnum, &epidx, &ifidx);
				if (epints.b.setup)
				{
					USB_OTG_DEP0XFRSIZ_TypeDef deptsiz = { .d32 = data->core->OUTEP_REGS[0].DOEPTSIZ.d32 };
					int back2back = 3 - deptsiz.b.supcnt;
					if (data->core->INEP_REGS[ep].DIEPCTL.b.epena)
					{
						// Urgh, someone was still babbling on our IN pipe, and now we have some
						// old crap in the FIFO. Disable the endpoint, to make sure nobody will
						// fetch any more old crap while we're trying to get rid of it.
						data->core->INEP_REGS[ep].DIEPCTL.b.epdis = 1;
						while (!(data->core->INEP_REGS[ep].DIEPINT.b.epdisabled));
						// Wait for any DMA activity to stop, to make sure nobody will touch the FIFO.
						while (!data->core->GREGS.GRSTCTL.b.ahbidle);
						// Flush it all the way down!
						USB_OTG_GRSTCTL_TypeDef grstctl = { .b = { .txfnum = ep, .txfflsh = 1 } };
						data->core->GREGS.GRSTCTL = grstctl;
						while (data->core->GREGS.GRSTCTL.b.txfflsh);
						// Reset the transfer size register. Not strictly necessary, but can't hurt.
						data->core->INEP_REGS[ep].DIEPTSIZ.d32 = 0;
					}
					if (!ep)
					{
						// Figure out the location of the newest SETUP packet if there were
						// multiple back to back ones. If there were more than 3 SETUP packets
						// in a row, the OTG will take care of it, so we're on the safe side here.
						void* addr = &data->buffer->raw[8 * (back2back - 1)];
						union synopsysotg_buffer* buffer = (union synopsysotg_buffer*)addr;
						if (!data->ep0_setup_hook || !data->ep0_setup_hook(data, buffer))
							synopsysotg_handle_ep0_setup(data, buffer);
					}
					else if (!endpoint) synopsysotg_kill_endpoint(data, epnum);
					else if (endpoint->setup_received) endpoint->setup_received(data, ifidx, epidx, back2back);
				}
				else if (epints.b.xfercompl)
				{
					int bytesleft = data->core->INEP_REGS[ep].DIEPTSIZ.b.xfersize;
					if (!ep)
					{
						if (!data->ep0_data_hook || !data->ep0_data_hook(data, data->buffer, 64 - bytesleft))
							synopsysotg_handle_ep0_data(data, data->buffer, 64 - bytesleft);
					}
					else if (!endpoint) synopsysotg_kill_endpoint(data, epnum);
					else if (endpoint->xfer_complete) endpoint->xfer_complete(data, ifidx, epidx, bytesleft);
				}
				data->core->OUTEP_REGS[ep].DOEPINT = epints;
			}
	}

    data->core->GREGS.GINTSTS = gintsts;
}

void synopsysotg_init(const struct synopsysotg_data* data)
{
	int i;

	// Initialize data struct
	data->state->current_address = 0;
	data->state->current_configuration = 0;

	// Enable OTG clocks and configure GPIO pins
	int irq;
	if (data->core == &USB_OTG_HS)
	{
		synopsysotg_hsdata = data;
		irq = OTG_HS_IRQn;
		RCC->AHB1ENR |= RCC_AHB1ENR_OTGHSEN;
		GPIOB->AFR[1] = (GPIOB->AFR[1] & ~0xff000000) | 0xcc000000;
		GPIOB->MODER = (GPIOB->MODER & ~0xf0000000) | 0xa0000000;
	}
	else if (data->core == &USB_OTG_FS)
	{
		synopsysotg_fsdata = data;
		irq = OTG_FS_IRQn;
		RCC->AHB2ENR |= RCC_AHB2ENR_OTGFSEN;
		GPIOA->AFR[1] = (GPIOA->AFR[1] & ~0x000ff000) | 0x000aa000;
		GPIOA->MODER = (GPIOA->MODER & ~0x03c00000) | 0x02800000;
	}
	else return;

	// Disable IRQ during setup
	NVIC_DisableIRQ(irq);

	// Enable PHY clocks
	USB_OTG_PCGCCTL_TypeDef pcgcctl = { .b = {} };
	data->core->PCGCCTL = pcgcctl;

	// Configure PHY type (must be done before reset)
	USB_OTG_GCCFG_TypeDef gccfg = { .b = { .disablevbussensing = 1, .pwdn = 0 } };
	data->core->GREGS.GCCFG = gccfg;
	USB_OTG_GUSBCFG_TypeDef gusbcfg = { .b = { .force_dev = 1, .usbtrdtim = SYNOPSYSOTG_TURNAROUND } };
	if (data->use_ulpi) gusbcfg.b.ulpi_utmi_sel = 1;
	else gusbcfg.b.physel  = 1;
	data->core->GREGS.GUSBCFG = gusbcfg;

	// Reset the whole USB core
	USB_OTG_GRSTCTL_TypeDef grstctl = { .b = { .csftrst = 1 } };
    while (!data->core->GREGS.GRSTCTL.b.ahbidle);
	data->core->GREGS.GRSTCTL = grstctl;
    while (data->core->GREGS.GRSTCTL.b.csftrst);
    while (!data->core->GREGS.GRSTCTL.b.ahbidle);

    // Soft disconnect
    USB_OTG_DCTL_TypeDef dctl = { .b = { .sftdiscon = 1 } };
	data->core->DREGS.DCTL = dctl;

	// Configure the core
	USB_OTG_GAHBCFG_TypeDef gahbcfg = { .b = { .dmaenable = data->use_dma, .hburstlen = SYNOPSYSOTG_AHB_BURST_LEN, .glblintrmsk = 1 } };
	if (data->disable_double_buffering)
	{
		gahbcfg.b.nptxfemplvl_txfemplvl = 1;
		gahbcfg.b.ptxfemplvl = 1;
	}
	data->core->GREGS.GAHBCFG = gahbcfg;
	data->core->GREGS.GUSBCFG = gusbcfg;
	gccfg.b.pwdn = 1;
	data->core->GREGS.GCCFG = gccfg;
	USB_OTG_DCFG_TypeDef dcfg = { .b = { .nzstsouthshk = 1 } };
	data->core->DREGS.DCFG = dcfg;

	// Configure the FIFOs
	if (data->use_dma)
	{
		USB_OTG_DTHRCTL_TypeDef dthrctl = { .b = { .arb_park_en = 1, .rx_thr_en = 1, .iso_thr_en = 0, .non_iso_thr_en = 0,
												   .rx_thr_len = SYNOPSYSOTG_AHB_THRESHOLD } };
		data->core->DREGS.DTHRCTL = dthrctl;
	}
	int addr = data->fifosize;
	for (i = 0; i < 16; i++)
	{
		int size = data->txfifosize[i];
		addr -= size;
		if (size)
		{
			USB_OTG_TXFSIZ_TypeDef fsiz = { .b = { .startaddr = addr, .depth = size } };
			if (!i) data->core->GREGS.DIEPTXF0_HNPTXFSIZ = fsiz;
			else data->core->GREGS.DIEPTXF[i - 1] = fsiz;
		}
	}

	// Set up interrupts
	USB_OTG_DOEPMSK_TypeDef doepmsk =  { .b = { .xfercompl = 1, .setup = 1 } };
	data->core->DREGS.DOEPMSK = doepmsk;
	USB_OTG_DIEPMSK_TypeDef diepmsk =  { .b = { .xfercompl = 1, .timeout = 1 } };
	data->core->DREGS.DIEPMSK = diepmsk;
	data->core->DREGS.DIEPEMPMSK.d32 = 0;
	USB_OTG_DAINT_TypeDef daintmsk = { .ep = { .in = 0b0000000000000001, .out = 0b0000000000000001 } };
	data->core->DREGS.DAINTMSK = daintmsk;
	USB_OTG_GINTMSK_TypeDef gintmsk =  { .b = { .usbreset = 1, .outepintr = 1, .inepintr = 1 } };
	if (!data->use_dma) gintmsk.b.rxstsqlvl = 1;
	data->core->GREGS.GINTMSK = gintmsk;
	synopsysotg_flush_ints(data);
	NVIC_ClearPendingIRQ(irq);
	NVIC_EnableIRQ(irq);

    // Soft reconnect
    dctl.b.sftdiscon = 0;
	data->core->DREGS.DCTL = dctl;
}

void otg_fs_irqhandler()
{
	if (synopsysotg_fsdata) synopsysotg_irq(synopsysotg_fsdata);
	else NVIC_DisableIRQ(OTG_FS_IRQn);
}

void otg_hs_irqhandler()
{
	if (synopsysotg_hsdata) synopsysotg_irq(synopsysotg_hsdata);
	else NVIC_DisableIRQ(OTG_HS_IRQn);
}