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