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