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