xref: /linux/drivers/media/usb/stk1160/stk1160-video.c (revision 9025cebf12d1763de36d5e09e2b0a1e4f9b13b28)
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 
20 static unsigned int debug;
21 module_param(debug, int, 0644);
22 MODULE_PARM_DESC(debug, "enable debug messages");
23 
24 static 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 
64 static inline
65 struct 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 
84 static inline
85 void 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 
99 static inline
100 void 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 1) check why we are getting them
111 	 * and 2) add ratelimit.
112 	 *
113 	 * UPDATE: One of the reasons (the only one?) for getting these
114 	 * is incorrect standard (mismatch between expected and configured).
115 	 * So perhaps, we could add a counter for errors. When the counter
116 	 * reaches some value, we simply stop streaming.
117 	 */
118 
119 	len -= 4;
120 	src += 4;
121 
122 	remain = len;
123 
124 	linesdone = buf->pos / bytesperline;
125 	lineoff = buf->pos % bytesperline; /* offset in current line */
126 
127 	if (!buf->odd)
128 		dst += bytesperline;
129 
130 	/* Multiply linesdone by two, to take account of the other field */
131 	dst += linesdone * bytesperline * 2 + lineoff;
132 
133 	/* Copy the remaining of current line */
134 	if (remain < (bytesperline - lineoff))
135 		lencopy = remain;
136 	else
137 		lencopy = bytesperline - lineoff;
138 
139 	/*
140 	 * Check if we have enough space left in the buffer.
141 	 * In that case, we force loop exit after copy.
142 	 */
143 	if (lencopy > buf->bytesused - buf->length) {
144 		lencopy = buf->bytesused - buf->length;
145 		remain = lencopy;
146 	}
147 
148 	/* Check if the copy is done */
149 	if (lencopy == 0 || remain == 0)
150 		return;
151 
152 	/* Let the bug hunt begin! sanity checks! */
153 	if (lencopy < 0) {
154 		stk1160_dbg("copy skipped: negative lencopy\n");
155 		return;
156 	}
157 
158 	if ((unsigned long)dst + lencopy >
159 		(unsigned long)buf->mem + buf->length) {
160 		printk_ratelimited(KERN_WARNING "stk1160: buffer overflow detected\n");
161 		return;
162 	}
163 
164 	memcpy(dst, src, lencopy);
165 
166 	buf->bytesused += lencopy;
167 	buf->pos += lencopy;
168 	remain -= lencopy;
169 
170 	/* Copy current field line by line, interlacing with the other field */
171 	while (remain > 0) {
172 
173 		dst += lencopy + bytesperline;
174 		src += lencopy;
175 
176 		/* Copy one line at a time */
177 		if (remain < bytesperline)
178 			lencopy = remain;
179 		else
180 			lencopy = bytesperline;
181 
182 		/*
183 		 * Check if we have enough space left in the buffer.
184 		 * In that case, we force loop exit after copy.
185 		 */
186 		if (lencopy > buf->bytesused - buf->length) {
187 			lencopy = buf->bytesused - buf->length;
188 			remain = lencopy;
189 		}
190 
191 		/* Check if the copy is done */
192 		if (lencopy == 0 || remain == 0)
193 			return;
194 
195 		if (lencopy < 0) {
196 			printk_ratelimited(KERN_WARNING "stk1160: negative lencopy detected\n");
197 			return;
198 		}
199 
200 		if ((unsigned long)dst + lencopy >
201 			(unsigned long)buf->mem + buf->length) {
202 			printk_ratelimited(KERN_WARNING "stk1160: buffer overflow detected\n");
203 			return;
204 		}
205 
206 		memcpy(dst, src, lencopy);
207 		remain -= lencopy;
208 
209 		buf->bytesused += lencopy;
210 		buf->pos += lencopy;
211 	}
212 }
213 
214 /*
215  * Controls the isoc copy of each urb packet
216  */
217 static void stk1160_process_isoc(struct stk1160 *dev, struct urb *urb)
218 {
219 	int i, len, status;
220 	u8 *p;
221 
222 	if (!dev) {
223 		stk1160_warn("%s called with null device\n", __func__);
224 		return;
225 	}
226 
227 	if (urb->status < 0) {
228 		/* Print status and drop current packet (or field?) */
229 		print_err_status(dev, -1, urb->status);
230 		return;
231 	}
232 
233 	for (i = 0; i < urb->number_of_packets; i++) {
234 		status = urb->iso_frame_desc[i].status;
235 		if (status < 0) {
236 			print_err_status(dev, i, status);
237 			continue;
238 		}
239 
240 		/* Get packet actual length and pointer to data */
241 		p = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
242 		len = urb->iso_frame_desc[i].actual_length;
243 
244 		/* Empty packet */
245 		if (len <= 4)
246 			continue;
247 
248 		/*
249 		 * An 8-byte packet sequence means end of field.
250 		 * So if we don't have any packet, we start receiving one now
251 		 * and if we do have a packet, then we are done with it.
252 		 *
253 		 * These end of field packets are always 0xc0 or 0x80,
254 		 * but not always 8-byte long so we don't check packet length.
255 		 */
256 		if (p[0] == 0xc0) {
257 
258 			/*
259 			 * If first byte is 0xc0 then we received
260 			 * second field, and frame has ended.
261 			 */
262 			if (dev->isoc_ctl.buf != NULL)
263 				stk1160_buffer_done(dev);
264 
265 			dev->isoc_ctl.buf = stk1160_next_buffer(dev);
266 			if (dev->isoc_ctl.buf == NULL)
267 				return;
268 		}
269 
270 		/*
271 		 * If we don't have a buffer here, then it means we
272 		 * haven't found the start mark sequence.
273 		 */
274 		if (dev->isoc_ctl.buf == NULL)
275 			continue;
276 
277 		if (p[0] == 0xc0 || p[0] == 0x80) {
278 
279 			/* We set next packet parity and
280 			 * continue to get next one
281 			 */
282 			dev->isoc_ctl.buf->odd = *p & 0x40;
283 			dev->isoc_ctl.buf->pos = 0;
284 			continue;
285 		}
286 
287 		stk1160_copy_video(dev, p, len);
288 	}
289 }
290 
291 
292 /*
293  * IRQ callback, called by URB callback
294  */
295 static void stk1160_isoc_irq(struct urb *urb)
296 {
297 	int i, rc;
298 	struct stk1160_urb *stk_urb = urb->context;
299 	struct stk1160 *dev = stk_urb->dev;
300 	struct device *dma_dev = stk1160_get_dmadev(dev);
301 
302 	switch (urb->status) {
303 	case 0:
304 		break;
305 	case -ECONNRESET:   /* kill */
306 	case -ENOENT:
307 	case -ESHUTDOWN:
308 		/* TODO: check uvc driver: he frees the queue here */
309 		return;
310 	default:
311 		stk1160_err("urb error! status %d\n", urb->status);
312 		return;
313 	}
314 
315 	invalidate_kernel_vmap_range(stk_urb->transfer_buffer,
316 				     urb->transfer_buffer_length);
317 	dma_sync_sgtable_for_cpu(dma_dev, stk_urb->sgt, DMA_FROM_DEVICE);
318 
319 	stk1160_process_isoc(dev, urb);
320 
321 	/* Reset urb buffers */
322 	for (i = 0; i < urb->number_of_packets; i++) {
323 		urb->iso_frame_desc[i].status = 0;
324 		urb->iso_frame_desc[i].actual_length = 0;
325 	}
326 
327 	dma_sync_sgtable_for_device(dma_dev, stk_urb->sgt, DMA_FROM_DEVICE);
328 	rc = usb_submit_urb(urb, GFP_ATOMIC);
329 	if (rc)
330 		stk1160_err("urb re-submit failed (%d)\n", rc);
331 }
332 
333 /*
334  * Cancel urbs
335  * This function can't be called in atomic context
336  */
337 void stk1160_cancel_isoc(struct stk1160 *dev)
338 {
339 	int i, num_bufs = dev->isoc_ctl.num_bufs;
340 
341 	/*
342 	 * This check is not necessary, but we add it
343 	 * to avoid a spurious debug message
344 	 */
345 	if (!num_bufs)
346 		return;
347 
348 	stk1160_dbg("killing %d urbs...\n", num_bufs);
349 
350 	for (i = 0; i < num_bufs; i++) {
351 
352 		/*
353 		 * To kill urbs we can't be in atomic context.
354 		 * We don't care for NULL pointer since
355 		 * usb_kill_urb allows it.
356 		 */
357 		usb_kill_urb(dev->isoc_ctl.urb_ctl[i].urb);
358 	}
359 
360 	stk1160_dbg("all urbs killed\n");
361 }
362 
363 static void stk_free_urb(struct stk1160 *dev, struct stk1160_urb *stk_urb)
364 {
365 	struct device *dma_dev = stk1160_get_dmadev(dev);
366 
367 	dma_vunmap_noncontiguous(dma_dev, stk_urb->transfer_buffer);
368 	dma_free_noncontiguous(dma_dev, stk_urb->urb->transfer_buffer_length,
369 			       stk_urb->sgt, DMA_FROM_DEVICE);
370 	usb_free_urb(stk_urb->urb);
371 
372 	stk_urb->transfer_buffer = NULL;
373 	stk_urb->sgt = NULL;
374 	stk_urb->urb = NULL;
375 	stk_urb->dev = NULL;
376 	stk_urb->dma = 0;
377 }
378 
379 /*
380  * Releases urb and transfer buffers
381  * Obviusly, associated urb must be killed before releasing it.
382  */
383 void stk1160_free_isoc(struct stk1160 *dev)
384 {
385 	int i, num_bufs = dev->isoc_ctl.num_bufs;
386 
387 	stk1160_dbg("freeing %d urb buffers...\n", num_bufs);
388 
389 	for (i = 0; i < num_bufs; i++)
390 		stk_free_urb(dev, &dev->isoc_ctl.urb_ctl[i]);
391 
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  */
401 void stk1160_uninit_isoc(struct stk1160 *dev)
402 {
403 	stk1160_cancel_isoc(dev);
404 	stk1160_free_isoc(dev);
405 }
406 
407 static int stk1160_fill_urb(struct stk1160 *dev, struct stk1160_urb *stk_urb,
408 			    int sb_size, int max_packets)
409 {
410 	struct device *dma_dev = stk1160_get_dmadev(dev);
411 
412 	stk_urb->urb = usb_alloc_urb(max_packets, GFP_KERNEL);
413 	if (!stk_urb->urb)
414 		return -ENOMEM;
415 	stk_urb->sgt = dma_alloc_noncontiguous(dma_dev, sb_size,
416 					       DMA_FROM_DEVICE, GFP_KERNEL, 0);
417 
418 	/*
419 	 * If the buffer allocation failed, we exit but return 0 since
420 	 * we allow the driver working with less buffers
421 	 */
422 	if (!stk_urb->sgt)
423 		goto free_urb;
424 
425 	stk_urb->transfer_buffer = dma_vmap_noncontiguous(dma_dev, sb_size,
426 							  stk_urb->sgt);
427 	if (!stk_urb->transfer_buffer)
428 		goto free_sgt;
429 
430 	stk_urb->dma = stk_urb->sgt->sgl->dma_address;
431 	stk_urb->dev = dev;
432 	return 0;
433 free_sgt:
434 	dma_free_noncontiguous(dma_dev, sb_size, stk_urb->sgt, DMA_FROM_DEVICE);
435 	stk_urb->sgt = NULL;
436 free_urb:
437 	usb_free_urb(stk_urb->urb);
438 	stk_urb->urb = NULL;
439 
440 	return 0;
441 }
442 /*
443  * Allocate URBs
444  */
445 int stk1160_alloc_isoc(struct stk1160 *dev)
446 {
447 	struct urb *urb;
448 	int i, j, k, sb_size, max_packets, num_bufs;
449 	int ret;
450 
451 	/*
452 	 * It may be necessary to release isoc here,
453 	 * since isoc are only released on disconnection.
454 	 * (see new_pkt_size flag)
455 	 */
456 	if (dev->isoc_ctl.num_bufs)
457 		stk1160_uninit_isoc(dev);
458 
459 	stk1160_dbg("allocating urbs...\n");
460 
461 	num_bufs = STK1160_NUM_BUFS;
462 	max_packets = STK1160_NUM_PACKETS;
463 	sb_size = max_packets * dev->max_pkt_size;
464 
465 	dev->isoc_ctl.buf = NULL;
466 	dev->isoc_ctl.max_pkt_size = dev->max_pkt_size;
467 
468 	/* allocate urbs and transfer buffers */
469 	for (i = 0; i < num_bufs; i++) {
470 
471 		ret = stk1160_fill_urb(dev, &dev->isoc_ctl.urb_ctl[i],
472 				       sb_size, max_packets);
473 		if (ret)
474 			goto free_i_bufs;
475 
476 		urb = dev->isoc_ctl.urb_ctl[i].urb;
477 
478 		if (!urb) {
479 			/* Not enough transfer buffers, so just give up */
480 			if (i < STK1160_MIN_BUFS)
481 				goto free_i_bufs;
482 			goto nomore_tx_bufs;
483 		}
484 		memset(dev->isoc_ctl.urb_ctl[i].transfer_buffer, 0, sb_size);
485 
486 		/*
487 		 * FIXME: Where can I get the endpoint?
488 		 */
489 		urb->dev = dev->udev;
490 		urb->pipe = usb_rcvisocpipe(dev->udev, STK1160_EP_VIDEO);
491 		urb->transfer_buffer = dev->isoc_ctl.urb_ctl[i].transfer_buffer;
492 		urb->transfer_buffer_length = sb_size;
493 		urb->complete = stk1160_isoc_irq;
494 		urb->context = &dev->isoc_ctl.urb_ctl[i];
495 		urb->interval = 1;
496 		urb->start_frame = 0;
497 		urb->number_of_packets = max_packets;
498 		urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
499 		urb->transfer_dma = dev->isoc_ctl.urb_ctl[i].dma;
500 
501 		k = 0;
502 		for (j = 0; j < max_packets; j++) {
503 			urb->iso_frame_desc[j].offset = k;
504 			urb->iso_frame_desc[j].length =
505 					dev->isoc_ctl.max_pkt_size;
506 			k += dev->isoc_ctl.max_pkt_size;
507 		}
508 	}
509 
510 	stk1160_dbg("%d urbs allocated\n", num_bufs);
511 
512 	/* At last we can say we have some buffers */
513 	dev->isoc_ctl.num_bufs = num_bufs;
514 
515 	return 0;
516 
517 nomore_tx_bufs:
518 	/*
519 	 * Failed to allocate desired buffer count. However, we may have
520 	 * enough to work fine, so we just free the extra urb,
521 	 * store the allocated count and keep going, fingers crossed!
522 	 */
523 
524 	stk1160_warn("%d urbs allocated. Trying to continue...\n", i);
525 
526 	dev->isoc_ctl.num_bufs = i;
527 
528 	return 0;
529 
530 free_i_bufs:
531 	/* Save the allocated buffers so far, so we can properly free them */
532 	dev->isoc_ctl.num_bufs = i;
533 	stk1160_free_isoc(dev);
534 	return -ENOMEM;
535 }
536 
537