1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3     file operation functions
4     Copyright (C) 2003-2004  Kevin Thayer <nufan_wfk at yahoo.com>
5     Copyright (C) 2004  Chris Kennedy <c@groovy.org>
6     Copyright (C) 2005-2007  Hans Verkuil <hverkuil@xs4all.nl>
7 
8  */
9 
10 #include "ivtv-driver.h"
11 #include "ivtv-fileops.h"
12 #include "ivtv-i2c.h"
13 #include "ivtv-queue.h"
14 #include "ivtv-udma.h"
15 #include "ivtv-irq.h"
16 #include "ivtv-vbi.h"
17 #include "ivtv-mailbox.h"
18 #include "ivtv-routing.h"
19 #include "ivtv-streams.h"
20 #include "ivtv-yuv.h"
21 #include "ivtv-ioctl.h"
22 #include "ivtv-cards.h"
23 #include "ivtv-firmware.h"
24 #include <media/v4l2-event.h>
25 #include <media/i2c/saa7115.h>
26 
27 /* This function tries to claim the stream for a specific file descriptor.
28    If no one else is using this stream then the stream is claimed and
29    associated VBI streams are also automatically claimed.
30    Possible error returns: -EBUSY if someone else has claimed
31    the stream or 0 on success. */
32 int ivtv_claim_stream(struct ivtv_open_id *id, int type)
33 {
34 	struct ivtv *itv = id->itv;
35 	struct ivtv_stream *s = &itv->streams[type];
36 	struct ivtv_stream *s_vbi;
37 	int vbi_type;
38 
39 	if (test_and_set_bit(IVTV_F_S_CLAIMED, &s->s_flags)) {
40 		/* someone already claimed this stream */
41 		if (s->fh == &id->fh) {
42 			/* yes, this file descriptor did. So that's OK. */
43 			return 0;
44 		}
45 		if (s->fh == NULL && (type == IVTV_DEC_STREAM_TYPE_VBI ||
46 					 type == IVTV_ENC_STREAM_TYPE_VBI)) {
47 			/* VBI is handled already internally, now also assign
48 			   the file descriptor to this stream for external
49 			   reading of the stream. */
50 			s->fh = &id->fh;
51 			IVTV_DEBUG_INFO("Start Read VBI\n");
52 			return 0;
53 		}
54 		/* someone else is using this stream already */
55 		IVTV_DEBUG_INFO("Stream %d is busy\n", type);
56 		return -EBUSY;
57 	}
58 	s->fh = &id->fh;
59 	if (type == IVTV_DEC_STREAM_TYPE_VBI) {
60 		/* Enable reinsertion interrupt */
61 		ivtv_clear_irq_mask(itv, IVTV_IRQ_DEC_VBI_RE_INSERT);
62 	}
63 
64 	/* IVTV_DEC_STREAM_TYPE_MPG needs to claim IVTV_DEC_STREAM_TYPE_VBI,
65 	   IVTV_ENC_STREAM_TYPE_MPG needs to claim IVTV_ENC_STREAM_TYPE_VBI
66 	   (provided VBI insertion is on and sliced VBI is selected), for all
67 	   other streams we're done */
68 	if (type == IVTV_DEC_STREAM_TYPE_MPG) {
69 		vbi_type = IVTV_DEC_STREAM_TYPE_VBI;
70 	} else if (type == IVTV_ENC_STREAM_TYPE_MPG &&
71 		   itv->vbi.insert_mpeg && !ivtv_raw_vbi(itv)) {
72 		vbi_type = IVTV_ENC_STREAM_TYPE_VBI;
73 	} else {
74 		return 0;
75 	}
76 	s_vbi = &itv->streams[vbi_type];
77 
78 	if (!test_and_set_bit(IVTV_F_S_CLAIMED, &s_vbi->s_flags)) {
79 		/* Enable reinsertion interrupt */
80 		if (vbi_type == IVTV_DEC_STREAM_TYPE_VBI)
81 			ivtv_clear_irq_mask(itv, IVTV_IRQ_DEC_VBI_RE_INSERT);
82 	}
83 	/* mark that it is used internally */
84 	set_bit(IVTV_F_S_INTERNAL_USE, &s_vbi->s_flags);
85 	return 0;
86 }
87 EXPORT_SYMBOL(ivtv_claim_stream);
88 
89 /* This function releases a previously claimed stream. It will take into
90    account associated VBI streams. */
91 void ivtv_release_stream(struct ivtv_stream *s)
92 {
93 	struct ivtv *itv = s->itv;
94 	struct ivtv_stream *s_vbi;
95 
96 	s->fh = NULL;
97 	if ((s->type == IVTV_DEC_STREAM_TYPE_VBI || s->type == IVTV_ENC_STREAM_TYPE_VBI) &&
98 		test_bit(IVTV_F_S_INTERNAL_USE, &s->s_flags)) {
99 		/* this stream is still in use internally */
100 		return;
101 	}
102 	if (!test_and_clear_bit(IVTV_F_S_CLAIMED, &s->s_flags)) {
103 		IVTV_DEBUG_WARN("Release stream %s not in use!\n", s->name);
104 		return;
105 	}
106 
107 	ivtv_flush_queues(s);
108 
109 	/* disable reinsertion interrupt */
110 	if (s->type == IVTV_DEC_STREAM_TYPE_VBI)
111 		ivtv_set_irq_mask(itv, IVTV_IRQ_DEC_VBI_RE_INSERT);
112 
113 	/* IVTV_DEC_STREAM_TYPE_MPG needs to release IVTV_DEC_STREAM_TYPE_VBI,
114 	   IVTV_ENC_STREAM_TYPE_MPG needs to release IVTV_ENC_STREAM_TYPE_VBI,
115 	   for all other streams we're done */
116 	if (s->type == IVTV_DEC_STREAM_TYPE_MPG)
117 		s_vbi = &itv->streams[IVTV_DEC_STREAM_TYPE_VBI];
118 	else if (s->type == IVTV_ENC_STREAM_TYPE_MPG)
119 		s_vbi = &itv->streams[IVTV_ENC_STREAM_TYPE_VBI];
120 	else
121 		return;
122 
123 	/* clear internal use flag */
124 	if (!test_and_clear_bit(IVTV_F_S_INTERNAL_USE, &s_vbi->s_flags)) {
125 		/* was already cleared */
126 		return;
127 	}
128 	if (s_vbi->fh) {
129 		/* VBI stream still claimed by a file descriptor */
130 		return;
131 	}
132 	/* disable reinsertion interrupt */
133 	if (s_vbi->type == IVTV_DEC_STREAM_TYPE_VBI)
134 		ivtv_set_irq_mask(itv, IVTV_IRQ_DEC_VBI_RE_INSERT);
135 	clear_bit(IVTV_F_S_CLAIMED, &s_vbi->s_flags);
136 	ivtv_flush_queues(s_vbi);
137 }
138 EXPORT_SYMBOL(ivtv_release_stream);
139 
140 static void ivtv_dualwatch(struct ivtv *itv)
141 {
142 	struct v4l2_tuner vt;
143 	u32 new_stereo_mode;
144 	const u32 dual = 0x02;
145 
146 	new_stereo_mode = v4l2_ctrl_g_ctrl(itv->cxhdl.audio_mode);
147 	memset(&vt, 0, sizeof(vt));
148 	ivtv_call_all(itv, tuner, g_tuner, &vt);
149 	if (vt.audmode == V4L2_TUNER_MODE_LANG1_LANG2 && (vt.rxsubchans & V4L2_TUNER_SUB_LANG2))
150 		new_stereo_mode = dual;
151 
152 	if (new_stereo_mode == itv->dualwatch_stereo_mode)
153 		return;
154 
155 	IVTV_DEBUG_INFO("dualwatch: change stereo flag from 0x%x to 0x%x.\n",
156 			   itv->dualwatch_stereo_mode, new_stereo_mode);
157 	if (v4l2_ctrl_s_ctrl(itv->cxhdl.audio_mode, new_stereo_mode))
158 		IVTV_DEBUG_INFO("dualwatch: changing stereo flag failed\n");
159 }
160 
161 static void ivtv_update_pgm_info(struct ivtv *itv)
162 {
163 	u32 wr_idx = (read_enc(itv->pgm_info_offset) - itv->pgm_info_offset - 4) / 24;
164 	int cnt;
165 	int i = 0;
166 
167 	if (wr_idx >= itv->pgm_info_num) {
168 		IVTV_DEBUG_WARN("Invalid PGM index %d (>= %d)\n", wr_idx, itv->pgm_info_num);
169 		return;
170 	}
171 	cnt = (wr_idx + itv->pgm_info_num - itv->pgm_info_write_idx) % itv->pgm_info_num;
172 	while (i < cnt) {
173 		int idx = (itv->pgm_info_write_idx + i) % itv->pgm_info_num;
174 		struct v4l2_enc_idx_entry *e = itv->pgm_info + idx;
175 		u32 addr = itv->pgm_info_offset + 4 + idx * 24;
176 		const int mapping[8] = { -1, V4L2_ENC_IDX_FRAME_I, V4L2_ENC_IDX_FRAME_P, -1,
177 			V4L2_ENC_IDX_FRAME_B, -1, -1, -1 };
178 					// 1=I, 2=P, 4=B
179 
180 		e->offset = read_enc(addr + 4) + ((u64)read_enc(addr + 8) << 32);
181 		if (e->offset > itv->mpg_data_received) {
182 			break;
183 		}
184 		e->offset += itv->vbi_data_inserted;
185 		e->length = read_enc(addr);
186 		e->pts = read_enc(addr + 16) + ((u64)(read_enc(addr + 20) & 1) << 32);
187 		e->flags = mapping[read_enc(addr + 12) & 7];
188 		i++;
189 	}
190 	itv->pgm_info_write_idx = (itv->pgm_info_write_idx + i) % itv->pgm_info_num;
191 }
192 
193 static struct ivtv_buffer *ivtv_get_buffer(struct ivtv_stream *s, int non_block, int *err)
194 {
195 	struct ivtv *itv = s->itv;
196 	struct ivtv_stream *s_vbi = &itv->streams[IVTV_ENC_STREAM_TYPE_VBI];
197 	struct ivtv_buffer *buf;
198 	DEFINE_WAIT(wait);
199 
200 	*err = 0;
201 	while (1) {
202 		if (s->type == IVTV_ENC_STREAM_TYPE_MPG) {
203 			/* Process pending program info updates and pending VBI data */
204 			ivtv_update_pgm_info(itv);
205 
206 			if (time_after(jiffies,
207 				       itv->dualwatch_jiffies +
208 				       msecs_to_jiffies(1000))) {
209 				itv->dualwatch_jiffies = jiffies;
210 				ivtv_dualwatch(itv);
211 			}
212 
213 			if (test_bit(IVTV_F_S_INTERNAL_USE, &s_vbi->s_flags) &&
214 			    !test_bit(IVTV_F_S_APPL_IO, &s_vbi->s_flags)) {
215 				while ((buf = ivtv_dequeue(s_vbi, &s_vbi->q_full))) {
216 					/* byteswap and process VBI data */
217 					ivtv_process_vbi_data(itv, buf, s_vbi->dma_pts, s_vbi->type);
218 					ivtv_enqueue(s_vbi, buf, &s_vbi->q_free);
219 				}
220 			}
221 			buf = &itv->vbi.sliced_mpeg_buf;
222 			if (buf->readpos != buf->bytesused) {
223 				return buf;
224 			}
225 		}
226 
227 		/* do we have leftover data? */
228 		buf = ivtv_dequeue(s, &s->q_io);
229 		if (buf)
230 			return buf;
231 
232 		/* do we have new data? */
233 		buf = ivtv_dequeue(s, &s->q_full);
234 		if (buf) {
235 			if ((buf->b_flags & IVTV_F_B_NEED_BUF_SWAP) == 0)
236 				return buf;
237 			buf->b_flags &= ~IVTV_F_B_NEED_BUF_SWAP;
238 			if (s->type == IVTV_ENC_STREAM_TYPE_MPG)
239 				/* byteswap MPG data */
240 				ivtv_buf_swap(buf);
241 			else if (s->type != IVTV_DEC_STREAM_TYPE_VBI) {
242 				/* byteswap and process VBI data */
243 				ivtv_process_vbi_data(itv, buf, s->dma_pts, s->type);
244 			}
245 			return buf;
246 		}
247 
248 		/* return if end of stream */
249 		if (s->type != IVTV_DEC_STREAM_TYPE_VBI && !test_bit(IVTV_F_S_STREAMING, &s->s_flags)) {
250 			IVTV_DEBUG_INFO("EOS %s\n", s->name);
251 			return NULL;
252 		}
253 
254 		/* return if file was opened with O_NONBLOCK */
255 		if (non_block) {
256 			*err = -EAGAIN;
257 			return NULL;
258 		}
259 
260 		/* wait for more data to arrive */
261 		mutex_unlock(&itv->serialize_lock);
262 		prepare_to_wait(&s->waitq, &wait, TASK_INTERRUPTIBLE);
263 		/* New buffers might have become available before we were added to the waitqueue */
264 		if (!s->q_full.buffers)
265 			schedule();
266 		finish_wait(&s->waitq, &wait);
267 		mutex_lock(&itv->serialize_lock);
268 		if (signal_pending(current)) {
269 			/* return if a signal was received */
270 			IVTV_DEBUG_INFO("User stopped %s\n", s->name);
271 			*err = -EINTR;
272 			return NULL;
273 		}
274 	}
275 }
276 
277 static void ivtv_setup_sliced_vbi_buf(struct ivtv *itv)
278 {
279 	int idx = itv->vbi.inserted_frame % IVTV_VBI_FRAMES;
280 
281 	itv->vbi.sliced_mpeg_buf.buf = itv->vbi.sliced_mpeg_data[idx];
282 	itv->vbi.sliced_mpeg_buf.bytesused = itv->vbi.sliced_mpeg_size[idx];
283 	itv->vbi.sliced_mpeg_buf.readpos = 0;
284 }
285 
286 static size_t ivtv_copy_buf_to_user(struct ivtv_stream *s, struct ivtv_buffer *buf,
287 		char __user *ubuf, size_t ucount)
288 {
289 	struct ivtv *itv = s->itv;
290 	size_t len = buf->bytesused - buf->readpos;
291 
292 	if (len > ucount) len = ucount;
293 	if (itv->vbi.insert_mpeg && s->type == IVTV_ENC_STREAM_TYPE_MPG &&
294 	    !ivtv_raw_vbi(itv) && buf != &itv->vbi.sliced_mpeg_buf) {
295 		const char *start = buf->buf + buf->readpos;
296 		const char *p = start + 1;
297 		const u8 *q;
298 		u8 ch = itv->search_pack_header ? 0xba : 0xe0;
299 		int stuffing, i;
300 
301 		while (start + len > p && (q = memchr(p, 0, start + len - p))) {
302 			p = q + 1;
303 			if ((char *)q + 15 >= buf->buf + buf->bytesused ||
304 			    q[1] != 0 || q[2] != 1 || q[3] != ch) {
305 				continue;
306 			}
307 			if (!itv->search_pack_header) {
308 				if ((q[6] & 0xc0) != 0x80)
309 					continue;
310 				if (((q[7] & 0xc0) == 0x80 && (q[9] & 0xf0) == 0x20) ||
311 				    ((q[7] & 0xc0) == 0xc0 && (q[9] & 0xf0) == 0x30)) {
312 					ch = 0xba;
313 					itv->search_pack_header = 1;
314 					p = q + 9;
315 				}
316 				continue;
317 			}
318 			stuffing = q[13] & 7;
319 			/* all stuffing bytes must be 0xff */
320 			for (i = 0; i < stuffing; i++)
321 				if (q[14 + i] != 0xff)
322 					break;
323 			if (i == stuffing && (q[4] & 0xc4) == 0x44 && (q[12] & 3) == 3 &&
324 					q[14 + stuffing] == 0 && q[15 + stuffing] == 0 &&
325 					q[16 + stuffing] == 1) {
326 				itv->search_pack_header = 0;
327 				len = (char *)q - start;
328 				ivtv_setup_sliced_vbi_buf(itv);
329 				break;
330 			}
331 		}
332 	}
333 	if (copy_to_user(ubuf, (u8 *)buf->buf + buf->readpos, len)) {
334 		IVTV_DEBUG_WARN("copy %zd bytes to user failed for %s\n", len, s->name);
335 		return -EFAULT;
336 	}
337 	/*IVTV_INFO("copied %lld %d %d %d %d %d vbi %d\n", itv->mpg_data_received, len, ucount,
338 			buf->readpos, buf->bytesused, buf->bytesused - buf->readpos - len,
339 			buf == &itv->vbi.sliced_mpeg_buf); */
340 	buf->readpos += len;
341 	if (s->type == IVTV_ENC_STREAM_TYPE_MPG && buf != &itv->vbi.sliced_mpeg_buf)
342 		itv->mpg_data_received += len;
343 	return len;
344 }
345 
346 static ssize_t ivtv_read(struct ivtv_stream *s, char __user *ubuf, size_t tot_count, int non_block)
347 {
348 	struct ivtv *itv = s->itv;
349 	size_t tot_written = 0;
350 	int single_frame = 0;
351 
352 	if (atomic_read(&itv->capturing) == 0 && s->fh == NULL) {
353 		/* shouldn't happen */
354 		IVTV_DEBUG_WARN("Stream %s not initialized before read\n", s->name);
355 		return -EIO;
356 	}
357 
358 	/* Each VBI buffer is one frame, the v4l2 API says that for VBI the frames should
359 	   arrive one-by-one, so make sure we never output more than one VBI frame at a time */
360 	if (s->type == IVTV_DEC_STREAM_TYPE_VBI ||
361 	    (s->type == IVTV_ENC_STREAM_TYPE_VBI && !ivtv_raw_vbi(itv)))
362 		single_frame = 1;
363 
364 	for (;;) {
365 		struct ivtv_buffer *buf;
366 		int rc;
367 
368 		buf = ivtv_get_buffer(s, non_block, &rc);
369 		/* if there is no data available... */
370 		if (buf == NULL) {
371 			/* if we got data, then return that regardless */
372 			if (tot_written)
373 				break;
374 			/* EOS condition */
375 			if (rc == 0) {
376 				clear_bit(IVTV_F_S_STREAMOFF, &s->s_flags);
377 				clear_bit(IVTV_F_S_APPL_IO, &s->s_flags);
378 				ivtv_release_stream(s);
379 			}
380 			/* set errno */
381 			return rc;
382 		}
383 		rc = ivtv_copy_buf_to_user(s, buf, ubuf + tot_written, tot_count - tot_written);
384 		if (buf != &itv->vbi.sliced_mpeg_buf) {
385 			ivtv_enqueue(s, buf, (buf->readpos == buf->bytesused) ? &s->q_free : &s->q_io);
386 		}
387 		else if (buf->readpos == buf->bytesused) {
388 			int idx = itv->vbi.inserted_frame % IVTV_VBI_FRAMES;
389 			itv->vbi.sliced_mpeg_size[idx] = 0;
390 			itv->vbi.inserted_frame++;
391 			itv->vbi_data_inserted += buf->bytesused;
392 		}
393 		if (rc < 0)
394 			return rc;
395 		tot_written += rc;
396 
397 		if (tot_written == tot_count || single_frame)
398 			break;
399 	}
400 	return tot_written;
401 }
402 
403 static ssize_t ivtv_read_pos(struct ivtv_stream *s, char __user *ubuf, size_t count,
404 			loff_t *pos, int non_block)
405 {
406 	ssize_t rc = count ? ivtv_read(s, ubuf, count, non_block) : 0;
407 	struct ivtv *itv = s->itv;
408 
409 	IVTV_DEBUG_HI_FILE("read %zd from %s, got %zd\n", count, s->name, rc);
410 	if (rc > 0)
411 		*pos += rc;
412 	return rc;
413 }
414 
415 int ivtv_start_capture(struct ivtv_open_id *id)
416 {
417 	struct ivtv *itv = id->itv;
418 	struct ivtv_stream *s = &itv->streams[id->type];
419 	struct ivtv_stream *s_vbi;
420 
421 	if (s->type == IVTV_ENC_STREAM_TYPE_RAD ||
422 	    s->type == IVTV_DEC_STREAM_TYPE_MPG ||
423 	    s->type == IVTV_DEC_STREAM_TYPE_YUV ||
424 	    s->type == IVTV_DEC_STREAM_TYPE_VOUT) {
425 		/* you cannot read from these stream types. */
426 		return -EINVAL;
427 	}
428 
429 	/* Try to claim this stream. */
430 	if (ivtv_claim_stream(id, s->type))
431 		return -EBUSY;
432 
433 	/* This stream does not need to start capturing */
434 	if (s->type == IVTV_DEC_STREAM_TYPE_VBI) {
435 		set_bit(IVTV_F_S_APPL_IO, &s->s_flags);
436 		return 0;
437 	}
438 
439 	/* If capture is already in progress, then we also have to
440 	   do nothing extra. */
441 	if (test_bit(IVTV_F_S_STREAMOFF, &s->s_flags) || test_and_set_bit(IVTV_F_S_STREAMING, &s->s_flags)) {
442 		set_bit(IVTV_F_S_APPL_IO, &s->s_flags);
443 		return 0;
444 	}
445 
446 	/* Start VBI capture if required */
447 	s_vbi = &itv->streams[IVTV_ENC_STREAM_TYPE_VBI];
448 	if (s->type == IVTV_ENC_STREAM_TYPE_MPG &&
449 	    test_bit(IVTV_F_S_INTERNAL_USE, &s_vbi->s_flags) &&
450 	    !test_and_set_bit(IVTV_F_S_STREAMING, &s_vbi->s_flags)) {
451 		/* Note: the IVTV_ENC_STREAM_TYPE_VBI is claimed
452 		   automatically when the MPG stream is claimed.
453 		   We only need to start the VBI capturing. */
454 		if (ivtv_start_v4l2_encode_stream(s_vbi)) {
455 			IVTV_DEBUG_WARN("VBI capture start failed\n");
456 
457 			/* Failure, clean up and return an error */
458 			clear_bit(IVTV_F_S_STREAMING, &s_vbi->s_flags);
459 			clear_bit(IVTV_F_S_STREAMING, &s->s_flags);
460 			/* also releases the associated VBI stream */
461 			ivtv_release_stream(s);
462 			return -EIO;
463 		}
464 		IVTV_DEBUG_INFO("VBI insertion started\n");
465 	}
466 
467 	/* Tell the card to start capturing */
468 	if (!ivtv_start_v4l2_encode_stream(s)) {
469 		/* We're done */
470 		set_bit(IVTV_F_S_APPL_IO, &s->s_flags);
471 		/* Resume a possibly paused encoder */
472 		if (test_and_clear_bit(IVTV_F_I_ENC_PAUSED, &itv->i_flags))
473 			ivtv_vapi(itv, CX2341X_ENC_PAUSE_ENCODER, 1, 1);
474 		return 0;
475 	}
476 
477 	/* failure, clean up */
478 	IVTV_DEBUG_WARN("Failed to start capturing for stream %s\n", s->name);
479 
480 	/* Note: the IVTV_ENC_STREAM_TYPE_VBI is released
481 	   automatically when the MPG stream is released.
482 	   We only need to stop the VBI capturing. */
483 	if (s->type == IVTV_ENC_STREAM_TYPE_MPG &&
484 	    test_bit(IVTV_F_S_STREAMING, &s_vbi->s_flags)) {
485 		ivtv_stop_v4l2_encode_stream(s_vbi, 0);
486 		clear_bit(IVTV_F_S_STREAMING, &s_vbi->s_flags);
487 	}
488 	clear_bit(IVTV_F_S_STREAMING, &s->s_flags);
489 	ivtv_release_stream(s);
490 	return -EIO;
491 }
492 
493 ssize_t ivtv_v4l2_read(struct file * filp, char __user *buf, size_t count, loff_t * pos)
494 {
495 	struct ivtv_open_id *id = fh2id(filp->private_data);
496 	struct ivtv *itv = id->itv;
497 	struct ivtv_stream *s = &itv->streams[id->type];
498 	ssize_t rc;
499 
500 	IVTV_DEBUG_HI_FILE("read %zd bytes from %s\n", count, s->name);
501 
502 	if (mutex_lock_interruptible(&itv->serialize_lock))
503 		return -ERESTARTSYS;
504 	rc = ivtv_start_capture(id);
505 	if (!rc)
506 		rc = ivtv_read_pos(s, buf, count, pos, filp->f_flags & O_NONBLOCK);
507 	mutex_unlock(&itv->serialize_lock);
508 	return rc;
509 }
510 
511 int ivtv_start_decoding(struct ivtv_open_id *id, int speed)
512 {
513 	struct ivtv *itv = id->itv;
514 	struct ivtv_stream *s = &itv->streams[id->type];
515 	int rc;
516 
517 	if (atomic_read(&itv->decoding) == 0) {
518 		if (ivtv_claim_stream(id, s->type)) {
519 			/* someone else is using this stream already */
520 			IVTV_DEBUG_WARN("start decode, stream already claimed\n");
521 			return -EBUSY;
522 		}
523 		rc = ivtv_start_v4l2_decode_stream(s, 0);
524 		if (rc < 0) {
525 			if (rc == -EAGAIN)
526 				rc = ivtv_start_v4l2_decode_stream(s, 0);
527 			if (rc < 0)
528 				return rc;
529 		}
530 	}
531 	if (s->type == IVTV_DEC_STREAM_TYPE_MPG)
532 		return ivtv_set_speed(itv, speed);
533 	return 0;
534 }
535 
536 static ssize_t ivtv_write(struct file *filp, const char __user *user_buf, size_t count, loff_t *pos)
537 {
538 	struct ivtv_open_id *id = fh2id(filp->private_data);
539 	struct ivtv *itv = id->itv;
540 	struct ivtv_stream *s = &itv->streams[id->type];
541 	struct yuv_playback_info *yi = &itv->yuv_info;
542 	struct ivtv_buffer *buf;
543 	struct ivtv_queue q;
544 	int bytes_written = 0;
545 	int mode;
546 	int rc;
547 	DEFINE_WAIT(wait);
548 
549 	IVTV_DEBUG_HI_FILE("write %zd bytes to %s\n", count, s->name);
550 
551 	if (s->type != IVTV_DEC_STREAM_TYPE_MPG &&
552 	    s->type != IVTV_DEC_STREAM_TYPE_YUV &&
553 	    s->type != IVTV_DEC_STREAM_TYPE_VOUT)
554 		/* not decoder streams */
555 		return -EINVAL;
556 
557 	/* Try to claim this stream */
558 	if (ivtv_claim_stream(id, s->type))
559 		return -EBUSY;
560 
561 	/* This stream does not need to start any decoding */
562 	if (s->type == IVTV_DEC_STREAM_TYPE_VOUT) {
563 		int elems = count / sizeof(struct v4l2_sliced_vbi_data);
564 
565 		set_bit(IVTV_F_S_APPL_IO, &s->s_flags);
566 		return ivtv_write_vbi_from_user(itv,
567 		   (const struct v4l2_sliced_vbi_data __user *)user_buf, elems);
568 	}
569 
570 	mode = s->type == IVTV_DEC_STREAM_TYPE_MPG ? OUT_MPG : OUT_YUV;
571 
572 	if (ivtv_set_output_mode(itv, mode) != mode) {
573 	    ivtv_release_stream(s);
574 	    return -EBUSY;
575 	}
576 	ivtv_queue_init(&q);
577 	set_bit(IVTV_F_S_APPL_IO, &s->s_flags);
578 
579 	/* Start decoder (returns 0 if already started) */
580 	rc = ivtv_start_decoding(id, itv->speed);
581 	if (rc) {
582 		IVTV_DEBUG_WARN("Failed start decode stream %s\n", s->name);
583 
584 		/* failure, clean up */
585 		clear_bit(IVTV_F_S_STREAMING, &s->s_flags);
586 		clear_bit(IVTV_F_S_APPL_IO, &s->s_flags);
587 		return rc;
588 	}
589 
590 retry:
591 	/* If possible, just DMA the entire frame - Check the data transfer size
592 	since we may get here before the stream has been fully set-up */
593 	if (mode == OUT_YUV && s->q_full.length == 0 && itv->dma_data_req_size) {
594 		while (count >= itv->dma_data_req_size) {
595 			rc = ivtv_yuv_udma_stream_frame(itv, (void __user *)user_buf);
596 
597 			if (rc < 0)
598 				return rc;
599 
600 			bytes_written += itv->dma_data_req_size;
601 			user_buf += itv->dma_data_req_size;
602 			count -= itv->dma_data_req_size;
603 		}
604 		if (count == 0) {
605 			IVTV_DEBUG_HI_FILE("Wrote %d bytes to %s (%d)\n", bytes_written, s->name, s->q_full.bytesused);
606 			return bytes_written;
607 		}
608 	}
609 
610 	for (;;) {
611 		/* Gather buffers */
612 		while (q.length - q.bytesused < count && (buf = ivtv_dequeue(s, &s->q_io)))
613 			ivtv_enqueue(s, buf, &q);
614 		while (q.length - q.bytesused < count && (buf = ivtv_dequeue(s, &s->q_free))) {
615 			ivtv_enqueue(s, buf, &q);
616 		}
617 		if (q.buffers)
618 			break;
619 		if (filp->f_flags & O_NONBLOCK)
620 			return -EAGAIN;
621 		mutex_unlock(&itv->serialize_lock);
622 		prepare_to_wait(&s->waitq, &wait, TASK_INTERRUPTIBLE);
623 		/* New buffers might have become free before we were added to the waitqueue */
624 		if (!s->q_free.buffers)
625 			schedule();
626 		finish_wait(&s->waitq, &wait);
627 		mutex_lock(&itv->serialize_lock);
628 		if (signal_pending(current)) {
629 			IVTV_DEBUG_INFO("User stopped %s\n", s->name);
630 			return -EINTR;
631 		}
632 	}
633 
634 	/* copy user data into buffers */
635 	while ((buf = ivtv_dequeue(s, &q))) {
636 		/* yuv is a pain. Don't copy more data than needed for a single
637 		   frame, otherwise we lose sync with the incoming stream */
638 		if (s->type == IVTV_DEC_STREAM_TYPE_YUV &&
639 		    yi->stream_size + count > itv->dma_data_req_size)
640 			rc  = ivtv_buf_copy_from_user(s, buf, user_buf,
641 				itv->dma_data_req_size - yi->stream_size);
642 		else
643 			rc = ivtv_buf_copy_from_user(s, buf, user_buf, count);
644 
645 		/* Make sure we really got all the user data */
646 		if (rc < 0) {
647 			ivtv_queue_move(s, &q, NULL, &s->q_free, 0);
648 			return rc;
649 		}
650 		user_buf += rc;
651 		count -= rc;
652 		bytes_written += rc;
653 
654 		if (s->type == IVTV_DEC_STREAM_TYPE_YUV) {
655 			yi->stream_size += rc;
656 			/* If we have a complete yuv frame, break loop now */
657 			if (yi->stream_size == itv->dma_data_req_size) {
658 				ivtv_enqueue(s, buf, &s->q_full);
659 				yi->stream_size = 0;
660 				break;
661 			}
662 		}
663 
664 		if (buf->bytesused != s->buf_size) {
665 			/* incomplete, leave in q_io for next time */
666 			ivtv_enqueue(s, buf, &s->q_io);
667 			break;
668 		}
669 		/* Byteswap MPEG buffer */
670 		if (s->type == IVTV_DEC_STREAM_TYPE_MPG)
671 			ivtv_buf_swap(buf);
672 		ivtv_enqueue(s, buf, &s->q_full);
673 	}
674 
675 	if (test_bit(IVTV_F_S_NEEDS_DATA, &s->s_flags)) {
676 		if (s->q_full.length >= itv->dma_data_req_size) {
677 			int got_sig;
678 
679 			if (mode == OUT_YUV)
680 				ivtv_yuv_setup_stream_frame(itv);
681 
682 			mutex_unlock(&itv->serialize_lock);
683 			prepare_to_wait(&itv->dma_waitq, &wait, TASK_INTERRUPTIBLE);
684 			while (!(got_sig = signal_pending(current)) &&
685 					test_bit(IVTV_F_S_DMA_PENDING, &s->s_flags)) {
686 				schedule();
687 			}
688 			finish_wait(&itv->dma_waitq, &wait);
689 			mutex_lock(&itv->serialize_lock);
690 			if (got_sig) {
691 				IVTV_DEBUG_INFO("User interrupted %s\n", s->name);
692 				return -EINTR;
693 			}
694 
695 			clear_bit(IVTV_F_S_NEEDS_DATA, &s->s_flags);
696 			ivtv_queue_move(s, &s->q_full, NULL, &s->q_predma, itv->dma_data_req_size);
697 			ivtv_dma_stream_dec_prepare(s, itv->dma_data_req_offset + IVTV_DECODER_OFFSET, 1);
698 		}
699 	}
700 	/* more user data is available, wait until buffers become free
701 	   to transfer the rest. */
702 	if (count && !(filp->f_flags & O_NONBLOCK))
703 		goto retry;
704 	IVTV_DEBUG_HI_FILE("Wrote %d bytes to %s (%d)\n", bytes_written, s->name, s->q_full.bytesused);
705 	return bytes_written;
706 }
707 
708 ssize_t ivtv_v4l2_write(struct file *filp, const char __user *user_buf, size_t count, loff_t *pos)
709 {
710 	struct ivtv_open_id *id = fh2id(filp->private_data);
711 	struct ivtv *itv = id->itv;
712 	ssize_t res;
713 
714 	if (mutex_lock_interruptible(&itv->serialize_lock))
715 		return -ERESTARTSYS;
716 	res = ivtv_write(filp, user_buf, count, pos);
717 	mutex_unlock(&itv->serialize_lock);
718 	return res;
719 }
720 
721 __poll_t ivtv_v4l2_dec_poll(struct file *filp, poll_table *wait)
722 {
723 	struct ivtv_open_id *id = fh2id(filp->private_data);
724 	struct ivtv *itv = id->itv;
725 	struct ivtv_stream *s = &itv->streams[id->type];
726 	__poll_t res = 0;
727 
728 	/* add stream's waitq to the poll list */
729 	IVTV_DEBUG_HI_FILE("Decoder poll\n");
730 
731 	/* If there are subscribed events, then only use the new event
732 	   API instead of the old video.h based API. */
733 	if (!list_empty(&id->fh.subscribed)) {
734 		poll_wait(filp, &id->fh.wait, wait);
735 		/* Turn off the old-style vsync events */
736 		clear_bit(IVTV_F_I_EV_VSYNC_ENABLED, &itv->i_flags);
737 		if (v4l2_event_pending(&id->fh))
738 			res = EPOLLPRI;
739 	} else {
740 		/* This is the old-style API which is here only for backwards
741 		   compatibility. */
742 		poll_wait(filp, &s->waitq, wait);
743 		set_bit(IVTV_F_I_EV_VSYNC_ENABLED, &itv->i_flags);
744 		if (test_bit(IVTV_F_I_EV_VSYNC, &itv->i_flags) ||
745 		    test_bit(IVTV_F_I_EV_DEC_STOPPED, &itv->i_flags))
746 			res = EPOLLPRI;
747 	}
748 
749 	/* Allow write if buffers are available for writing */
750 	if (s->q_free.buffers)
751 		res |= EPOLLOUT | EPOLLWRNORM;
752 	return res;
753 }
754 
755 __poll_t ivtv_v4l2_enc_poll(struct file *filp, poll_table *wait)
756 {
757 	__poll_t req_events = poll_requested_events(wait);
758 	struct ivtv_open_id *id = fh2id(filp->private_data);
759 	struct ivtv *itv = id->itv;
760 	struct ivtv_stream *s = &itv->streams[id->type];
761 	int eof = test_bit(IVTV_F_S_STREAMOFF, &s->s_flags);
762 	__poll_t res = 0;
763 
764 	/* Start a capture if there is none */
765 	if (!eof && !test_bit(IVTV_F_S_STREAMING, &s->s_flags) &&
766 			s->type != IVTV_ENC_STREAM_TYPE_RAD &&
767 			(req_events & (EPOLLIN | EPOLLRDNORM))) {
768 		int rc;
769 
770 		mutex_lock(&itv->serialize_lock);
771 		rc = ivtv_start_capture(id);
772 		mutex_unlock(&itv->serialize_lock);
773 		if (rc) {
774 			IVTV_DEBUG_INFO("Could not start capture for %s (%d)\n",
775 					s->name, rc);
776 			return EPOLLERR;
777 		}
778 		IVTV_DEBUG_FILE("Encoder poll started capture\n");
779 	}
780 
781 	/* add stream's waitq to the poll list */
782 	IVTV_DEBUG_HI_FILE("Encoder poll\n");
783 	poll_wait(filp, &s->waitq, wait);
784 	if (v4l2_event_pending(&id->fh))
785 		res |= EPOLLPRI;
786 	else
787 		poll_wait(filp, &id->fh.wait, wait);
788 
789 	if (s->q_full.length || s->q_io.length)
790 		return res | EPOLLIN | EPOLLRDNORM;
791 	if (eof)
792 		return res | EPOLLHUP;
793 	return res;
794 }
795 
796 void ivtv_stop_capture(struct ivtv_open_id *id, int gop_end)
797 {
798 	struct ivtv *itv = id->itv;
799 	struct ivtv_stream *s = &itv->streams[id->type];
800 
801 	IVTV_DEBUG_FILE("close() of %s\n", s->name);
802 
803 	/* 'Unclaim' this stream */
804 
805 	/* Stop capturing */
806 	if (test_bit(IVTV_F_S_STREAMING, &s->s_flags)) {
807 		struct ivtv_stream *s_vbi = &itv->streams[IVTV_ENC_STREAM_TYPE_VBI];
808 
809 		IVTV_DEBUG_INFO("close stopping capture\n");
810 		/* Special case: a running VBI capture for VBI insertion
811 		   in the mpeg stream. Need to stop that too. */
812 		if (id->type == IVTV_ENC_STREAM_TYPE_MPG &&
813 		    test_bit(IVTV_F_S_STREAMING, &s_vbi->s_flags) &&
814 		    !test_bit(IVTV_F_S_APPL_IO, &s_vbi->s_flags)) {
815 			IVTV_DEBUG_INFO("close stopping embedded VBI capture\n");
816 			ivtv_stop_v4l2_encode_stream(s_vbi, 0);
817 		}
818 		if ((id->type == IVTV_DEC_STREAM_TYPE_VBI ||
819 		     id->type == IVTV_ENC_STREAM_TYPE_VBI) &&
820 		    test_bit(IVTV_F_S_INTERNAL_USE, &s->s_flags)) {
821 			/* Also used internally, don't stop capturing */
822 			s->fh = NULL;
823 		}
824 		else {
825 			ivtv_stop_v4l2_encode_stream(s, gop_end);
826 		}
827 	}
828 	if (!gop_end) {
829 		clear_bit(IVTV_F_S_APPL_IO, &s->s_flags);
830 		clear_bit(IVTV_F_S_STREAMOFF, &s->s_flags);
831 		ivtv_release_stream(s);
832 	}
833 }
834 
835 static void ivtv_stop_decoding(struct ivtv_open_id *id, int flags, u64 pts)
836 {
837 	struct ivtv *itv = id->itv;
838 	struct ivtv_stream *s = &itv->streams[id->type];
839 
840 	IVTV_DEBUG_FILE("close() of %s\n", s->name);
841 
842 	if (id->type == IVTV_DEC_STREAM_TYPE_YUV &&
843 		test_bit(IVTV_F_I_DECODING_YUV, &itv->i_flags)) {
844 		/* Restore registers we've changed & clean up any mess */
845 		ivtv_yuv_close(itv);
846 	}
847 
848 	/* Stop decoding */
849 	if (test_bit(IVTV_F_S_STREAMING, &s->s_flags)) {
850 		IVTV_DEBUG_INFO("close stopping decode\n");
851 
852 		ivtv_stop_v4l2_decode_stream(s, flags, pts);
853 		itv->output_mode = OUT_NONE;
854 	}
855 	clear_bit(IVTV_F_S_APPL_IO, &s->s_flags);
856 	clear_bit(IVTV_F_S_STREAMOFF, &s->s_flags);
857 
858 	if (itv->output_mode == OUT_UDMA_YUV && id->yuv_frames)
859 		itv->output_mode = OUT_NONE;
860 
861 	itv->speed = 0;
862 	clear_bit(IVTV_F_I_DEC_PAUSED, &itv->i_flags);
863 	ivtv_release_stream(s);
864 }
865 
866 int ivtv_v4l2_close(struct file *filp)
867 {
868 	struct v4l2_fh *fh = filp->private_data;
869 	struct ivtv_open_id *id = fh2id(fh);
870 	struct ivtv *itv = id->itv;
871 	struct ivtv_stream *s = &itv->streams[id->type];
872 
873 	IVTV_DEBUG_FILE("close %s\n", s->name);
874 
875 	mutex_lock(&itv->serialize_lock);
876 
877 	/* Stop radio */
878 	if (id->type == IVTV_ENC_STREAM_TYPE_RAD &&
879 			v4l2_fh_is_singular_file(filp)) {
880 		/* Closing radio device, return to TV mode */
881 		ivtv_mute(itv);
882 		/* Mark that the radio is no longer in use */
883 		clear_bit(IVTV_F_I_RADIO_USER, &itv->i_flags);
884 		/* Switch tuner to TV */
885 		ivtv_call_all(itv, video, s_std, itv->std);
886 		/* Select correct audio input (i.e. TV tuner or Line in) */
887 		ivtv_audio_set_io(itv);
888 		if (itv->hw_flags & IVTV_HW_SAA711X) {
889 			ivtv_call_hw(itv, IVTV_HW_SAA711X, video, s_crystal_freq,
890 					SAA7115_FREQ_32_11_MHZ, 0);
891 		}
892 		if (atomic_read(&itv->capturing) > 0) {
893 			/* Undo video mute */
894 			ivtv_vapi(itv, CX2341X_ENC_MUTE_VIDEO, 1,
895 					v4l2_ctrl_g_ctrl(itv->cxhdl.video_mute) |
896 					(v4l2_ctrl_g_ctrl(itv->cxhdl.video_mute_yuv) << 8));
897 		}
898 		/* Done! Unmute and continue. */
899 		ivtv_unmute(itv);
900 	}
901 
902 	v4l2_fh_del(fh);
903 	v4l2_fh_exit(fh);
904 
905 	/* Easy case first: this stream was never claimed by us */
906 	if (s->fh != &id->fh)
907 		goto close_done;
908 
909 	/* 'Unclaim' this stream */
910 
911 	if (s->type >= IVTV_DEC_STREAM_TYPE_MPG) {
912 		struct ivtv_stream *s_vout = &itv->streams[IVTV_DEC_STREAM_TYPE_VOUT];
913 
914 		ivtv_stop_decoding(id, V4L2_DEC_CMD_STOP_TO_BLACK | V4L2_DEC_CMD_STOP_IMMEDIATELY, 0);
915 
916 		/* If all output streams are closed, and if the user doesn't have
917 		   IVTV_DEC_STREAM_TYPE_VOUT open, then disable CC on TV-out. */
918 		if (itv->output_mode == OUT_NONE && !test_bit(IVTV_F_S_APPL_IO, &s_vout->s_flags)) {
919 			/* disable CC on TV-out */
920 			ivtv_disable_cc(itv);
921 		}
922 	} else {
923 		ivtv_stop_capture(id, 0);
924 	}
925 close_done:
926 	kfree(id);
927 	mutex_unlock(&itv->serialize_lock);
928 	return 0;
929 }
930 
931 static int ivtv_open(struct file *filp)
932 {
933 	struct video_device *vdev = video_devdata(filp);
934 	struct ivtv_stream *s = video_get_drvdata(vdev);
935 	struct ivtv *itv = s->itv;
936 	struct ivtv_open_id *item;
937 	int res = 0;
938 
939 	IVTV_DEBUG_FILE("open %s\n", s->name);
940 
941 	if (ivtv_init_on_first_open(itv)) {
942 		IVTV_ERR("Failed to initialize on device %s\n",
943 			 video_device_node_name(vdev));
944 		return -ENXIO;
945 	}
946 
947 #ifdef CONFIG_VIDEO_ADV_DEBUG
948 	/* Unless ivtv_fw_debug is set, error out if firmware dead. */
949 	if (ivtv_fw_debug) {
950 		IVTV_WARN("Opening %s with dead firmware lockout disabled\n",
951 			  video_device_node_name(vdev));
952 		IVTV_WARN("Selected firmware errors will be ignored\n");
953 	} else {
954 #else
955 	if (1) {
956 #endif
957 		res = ivtv_firmware_check(itv, "ivtv_serialized_open");
958 		if (res == -EAGAIN)
959 			res = ivtv_firmware_check(itv, "ivtv_serialized_open");
960 		if (res < 0)
961 			return -EIO;
962 	}
963 
964 	if (s->type == IVTV_DEC_STREAM_TYPE_MPG &&
965 		test_bit(IVTV_F_S_CLAIMED, &itv->streams[IVTV_DEC_STREAM_TYPE_YUV].s_flags))
966 		return -EBUSY;
967 
968 	if (s->type == IVTV_DEC_STREAM_TYPE_YUV &&
969 		test_bit(IVTV_F_S_CLAIMED, &itv->streams[IVTV_DEC_STREAM_TYPE_MPG].s_flags))
970 		return -EBUSY;
971 
972 	if (s->type == IVTV_DEC_STREAM_TYPE_YUV) {
973 		if (read_reg(0x82c) == 0) {
974 			IVTV_ERR("Tried to open YUV output device but need to send data to mpeg decoder before it can be used\n");
975 			/* return -ENODEV; */
976 		}
977 		ivtv_udma_alloc(itv);
978 	}
979 
980 	/* Allocate memory */
981 	item = kzalloc(sizeof(struct ivtv_open_id), GFP_KERNEL);
982 	if (NULL == item) {
983 		IVTV_DEBUG_WARN("nomem on v4l2 open\n");
984 		return -ENOMEM;
985 	}
986 	v4l2_fh_init(&item->fh, &s->vdev);
987 	item->itv = itv;
988 	item->type = s->type;
989 
990 	filp->private_data = &item->fh;
991 	v4l2_fh_add(&item->fh);
992 
993 	if (item->type == IVTV_ENC_STREAM_TYPE_RAD &&
994 			v4l2_fh_is_singular_file(filp)) {
995 		if (!test_bit(IVTV_F_I_RADIO_USER, &itv->i_flags)) {
996 			if (atomic_read(&itv->capturing) > 0) {
997 				/* switching to radio while capture is
998 				   in progress is not polite */
999 				v4l2_fh_del(&item->fh);
1000 				v4l2_fh_exit(&item->fh);
1001 				kfree(item);
1002 				return -EBUSY;
1003 			}
1004 		}
1005 		/* Mark that the radio is being used. */
1006 		set_bit(IVTV_F_I_RADIO_USER, &itv->i_flags);
1007 		/* We have the radio */
1008 		ivtv_mute(itv);
1009 		/* Switch tuner to radio */
1010 		ivtv_call_all(itv, tuner, s_radio);
1011 		/* Select the correct audio input (i.e. radio tuner) */
1012 		ivtv_audio_set_io(itv);
1013 		if (itv->hw_flags & IVTV_HW_SAA711X) {
1014 			ivtv_call_hw(itv, IVTV_HW_SAA711X, video, s_crystal_freq,
1015 				SAA7115_FREQ_32_11_MHZ, SAA7115_FREQ_FL_APLL);
1016 		}
1017 		/* Done! Unmute and continue. */
1018 		ivtv_unmute(itv);
1019 	}
1020 
1021 	/* YUV or MPG Decoding Mode? */
1022 	if (s->type == IVTV_DEC_STREAM_TYPE_MPG) {
1023 		clear_bit(IVTV_F_I_DEC_YUV, &itv->i_flags);
1024 	} else if (s->type == IVTV_DEC_STREAM_TYPE_YUV) {
1025 		set_bit(IVTV_F_I_DEC_YUV, &itv->i_flags);
1026 		/* For yuv, we need to know the dma size before we start */
1027 		itv->dma_data_req_size =
1028 				1080 * ((itv->yuv_info.v4l2_src_h + 31) & ~31);
1029 		itv->yuv_info.stream_size = 0;
1030 	}
1031 	return 0;
1032 }
1033 
1034 int ivtv_v4l2_open(struct file *filp)
1035 {
1036 	struct video_device *vdev = video_devdata(filp);
1037 	int res;
1038 
1039 	if (mutex_lock_interruptible(vdev->lock))
1040 		return -ERESTARTSYS;
1041 	res = ivtv_open(filp);
1042 	mutex_unlock(vdev->lock);
1043 	return res;
1044 }
1045 
1046 void ivtv_mute(struct ivtv *itv)
1047 {
1048 	if (atomic_read(&itv->capturing))
1049 		ivtv_vapi(itv, CX2341X_ENC_MUTE_AUDIO, 1, 1);
1050 	IVTV_DEBUG_INFO("Mute\n");
1051 }
1052 
1053 void ivtv_unmute(struct ivtv *itv)
1054 {
1055 	if (atomic_read(&itv->capturing)) {
1056 		ivtv_msleep_timeout(100, 0);
1057 		ivtv_vapi(itv, CX2341X_ENC_MISC, 1, 12);
1058 		ivtv_vapi(itv, CX2341X_ENC_MUTE_AUDIO, 1, 0);
1059 	}
1060 	IVTV_DEBUG_INFO("Unmute\n");
1061 }
1062