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 *dev = urb->context;
298
299	switch (urb->status) {
300	case 0:
301		break;
302	case -ECONNRESET:   /* kill */
303	case -ENOENT:
304	case -ESHUTDOWN:
305		/* TODO: check uvc driver: he frees the queue here */
306		return;
307	default:
308		stk1160_err("urb error! status %d\n", urb->status);
309		return;
310	}
311
312	stk1160_process_isoc(dev, urb);
313
314	/* Reset urb buffers */
315	for (i = 0; i < urb->number_of_packets; i++) {
316		urb->iso_frame_desc[i].status = 0;
317		urb->iso_frame_desc[i].actual_length = 0;
318	}
319
320	rc = usb_submit_urb(urb, GFP_ATOMIC);
321	if (rc)
322		stk1160_err("urb re-submit failed (%d)\n", rc);
323}
324
325/*
326 * Cancel urbs
327 * This function can't be called in atomic context
328 */
329void stk1160_cancel_isoc(struct stk1160 *dev)
330{
331	int i, num_bufs = dev->isoc_ctl.num_bufs;
332
333	/*
334	 * This check is not necessary, but we add it
335	 * to avoid a spurious debug message
336	 */
337	if (!num_bufs)
338		return;
339
340	stk1160_dbg("killing %d urbs...\n", num_bufs);
341
342	for (i = 0; i < num_bufs; i++) {
343
344		/*
345		 * To kill urbs we can't be in atomic context.
346		 * We don't care for NULL pointer since
347		 * usb_kill_urb allows it.
348		 */
349		usb_kill_urb(dev->isoc_ctl.urb[i]);
350	}
351
352	stk1160_dbg("all urbs killed\n");
353}
354
355/*
356 * Releases urb and transfer buffers
357 * Obviusly, associated urb must be killed before releasing it.
358 */
359void stk1160_free_isoc(struct stk1160 *dev)
360{
361	struct urb *urb;
362	int i, num_bufs = dev->isoc_ctl.num_bufs;
363
364	stk1160_dbg("freeing %d urb buffers...\n", num_bufs);
365
366	for (i = 0; i < num_bufs; i++) {
367
368		urb = dev->isoc_ctl.urb[i];
369		if (urb) {
370
371			if (dev->isoc_ctl.transfer_buffer[i]) {
372#ifndef CONFIG_DMA_NONCOHERENT
373				usb_free_coherent(dev->udev,
374					urb->transfer_buffer_length,
375					dev->isoc_ctl.transfer_buffer[i],
376					urb->transfer_dma);
377#else
378				kfree(dev->isoc_ctl.transfer_buffer[i]);
379#endif
380			}
381			usb_free_urb(urb);
382			dev->isoc_ctl.urb[i] = NULL;
383		}
384		dev->isoc_ctl.transfer_buffer[i] = NULL;
385	}
386
387	kfree(dev->isoc_ctl.urb);
388	kfree(dev->isoc_ctl.transfer_buffer);
389
390	dev->isoc_ctl.urb = NULL;
391	dev->isoc_ctl.transfer_buffer = NULL;
392	dev->isoc_ctl.num_bufs = 0;
393
394	stk1160_dbg("all urb buffers freed\n");
395}
396
397/*
398 * Helper for cancelling and freeing urbs
399 * This function can't be called in atomic context
400 */
401void stk1160_uninit_isoc(struct stk1160 *dev)
402{
403	stk1160_cancel_isoc(dev);
404	stk1160_free_isoc(dev);
405}
406
407/*
408 * Allocate URBs
409 */
410int stk1160_alloc_isoc(struct stk1160 *dev)
411{
412	struct urb *urb;
413	int i, j, k, sb_size, max_packets, num_bufs;
414
415	/*
416	 * It may be necessary to release isoc here,
417	 * since isoc are only released on disconnection.
418	 * (see new_pkt_size flag)
419	 */
420	if (dev->isoc_ctl.num_bufs)
421		stk1160_uninit_isoc(dev);
422
423	stk1160_dbg("allocating urbs...\n");
424
425	num_bufs = STK1160_NUM_BUFS;
426	max_packets = STK1160_NUM_PACKETS;
427	sb_size = max_packets * dev->max_pkt_size;
428
429	dev->isoc_ctl.buf = NULL;
430	dev->isoc_ctl.max_pkt_size = dev->max_pkt_size;
431	dev->isoc_ctl.urb = kcalloc(num_bufs, sizeof(void *), GFP_KERNEL);
432	if (!dev->isoc_ctl.urb) {
433		stk1160_err("out of memory for urb array\n");
434		return -ENOMEM;
435	}
436
437	dev->isoc_ctl.transfer_buffer = kcalloc(num_bufs, sizeof(void *),
438						GFP_KERNEL);
439	if (!dev->isoc_ctl.transfer_buffer) {
440		stk1160_err("out of memory for usb transfers\n");
441		kfree(dev->isoc_ctl.urb);
442		return -ENOMEM;
443	}
444
445	/* allocate urbs and transfer buffers */
446	for (i = 0; i < num_bufs; i++) {
447
448		urb = usb_alloc_urb(max_packets, GFP_KERNEL);
449		if (!urb)
450			goto free_i_bufs;
451		dev->isoc_ctl.urb[i] = urb;
452
453#ifndef CONFIG_DMA_NONCOHERENT
454		dev->isoc_ctl.transfer_buffer[i] = usb_alloc_coherent(dev->udev,
455			sb_size, GFP_KERNEL, &urb->transfer_dma);
456#else
457		dev->isoc_ctl.transfer_buffer[i] = kmalloc(sb_size, GFP_KERNEL);
458#endif
459		if (!dev->isoc_ctl.transfer_buffer[i]) {
460			stk1160_err("cannot alloc %d bytes for tx[%d] buffer\n",
461				sb_size, i);
462
463			/* Not enough transfer buffers, so just give up */
464			if (i < STK1160_MIN_BUFS)
465				goto free_i_bufs;
466			goto nomore_tx_bufs;
467		}
468		memset(dev->isoc_ctl.transfer_buffer[i], 0, sb_size);
469
470		/*
471		 * FIXME: Where can I get the endpoint?
472		 */
473		urb->dev = dev->udev;
474		urb->pipe = usb_rcvisocpipe(dev->udev, STK1160_EP_VIDEO);
475		urb->transfer_buffer = dev->isoc_ctl.transfer_buffer[i];
476		urb->transfer_buffer_length = sb_size;
477		urb->complete = stk1160_isoc_irq;
478		urb->context = dev;
479		urb->interval = 1;
480		urb->start_frame = 0;
481		urb->number_of_packets = max_packets;
482#ifndef CONFIG_DMA_NONCOHERENT
483		urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
484#else
485		urb->transfer_flags = URB_ISO_ASAP;
486#endif
487
488		k = 0;
489		for (j = 0; j < max_packets; j++) {
490			urb->iso_frame_desc[j].offset = k;
491			urb->iso_frame_desc[j].length =
492					dev->isoc_ctl.max_pkt_size;
493			k += dev->isoc_ctl.max_pkt_size;
494		}
495	}
496
497	stk1160_dbg("%d urbs allocated\n", num_bufs);
498
499	/* At last we can say we have some buffers */
500	dev->isoc_ctl.num_bufs = num_bufs;
501
502	return 0;
503
504nomore_tx_bufs:
505	/*
506	 * Failed to allocate desired buffer count. However, we may have
507	 * enough to work fine, so we just free the extra urb,
508	 * store the allocated count and keep going, fingers crossed!
509	 */
510	usb_free_urb(dev->isoc_ctl.urb[i]);
511	dev->isoc_ctl.urb[i] = NULL;
512
513	stk1160_warn("%d urbs allocated. Trying to continue...\n", i - 1);
514
515	dev->isoc_ctl.num_bufs = i - 1;
516
517	return 0;
518
519free_i_bufs:
520	/* Save the allocated buffers so far, so we can properly free them */
521	dev->isoc_ctl.num_bufs = i+1;
522	stk1160_free_isoc(dev);
523	return -ENOMEM;
524}
525
526