1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * STK1160 driver
4 *
5 * Copyright (C) 2012 Ezequiel Garcia
6 * <elezegarcia--a.t--gmail.com>
7 *
8 * Based on Easycap driver by R.M. Thomas
9 *	Copyright (C) 2010 R.M. Thomas
10 *	<rmthomas--a.t--sciolus.org>
11 */
12
13#include <linux/module.h>
14#include <linux/usb.h>
15#include <linux/slab.h>
16#include <linux/ratelimit.h>
17
18#include "stk1160.h"
19
20static unsigned int debug;
21module_param(debug, int, 0644);
22MODULE_PARM_DESC(debug, "enable debug messages");
23
24static inline void print_err_status(struct stk1160 *dev,
25				     int packet, int status)
26{
27	char *errmsg = "Unknown";
28
29	switch (status) {
30	case -ENOENT:
31		errmsg = "unlinked synchronously";
32		break;
33	case -ECONNRESET:
34		errmsg = "unlinked asynchronously";
35		break;
36	case -ENOSR:
37		errmsg = "Buffer error (overrun)";
38		break;
39	case -EPIPE:
40		errmsg = "Stalled (device not responding)";
41		break;
42	case -EOVERFLOW:
43		errmsg = "Babble (bad cable?)";
44		break;
45	case -EPROTO:
46		errmsg = "Bit-stuff error (bad cable?)";
47		break;
48	case -EILSEQ:
49		errmsg = "CRC/Timeout (could be anything)";
50		break;
51	case -ETIME:
52		errmsg = "Device does not respond";
53		break;
54	}
55
56	if (packet < 0)
57		printk_ratelimited(KERN_WARNING "URB status %d [%s].\n",
58				status, errmsg);
59	else
60		printk_ratelimited(KERN_INFO "URB packet %d, status %d [%s].\n",
61			       packet, status, errmsg);
62}
63
64static inline
65struct stk1160_buffer *stk1160_next_buffer(struct stk1160 *dev)
66{
67	struct stk1160_buffer *buf = NULL;
68	unsigned long flags = 0;
69
70	/* Current buffer must be NULL when this functions gets called */
71	WARN_ON(dev->isoc_ctl.buf);
72
73	spin_lock_irqsave(&dev->buf_lock, flags);
74	if (!list_empty(&dev->avail_bufs)) {
75		buf = list_first_entry(&dev->avail_bufs,
76				struct stk1160_buffer, list);
77		list_del(&buf->list);
78	}
79	spin_unlock_irqrestore(&dev->buf_lock, flags);
80
81	return buf;
82}
83
84static inline
85void stk1160_buffer_done(struct stk1160 *dev)
86{
87	struct stk1160_buffer *buf = dev->isoc_ctl.buf;
88
89	buf->vb.sequence = dev->sequence++;
90	buf->vb.field = V4L2_FIELD_INTERLACED;
91	buf->vb.vb2_buf.timestamp = ktime_get_ns();
92
93	vb2_set_plane_payload(&buf->vb.vb2_buf, 0, buf->bytesused);
94	vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_DONE);
95
96	dev->isoc_ctl.buf = NULL;
97}
98
99static inline
100void stk1160_copy_video(struct stk1160 *dev, u8 *src, int len)
101{
102	int linesdone, lineoff, lencopy;
103	int bytesperline = dev->width * 2;
104	struct stk1160_buffer *buf = dev->isoc_ctl.buf;
105	u8 *dst = buf->mem;
106	int remain;
107
108	/*
109	 * TODO: These stk1160_dbg are very spammy!
110	 * We should check why we are getting them.
111	 *
112	 * UPDATE: One of the reasons (the only one?) for getting these
113	 * is incorrect standard (mismatch between expected and configured).
114	 * So perhaps, we could add a counter for errors. When the counter
115	 * reaches some value, we simply stop streaming.
116	 */
117
118	len -= 4;
119	src += 4;
120
121	remain = len;
122
123	linesdone = buf->pos / bytesperline;
124	lineoff = buf->pos % bytesperline; /* offset in current line */
125
126	if (!buf->odd)
127		dst += bytesperline;
128
129	/* Multiply linesdone by two, to take account of the other field */
130	dst += linesdone * bytesperline * 2 + lineoff;
131
132	/* Copy the remaining of current line */
133	if (remain < (bytesperline - lineoff))
134		lencopy = remain;
135	else
136		lencopy = bytesperline - lineoff;
137
138	/*
139	 * Check if we have enough space left in the buffer.
140	 * In that case, we force loop exit after copy.
141	 */
142	if (lencopy > buf->bytesused - buf->length) {
143		lencopy = buf->bytesused - buf->length;
144		remain = lencopy;
145	}
146
147	/* Check if the copy is done */
148	if (lencopy == 0 || remain == 0)
149		return;
150
151	/* Let the bug hunt begin! sanity checks! */
152	if (lencopy < 0) {
153		printk_ratelimited(KERN_DEBUG "copy skipped: negative lencopy\n");
154		return;
155	}
156
157	if ((unsigned long)dst + lencopy >
158		(unsigned long)buf->mem + buf->length) {
159		printk_ratelimited(KERN_WARNING "stk1160: buffer overflow detected\n");
160		return;
161	}
162
163	memcpy(dst, src, lencopy);
164
165	buf->bytesused += lencopy;
166	buf->pos += lencopy;
167	remain -= lencopy;
168
169	/* Copy current field line by line, interlacing with the other field */
170	while (remain > 0) {
171
172		dst += lencopy + bytesperline;
173		src += lencopy;
174
175		/* Copy one line at a time */
176		if (remain < bytesperline)
177			lencopy = remain;
178		else
179			lencopy = bytesperline;
180
181		/*
182		 * Check if we have enough space left in the buffer.
183		 * In that case, we force loop exit after copy.
184		 */
185		if (lencopy > buf->bytesused - buf->length) {
186			lencopy = buf->bytesused - buf->length;
187			remain = lencopy;
188		}
189
190		/* Check if the copy is done */
191		if (lencopy == 0 || remain == 0)
192			return;
193
194		if (lencopy < 0) {
195			printk_ratelimited(KERN_WARNING "stk1160: negative lencopy detected\n");
196			return;
197		}
198
199		if ((unsigned long)dst + lencopy >
200			(unsigned long)buf->mem + buf->length) {
201			printk_ratelimited(KERN_WARNING "stk1160: buffer overflow detected\n");
202			return;
203		}
204
205		memcpy(dst, src, lencopy);
206		remain -= lencopy;
207
208		buf->bytesused += lencopy;
209		buf->pos += lencopy;
210	}
211}
212
213/*
214 * Controls the isoc copy of each urb packet
215 */
216static void stk1160_process_isoc(struct stk1160 *dev, struct urb *urb)
217{
218	int i, len, status;
219	u8 *p;
220
221	if (!dev) {
222		stk1160_warn("%s called with null device\n", __func__);
223		return;
224	}
225
226	if (urb->status < 0) {
227		/* Print status and drop current packet (or field?) */
228		print_err_status(dev, -1, urb->status);
229		return;
230	}
231
232	for (i = 0; i < urb->number_of_packets; i++) {
233		status = urb->iso_frame_desc[i].status;
234		if (status < 0) {
235			print_err_status(dev, i, status);
236			continue;
237		}
238
239		/* Get packet actual length and pointer to data */
240		p = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
241		len = urb->iso_frame_desc[i].actual_length;
242
243		/* Empty packet */
244		if (len <= 4)
245			continue;
246
247		/*
248		 * An 8-byte packet sequence means end of field.
249		 * So if we don't have any packet, we start receiving one now
250		 * and if we do have a packet, then we are done with it.
251		 *
252		 * These end of field packets are always 0xc0 or 0x80,
253		 * but not always 8-byte long so we don't check packet length.
254		 */
255		if (p[0] == 0xc0) {
256
257			/*
258			 * If first byte is 0xc0 then we received
259			 * second field, and frame has ended.
260			 */
261			if (dev->isoc_ctl.buf != NULL)
262				stk1160_buffer_done(dev);
263
264			dev->isoc_ctl.buf = stk1160_next_buffer(dev);
265			if (dev->isoc_ctl.buf == NULL)
266				return;
267		}
268
269		/*
270		 * If we don't have a buffer here, then it means we
271		 * haven't found the start mark sequence.
272		 */
273		if (dev->isoc_ctl.buf == NULL)
274			continue;
275
276		if (p[0] == 0xc0 || p[0] == 0x80) {
277
278			/* We set next packet parity and
279			 * continue to get next one
280			 */
281			dev->isoc_ctl.buf->odd = *p & 0x40;
282			dev->isoc_ctl.buf->pos = 0;
283			continue;
284		}
285
286		stk1160_copy_video(dev, p, len);
287	}
288}
289
290
291/*
292 * IRQ callback, called by URB callback
293 */
294static void stk1160_isoc_irq(struct urb *urb)
295{
296	int i, rc;
297	struct stk1160_urb *stk_urb = urb->context;
298	struct stk1160 *dev = stk_urb->dev;
299	struct device *dma_dev = stk1160_get_dmadev(dev);
300
301	switch (urb->status) {
302	case 0:
303		break;
304	case -ECONNRESET:   /* kill */
305	case -ENOENT:
306	case -ESHUTDOWN:
307		/* TODO: check uvc driver: he frees the queue here */
308		return;
309	default:
310		stk1160_err("urb error! status %d\n", urb->status);
311		return;
312	}
313
314	invalidate_kernel_vmap_range(stk_urb->transfer_buffer,
315				     urb->transfer_buffer_length);
316	dma_sync_sgtable_for_cpu(dma_dev, stk_urb->sgt, DMA_FROM_DEVICE);
317
318	stk1160_process_isoc(dev, urb);
319
320	/* Reset urb buffers */
321	for (i = 0; i < urb->number_of_packets; i++) {
322		urb->iso_frame_desc[i].status = 0;
323		urb->iso_frame_desc[i].actual_length = 0;
324	}
325
326	dma_sync_sgtable_for_device(dma_dev, stk_urb->sgt, DMA_FROM_DEVICE);
327	rc = usb_submit_urb(urb, GFP_ATOMIC);
328	if (rc)
329		stk1160_err("urb re-submit failed (%d)\n", rc);
330}
331
332/*
333 * Cancel urbs
334 * This function can't be called in atomic context
335 */
336void stk1160_cancel_isoc(struct stk1160 *dev)
337{
338	int i, num_bufs = dev->isoc_ctl.num_bufs;
339
340	/*
341	 * This check is not necessary, but we add it
342	 * to avoid a spurious debug message
343	 */
344	if (!num_bufs)
345		return;
346
347	stk1160_dbg("killing %d urbs...\n", num_bufs);
348
349	for (i = 0; i < num_bufs; i++) {
350
351		/*
352		 * To kill urbs we can't be in atomic context.
353		 * We don't care for NULL pointer since
354		 * usb_kill_urb allows it.
355		 */
356		usb_kill_urb(dev->isoc_ctl.urb_ctl[i].urb);
357	}
358
359	stk1160_dbg("all urbs killed\n");
360}
361
362static void stk_free_urb(struct stk1160 *dev, struct stk1160_urb *stk_urb)
363{
364	struct device *dma_dev = stk1160_get_dmadev(dev);
365
366	dma_vunmap_noncontiguous(dma_dev, stk_urb->transfer_buffer);
367	dma_free_noncontiguous(dma_dev, stk_urb->urb->transfer_buffer_length,
368			       stk_urb->sgt, DMA_FROM_DEVICE);
369	usb_free_urb(stk_urb->urb);
370
371	stk_urb->transfer_buffer = NULL;
372	stk_urb->sgt = NULL;
373	stk_urb->urb = NULL;
374	stk_urb->dev = NULL;
375	stk_urb->dma = 0;
376}
377
378/*
379 * Releases urb and transfer buffers
380 * Obviusly, associated urb must be killed before releasing it.
381 */
382void stk1160_free_isoc(struct stk1160 *dev)
383{
384	int i, num_bufs = dev->isoc_ctl.num_bufs;
385
386	stk1160_dbg("freeing %d urb buffers...\n", num_bufs);
387
388	for (i = 0; i < num_bufs; i++)
389		stk_free_urb(dev, &dev->isoc_ctl.urb_ctl[i]);
390
391	dev->isoc_ctl.num_bufs = 0;
392
393	stk1160_dbg("all urb buffers freed\n");
394}
395
396/*
397 * Helper for cancelling and freeing urbs
398 * This function can't be called in atomic context
399 */
400void stk1160_uninit_isoc(struct stk1160 *dev)
401{
402	stk1160_cancel_isoc(dev);
403	stk1160_free_isoc(dev);
404}
405
406static int stk1160_fill_urb(struct stk1160 *dev, struct stk1160_urb *stk_urb,
407			    int sb_size, int max_packets)
408{
409	struct device *dma_dev = stk1160_get_dmadev(dev);
410
411	stk_urb->urb = usb_alloc_urb(max_packets, GFP_KERNEL);
412	if (!stk_urb->urb)
413		return -ENOMEM;
414	stk_urb->sgt = dma_alloc_noncontiguous(dma_dev, sb_size,
415					       DMA_FROM_DEVICE, GFP_KERNEL, 0);
416
417	/*
418	 * If the buffer allocation failed, we exit but return 0 since
419	 * we allow the driver working with less buffers
420	 */
421	if (!stk_urb->sgt)
422		goto free_urb;
423
424	stk_urb->transfer_buffer = dma_vmap_noncontiguous(dma_dev, sb_size,
425							  stk_urb->sgt);
426	if (!stk_urb->transfer_buffer)
427		goto free_sgt;
428
429	stk_urb->dma = stk_urb->sgt->sgl->dma_address;
430	stk_urb->dev = dev;
431	return 0;
432free_sgt:
433	dma_free_noncontiguous(dma_dev, sb_size, stk_urb->sgt, DMA_FROM_DEVICE);
434	stk_urb->sgt = NULL;
435free_urb:
436	usb_free_urb(stk_urb->urb);
437	stk_urb->urb = NULL;
438
439	return 0;
440}
441/*
442 * Allocate URBs
443 */
444int stk1160_alloc_isoc(struct stk1160 *dev)
445{
446	struct urb *urb;
447	int i, j, k, sb_size, max_packets, num_bufs;
448	int ret;
449
450	/*
451	 * It may be necessary to release isoc here,
452	 * since isoc are only released on disconnection.
453	 * (see new_pkt_size flag)
454	 */
455	if (dev->isoc_ctl.num_bufs)
456		stk1160_uninit_isoc(dev);
457
458	stk1160_dbg("allocating urbs...\n");
459
460	num_bufs = STK1160_NUM_BUFS;
461	max_packets = STK1160_NUM_PACKETS;
462	sb_size = max_packets * dev->max_pkt_size;
463
464	dev->isoc_ctl.buf = NULL;
465	dev->isoc_ctl.max_pkt_size = dev->max_pkt_size;
466
467	/* allocate urbs and transfer buffers */
468	for (i = 0; i < num_bufs; i++) {
469
470		ret = stk1160_fill_urb(dev, &dev->isoc_ctl.urb_ctl[i],
471				       sb_size, max_packets);
472		if (ret)
473			goto free_i_bufs;
474
475		urb = dev->isoc_ctl.urb_ctl[i].urb;
476
477		if (!urb) {
478			/* Not enough transfer buffers, so just give up */
479			if (i < STK1160_MIN_BUFS)
480				goto free_i_bufs;
481			goto nomore_tx_bufs;
482		}
483		memset(dev->isoc_ctl.urb_ctl[i].transfer_buffer, 0, sb_size);
484
485		/*
486		 * FIXME: Where can I get the endpoint?
487		 */
488		urb->dev = dev->udev;
489		urb->pipe = usb_rcvisocpipe(dev->udev, STK1160_EP_VIDEO);
490		urb->transfer_buffer = dev->isoc_ctl.urb_ctl[i].transfer_buffer;
491		urb->transfer_buffer_length = sb_size;
492		urb->complete = stk1160_isoc_irq;
493		urb->context = &dev->isoc_ctl.urb_ctl[i];
494		urb->interval = 1;
495		urb->start_frame = 0;
496		urb->number_of_packets = max_packets;
497		urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
498		urb->transfer_dma = dev->isoc_ctl.urb_ctl[i].dma;
499
500		k = 0;
501		for (j = 0; j < max_packets; j++) {
502			urb->iso_frame_desc[j].offset = k;
503			urb->iso_frame_desc[j].length =
504					dev->isoc_ctl.max_pkt_size;
505			k += dev->isoc_ctl.max_pkt_size;
506		}
507	}
508
509	stk1160_dbg("%d urbs allocated\n", num_bufs);
510
511	/* At last we can say we have some buffers */
512	dev->isoc_ctl.num_bufs = num_bufs;
513
514	return 0;
515
516nomore_tx_bufs:
517	/*
518	 * Failed to allocate desired buffer count. However, we may have
519	 * enough to work fine, so we just free the extra urb,
520	 * store the allocated count and keep going, fingers crossed!
521	 */
522
523	stk1160_warn("%d urbs allocated. Trying to continue...\n", i);
524
525	dev->isoc_ctl.num_bufs = i;
526
527	return 0;
528
529free_i_bufs:
530	/* Save the allocated buffers so far, so we can properly free them */
531	dev->isoc_ctl.num_bufs = i;
532	stk1160_free_isoc(dev);
533	return -ENOMEM;
534}
535
536