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