1 /*
2  * STK1160 driver
3  *
4  * Copyright (C) 2012 Ezequiel Garcia
5  * <elezegarcia--a.t--gmail.com>
6  *
7  * Based on Easycap driver by R.M. Thomas
8  *	Copyright (C) 2010 R.M. Thomas
9  *	<rmthomas--a.t--sciolus.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  */
22 
23 #include <linux/module.h>
24 #include <linux/usb.h>
25 #include <linux/slab.h>
26 #include <linux/ratelimit.h>
27 
28 #include "stk1160.h"
29 
30 static unsigned int debug;
31 module_param(debug, int, 0644);
32 MODULE_PARM_DESC(debug, "enable debug messages");
33 
34 static inline void print_err_status(struct stk1160 *dev,
35 				     int packet, int status)
36 {
37 	char *errmsg = "Unknown";
38 
39 	switch (status) {
40 	case -ENOENT:
41 		errmsg = "unlinked synchronuously";
42 		break;
43 	case -ECONNRESET:
44 		errmsg = "unlinked asynchronuously";
45 		break;
46 	case -ENOSR:
47 		errmsg = "Buffer error (overrun)";
48 		break;
49 	case -EPIPE:
50 		errmsg = "Stalled (device not responding)";
51 		break;
52 	case -EOVERFLOW:
53 		errmsg = "Babble (bad cable?)";
54 		break;
55 	case -EPROTO:
56 		errmsg = "Bit-stuff error (bad cable?)";
57 		break;
58 	case -EILSEQ:
59 		errmsg = "CRC/Timeout (could be anything)";
60 		break;
61 	case -ETIME:
62 		errmsg = "Device does not respond";
63 		break;
64 	}
65 
66 	if (packet < 0)
67 		printk_ratelimited(KERN_WARNING "URB status %d [%s].\n",
68 				status, errmsg);
69 	else
70 		printk_ratelimited(KERN_INFO "URB packet %d, status %d [%s].\n",
71 			       packet, status, errmsg);
72 }
73 
74 static inline
75 struct stk1160_buffer *stk1160_next_buffer(struct stk1160 *dev)
76 {
77 	struct stk1160_buffer *buf = NULL;
78 	unsigned long flags = 0;
79 
80 	/* Current buffer must be NULL when this functions gets called */
81 	WARN_ON(dev->isoc_ctl.buf);
82 
83 	spin_lock_irqsave(&dev->buf_lock, flags);
84 	if (!list_empty(&dev->avail_bufs)) {
85 		buf = list_first_entry(&dev->avail_bufs,
86 				struct stk1160_buffer, list);
87 		list_del(&buf->list);
88 	}
89 	spin_unlock_irqrestore(&dev->buf_lock, flags);
90 
91 	return buf;
92 }
93 
94 static inline
95 void stk1160_buffer_done(struct stk1160 *dev)
96 {
97 	struct stk1160_buffer *buf = dev->isoc_ctl.buf;
98 
99 	buf->vb.sequence = dev->sequence++;
100 	buf->vb.field = V4L2_FIELD_INTERLACED;
101 	buf->vb.vb2_buf.timestamp = ktime_get_ns();
102 
103 	vb2_set_plane_payload(&buf->vb.vb2_buf, 0, buf->bytesused);
104 	vb2_buffer_done(&buf->vb.vb2_buf, VB2_BUF_STATE_DONE);
105 
106 	dev->isoc_ctl.buf = NULL;
107 }
108 
109 static inline
110 void stk1160_copy_video(struct stk1160 *dev, u8 *src, int len)
111 {
112 	int linesdone, lineoff, lencopy;
113 	int bytesperline = dev->width * 2;
114 	struct stk1160_buffer *buf = dev->isoc_ctl.buf;
115 	u8 *dst = buf->mem;
116 	int remain;
117 
118 	/*
119 	 * TODO: These stk1160_dbg are very spammy!
120 	 * We should 1) check why we are getting them
121 	 * and 2) add ratelimit.
122 	 *
123 	 * UPDATE: One of the reasons (the only one?) for getting these
124 	 * is incorrect standard (mismatch between expected and configured).
125 	 * So perhaps, we could add a counter for errors. When the counter
126 	 * reaches some value, we simply stop streaming.
127 	 */
128 
129 	len -= 4;
130 	src += 4;
131 
132 	remain = len;
133 
134 	linesdone = buf->pos / bytesperline;
135 	lineoff = buf->pos % bytesperline; /* offset in current line */
136 
137 	if (!buf->odd)
138 		dst += bytesperline;
139 
140 	/* Multiply linesdone by two, to take account of the other field */
141 	dst += linesdone * bytesperline * 2 + lineoff;
142 
143 	/* Copy the remaining of current line */
144 	if (remain < (bytesperline - lineoff))
145 		lencopy = remain;
146 	else
147 		lencopy = bytesperline - lineoff;
148 
149 	/*
150 	 * Check if we have enough space left in the buffer.
151 	 * In that case, we force loop exit after copy.
152 	 */
153 	if (lencopy > buf->bytesused - buf->length) {
154 		lencopy = buf->bytesused - buf->length;
155 		remain = lencopy;
156 	}
157 
158 	/* Check if the copy is done */
159 	if (lencopy == 0 || remain == 0)
160 		return;
161 
162 	/* Let the bug hunt begin! sanity checks! */
163 	if (lencopy < 0) {
164 		stk1160_dbg("copy skipped: negative lencopy\n");
165 		return;
166 	}
167 
168 	if ((unsigned long)dst + lencopy >
169 		(unsigned long)buf->mem + buf->length) {
170 		printk_ratelimited(KERN_WARNING "stk1160: buffer overflow detected\n");
171 		return;
172 	}
173 
174 	memcpy(dst, src, lencopy);
175 
176 	buf->bytesused += lencopy;
177 	buf->pos += lencopy;
178 	remain -= lencopy;
179 
180 	/* Copy current field line by line, interlacing with the other field */
181 	while (remain > 0) {
182 
183 		dst += lencopy + bytesperline;
184 		src += lencopy;
185 
186 		/* Copy one line at a time */
187 		if (remain < bytesperline)
188 			lencopy = remain;
189 		else
190 			lencopy = bytesperline;
191 
192 		/*
193 		 * Check if we have enough space left in the buffer.
194 		 * In that case, we force loop exit after copy.
195 		 */
196 		if (lencopy > buf->bytesused - buf->length) {
197 			lencopy = buf->bytesused - buf->length;
198 			remain = lencopy;
199 		}
200 
201 		/* Check if the copy is done */
202 		if (lencopy == 0 || remain == 0)
203 			return;
204 
205 		if (lencopy < 0) {
206 			printk_ratelimited(KERN_WARNING "stk1160: negative lencopy detected\n");
207 			return;
208 		}
209 
210 		if ((unsigned long)dst + lencopy >
211 			(unsigned long)buf->mem + buf->length) {
212 			printk_ratelimited(KERN_WARNING "stk1160: buffer overflow detected\n");
213 			return;
214 		}
215 
216 		memcpy(dst, src, lencopy);
217 		remain -= lencopy;
218 
219 		buf->bytesused += lencopy;
220 		buf->pos += lencopy;
221 	}
222 }
223 
224 /*
225  * Controls the isoc copy of each urb packet
226  */
227 static void stk1160_process_isoc(struct stk1160 *dev, struct urb *urb)
228 {
229 	int i, len, status;
230 	u8 *p;
231 
232 	if (!dev) {
233 		stk1160_warn("%s called with null device\n", __func__);
234 		return;
235 	}
236 
237 	if (urb->status < 0) {
238 		/* Print status and drop current packet (or field?) */
239 		print_err_status(dev, -1, urb->status);
240 		return;
241 	}
242 
243 	for (i = 0; i < urb->number_of_packets; i++) {
244 		status = urb->iso_frame_desc[i].status;
245 		if (status < 0) {
246 			print_err_status(dev, i, status);
247 			continue;
248 		}
249 
250 		/* Get packet actual length and pointer to data */
251 		p = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
252 		len = urb->iso_frame_desc[i].actual_length;
253 
254 		/* Empty packet */
255 		if (len <= 4)
256 			continue;
257 
258 		/*
259 		 * An 8-byte packet sequence means end of field.
260 		 * So if we don't have any packet, we start receiving one now
261 		 * and if we do have a packet, then we are done with it.
262 		 *
263 		 * These end of field packets are always 0xc0 or 0x80,
264 		 * but not always 8-byte long so we don't check packet length.
265 		 */
266 		if (p[0] == 0xc0) {
267 
268 			/*
269 			 * If first byte is 0xc0 then we received
270 			 * second field, and frame has ended.
271 			 */
272 			if (dev->isoc_ctl.buf != NULL)
273 				stk1160_buffer_done(dev);
274 
275 			dev->isoc_ctl.buf = stk1160_next_buffer(dev);
276 			if (dev->isoc_ctl.buf == NULL)
277 				return;
278 		}
279 
280 		/*
281 		 * If we don't have a buffer here, then it means we
282 		 * haven't found the start mark sequence.
283 		 */
284 		if (dev->isoc_ctl.buf == NULL)
285 			continue;
286 
287 		if (p[0] == 0xc0 || p[0] == 0x80) {
288 
289 			/* We set next packet parity and
290 			 * continue to get next one
291 			 */
292 			dev->isoc_ctl.buf->odd = *p & 0x40;
293 			dev->isoc_ctl.buf->pos = 0;
294 			continue;
295 		}
296 
297 		stk1160_copy_video(dev, p, len);
298 	}
299 }
300 
301 
302 /*
303  * IRQ callback, called by URB callback
304  */
305 static void stk1160_isoc_irq(struct urb *urb)
306 {
307 	int i, rc;
308 	struct stk1160 *dev = urb->context;
309 
310 	switch (urb->status) {
311 	case 0:
312 		break;
313 	case -ECONNRESET:   /* kill */
314 	case -ENOENT:
315 	case -ESHUTDOWN:
316 		/* TODO: check uvc driver: he frees the queue here */
317 		return;
318 	default:
319 		stk1160_err("urb error! status %d\n", urb->status);
320 		return;
321 	}
322 
323 	stk1160_process_isoc(dev, urb);
324 
325 	/* Reset urb buffers */
326 	for (i = 0; i < urb->number_of_packets; i++) {
327 		urb->iso_frame_desc[i].status = 0;
328 		urb->iso_frame_desc[i].actual_length = 0;
329 	}
330 
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[i]);
361 	}
362 
363 	stk1160_dbg("all urbs killed\n");
364 }
365 
366 /*
367  * Releases urb and transfer buffers
368  * Obviusly, associated urb must be killed before releasing it.
369  */
370 void stk1160_free_isoc(struct stk1160 *dev)
371 {
372 	struct urb *urb;
373 	int i, num_bufs = dev->isoc_ctl.num_bufs;
374 
375 	stk1160_dbg("freeing %d urb buffers...\n", num_bufs);
376 
377 	for (i = 0; i < num_bufs; i++) {
378 
379 		urb = dev->isoc_ctl.urb[i];
380 		if (urb) {
381 
382 			if (dev->isoc_ctl.transfer_buffer[i]) {
383 #ifndef CONFIG_DMA_NONCOHERENT
384 				usb_free_coherent(dev->udev,
385 					urb->transfer_buffer_length,
386 					dev->isoc_ctl.transfer_buffer[i],
387 					urb->transfer_dma);
388 #else
389 				kfree(dev->isoc_ctl.transfer_buffer[i]);
390 #endif
391 			}
392 			usb_free_urb(urb);
393 			dev->isoc_ctl.urb[i] = NULL;
394 		}
395 		dev->isoc_ctl.transfer_buffer[i] = NULL;
396 	}
397 
398 	kfree(dev->isoc_ctl.urb);
399 	kfree(dev->isoc_ctl.transfer_buffer);
400 
401 	dev->isoc_ctl.urb = NULL;
402 	dev->isoc_ctl.transfer_buffer = NULL;
403 	dev->isoc_ctl.num_bufs = 0;
404 
405 	stk1160_dbg("all urb buffers freed\n");
406 }
407 
408 /*
409  * Helper for cancelling and freeing urbs
410  * This function can't be called in atomic context
411  */
412 void stk1160_uninit_isoc(struct stk1160 *dev)
413 {
414 	stk1160_cancel_isoc(dev);
415 	stk1160_free_isoc(dev);
416 }
417 
418 /*
419  * Allocate URBs
420  */
421 int stk1160_alloc_isoc(struct stk1160 *dev)
422 {
423 	struct urb *urb;
424 	int i, j, k, sb_size, max_packets, num_bufs;
425 
426 	/*
427 	 * It may be necessary to release isoc here,
428 	 * since isoc are only released on disconnection.
429 	 * (see new_pkt_size flag)
430 	 */
431 	if (dev->isoc_ctl.num_bufs)
432 		stk1160_uninit_isoc(dev);
433 
434 	stk1160_dbg("allocating urbs...\n");
435 
436 	num_bufs = STK1160_NUM_BUFS;
437 	max_packets = STK1160_NUM_PACKETS;
438 	sb_size = max_packets * dev->max_pkt_size;
439 
440 	dev->isoc_ctl.buf = NULL;
441 	dev->isoc_ctl.max_pkt_size = dev->max_pkt_size;
442 	dev->isoc_ctl.urb = kzalloc(sizeof(void *)*num_bufs, GFP_KERNEL);
443 	if (!dev->isoc_ctl.urb) {
444 		stk1160_err("out of memory for urb array\n");
445 		return -ENOMEM;
446 	}
447 
448 	dev->isoc_ctl.transfer_buffer = kzalloc(sizeof(void *)*num_bufs,
449 					      GFP_KERNEL);
450 	if (!dev->isoc_ctl.transfer_buffer) {
451 		stk1160_err("out of memory for usb transfers\n");
452 		kfree(dev->isoc_ctl.urb);
453 		return -ENOMEM;
454 	}
455 
456 	/* allocate urbs and transfer buffers */
457 	for (i = 0; i < num_bufs; i++) {
458 
459 		urb = usb_alloc_urb(max_packets, GFP_KERNEL);
460 		if (!urb)
461 			goto free_i_bufs;
462 		dev->isoc_ctl.urb[i] = urb;
463 
464 #ifndef CONFIG_DMA_NONCOHERENT
465 		dev->isoc_ctl.transfer_buffer[i] = usb_alloc_coherent(dev->udev,
466 			sb_size, GFP_KERNEL, &urb->transfer_dma);
467 #else
468 		dev->isoc_ctl.transfer_buffer[i] = kmalloc(sb_size, GFP_KERNEL);
469 #endif
470 		if (!dev->isoc_ctl.transfer_buffer[i]) {
471 			stk1160_err("cannot alloc %d bytes for tx[%d] buffer\n",
472 				sb_size, i);
473 
474 			/* Not enough transfer buffers, so just give up */
475 			if (i < STK1160_MIN_BUFS)
476 				goto free_i_bufs;
477 			goto nomore_tx_bufs;
478 		}
479 		memset(dev->isoc_ctl.transfer_buffer[i], 0, sb_size);
480 
481 		/*
482 		 * FIXME: Where can I get the endpoint?
483 		 */
484 		urb->dev = dev->udev;
485 		urb->pipe = usb_rcvisocpipe(dev->udev, STK1160_EP_VIDEO);
486 		urb->transfer_buffer = dev->isoc_ctl.transfer_buffer[i];
487 		urb->transfer_buffer_length = sb_size;
488 		urb->complete = stk1160_isoc_irq;
489 		urb->context = dev;
490 		urb->interval = 1;
491 		urb->start_frame = 0;
492 		urb->number_of_packets = max_packets;
493 #ifndef CONFIG_DMA_NONCOHERENT
494 		urb->transfer_flags = URB_ISO_ASAP | URB_NO_TRANSFER_DMA_MAP;
495 #else
496 		urb->transfer_flags = URB_ISO_ASAP;
497 #endif
498 
499 		k = 0;
500 		for (j = 0; j < max_packets; j++) {
501 			urb->iso_frame_desc[j].offset = k;
502 			urb->iso_frame_desc[j].length =
503 					dev->isoc_ctl.max_pkt_size;
504 			k += dev->isoc_ctl.max_pkt_size;
505 		}
506 	}
507 
508 	stk1160_dbg("%d urbs allocated\n", num_bufs);
509 
510 	/* At last we can say we have some buffers */
511 	dev->isoc_ctl.num_bufs = num_bufs;
512 
513 	return 0;
514 
515 nomore_tx_bufs:
516 	/*
517 	 * Failed to allocate desired buffer count. However, we may have
518 	 * enough to work fine, so we just free the extra urb,
519 	 * store the allocated count and keep going, fingers crossed!
520 	 */
521 	usb_free_urb(dev->isoc_ctl.urb[i]);
522 	dev->isoc_ctl.urb[i] = NULL;
523 
524 	stk1160_warn("%d urbs allocated. Trying to continue...\n", i - 1);
525 
526 	dev->isoc_ctl.num_bufs = i - 1;
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+1;
533 	stk1160_free_isoc(dev);
534 	return -ENOMEM;
535 }
536 
537