summaryrefslogtreecommitdiffstats
path: root/usb/txhandler.c
blob: 89cd0cf1596ff9d010dd90bb227d3015b31fc38b (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
/*
 * usb/txhandler.c -- USB Transmission Handling
 *
 * Copyright (C) 2017 Tomasz Kramkowski <tk@the-tk.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 3 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, see <http://www.gnu.org/licenses/>.
 */
#include <reg/usbotg.h>
#include <stdbool.h>
#include <stddef.h>

#include "bdt.h"
#include "txhandler.h"

/* puttx: place data in the current buffer descriptor */
static bool puttx(struct tx_ctx *tx, void *data, size_t size)
{
	if (GET_BIT(tx->bdt[tx->odd].desc, BD_OWN))
		return false;

	tx->bdt[tx->odd].addr = data;
	tx->bdt[tx->odd].desc = USB0_BD_INIT(size, tx->data01);
	tx->odd = !tx->odd;
	tx->data01 = !tx->data01;

	return true;
}

/* tx_push: attempt to push rest of the current transmission into a BD */
bool tx_push(struct tx_ctx *tx)
{
	size_t size = tx->size;

	if (tx->data == NULL)
		return false;

	if (size > tx->max)
		size = tx->max;

	if (!puttx(tx, tx->data, size))
		return false;

	tx->data = (char *)tx->data + size;
	tx->size -= size;

	if (tx->size == 0 && size < tx->max)
		tx->data = NULL;

	return true;
}

/* tx_que: enqueue a transmission */
void tx_que(struct tx_ctx *tx, void *data, size_t size)
{
	if (data == NULL || size == 0) {
		puttx(tx, NULL, 0);
		return;
	}

	tx->data = data;
	tx->size = size;

	while (tx_push(tx))
		;
}

/* tx_isempty: check if there's nothing left to transmit */
bool tx_isempty(struct tx_ctx *tx)
{
	return tx->data == NULL;
}