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