1/*
2 * dv1394.c - DV input/output over IEEE 1394 on OHCI chips
3 *   Copyright (C)2001 Daniel Maas <dmaas@dcine.com>
4 *     receive by Dan Dennedy <dan@dennedy.org>
5 *
6 * based on:
7 *  video1394.c - video driver for OHCI 1394 boards
8 *  Copyright (C)1999,2000 Sebastien Rougeaux <sebastien.rougeaux@anu.edu.au>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 */
24
25/*
26  OVERVIEW
27
28  I designed dv1394 as a "pipe" that you can use to shoot DV onto a
29  FireWire bus. In transmission mode, dv1394 does the following:
30
31   1. accepts contiguous frames of DV data from user-space, via write()
32      or mmap() (see dv1394.h for the complete API)
33   2. wraps IEC 61883 packets around the DV data, inserting
34      empty synchronization packets as necessary
35   3. assigns accurate SYT timestamps to the outgoing packets
36   4. shoots them out using the OHCI card's IT DMA engine
37
38   Thanks to Dan Dennedy, we now have a receive mode that does the following:
39
40   1. accepts raw IEC 61883 packets from the OHCI card
41   2. re-assembles the DV data payloads into contiguous frames,
42      discarding empty packets
43   3. sends the DV data to user-space via read() or mmap()
44*/
45
46
47#include <linux/kernel.h>
48#include <linux/list.h>
49#include <linux/slab.h>
50#include <linux/interrupt.h>
51#include <linux/wait.h>
52#include <linux/errno.h>
53#include <linux/module.h>
54#include <linux/init.h>
55#include <linux/pci.h>
56#include <linux/fs.h>
57#include <linux/poll.h>
58#include <linux/mutex.h>
59#include <linux/bitops.h>
60#include <asm/byteorder.h>
61#include <asm/atomic.h>
62#include <asm/io.h>
63#include <asm/uaccess.h>
64#include <linux/delay.h>
65#include <asm/pgtable.h>
66#include <asm/page.h>
67#include <linux/sched.h>
68#include <linux/types.h>
69#include <linux/vmalloc.h>
70#include <linux/string.h>
71#include <linux/compat.h>
72#include <linux/cdev.h>
73
74#include "dv1394.h"
75#include "dv1394-private.h"
76#include "highlevel.h"
77#include "hosts.h"
78#include "ieee1394.h"
79#include "ieee1394_core.h"
80#include "ieee1394_hotplug.h"
81#include "ieee1394_types.h"
82#include "nodemgr.h"
83#include "ohci1394.h"
84
85/* DEBUG LEVELS:
86   0 - no debugging messages
87   1 - some debugging messages, but none during DMA frame transmission
88   2 - lots of messages, including during DMA frame transmission
89       (will cause undeflows if your machine is too slow!)
90*/
91
92#define DV1394_DEBUG_LEVEL 0
93
94/* for debugging use ONLY: allow more than one open() of the device */
95/* #define DV1394_ALLOW_MORE_THAN_ONE_OPEN 1 */
96
97#if DV1394_DEBUG_LEVEL >= 2
98#define irq_printk( args... ) printk( args )
99#else
100#define irq_printk( args... ) do {} while (0)
101#endif
102
103#if DV1394_DEBUG_LEVEL >= 1
104#define debug_printk( args... ) printk( args)
105#else
106#define debug_printk( args... ) do {} while (0)
107#endif
108
109/* issue a dummy PCI read to force the preceding write
110   to be posted to the PCI bus immediately */
111
112static inline void flush_pci_write(struct ti_ohci *ohci)
113{
114	mb();
115	reg_read(ohci, OHCI1394_IsochronousCycleTimer);
116}
117
118static void it_tasklet_func(unsigned long data);
119static void ir_tasklet_func(unsigned long data);
120
121#ifdef CONFIG_COMPAT
122static long dv1394_compat_ioctl(struct file *file, unsigned int cmd,
123			       unsigned long arg);
124#endif
125
126/* GLOBAL DATA */
127
128/* list of all video_cards */
129static LIST_HEAD(dv1394_cards);
130static DEFINE_SPINLOCK(dv1394_cards_lock);
131
132/* translate from a struct file* to the corresponding struct video_card* */
133
134static inline struct video_card* file_to_video_card(struct file *file)
135{
136	return (struct video_card*) file->private_data;
137}
138
139/*** FRAME METHODS *********************************************************/
140
141static void frame_reset(struct frame *f)
142{
143	f->state = FRAME_CLEAR;
144	f->done = 0;
145	f->n_packets = 0;
146	f->frame_begin_timestamp = NULL;
147	f->assigned_timestamp = 0;
148	f->cip_syt1 = NULL;
149	f->cip_syt2 = NULL;
150	f->mid_frame_timestamp = NULL;
151	f->frame_end_timestamp = NULL;
152	f->frame_end_branch = NULL;
153}
154
155static struct frame* frame_new(unsigned int frame_num, struct video_card *video)
156{
157	struct frame *f = kmalloc(sizeof(*f), GFP_KERNEL);
158	if (!f)
159		return NULL;
160
161	f->video = video;
162	f->frame_num = frame_num;
163
164	f->header_pool = pci_alloc_consistent(f->video->ohci->dev, PAGE_SIZE, &f->header_pool_dma);
165	if (!f->header_pool) {
166		printk(KERN_ERR "dv1394: failed to allocate CIP header pool\n");
167		kfree(f);
168		return NULL;
169	}
170
171	debug_printk("dv1394: frame_new: allocated CIP header pool at virt 0x%08lx (contig) dma 0x%08lx size %ld\n",
172		     (unsigned long) f->header_pool, (unsigned long) f->header_pool_dma, PAGE_SIZE);
173
174	f->descriptor_pool_size = MAX_PACKETS * sizeof(struct DMA_descriptor_block);
175	/* make it an even # of pages */
176	f->descriptor_pool_size += PAGE_SIZE - (f->descriptor_pool_size%PAGE_SIZE);
177
178	f->descriptor_pool = pci_alloc_consistent(f->video->ohci->dev,
179						  f->descriptor_pool_size,
180						  &f->descriptor_pool_dma);
181	if (!f->descriptor_pool) {
182		pci_free_consistent(f->video->ohci->dev, PAGE_SIZE, f->header_pool, f->header_pool_dma);
183		kfree(f);
184		return NULL;
185	}
186
187	debug_printk("dv1394: frame_new: allocated DMA program memory at virt 0x%08lx (contig) dma 0x%08lx size %ld\n",
188		     (unsigned long) f->descriptor_pool, (unsigned long) f->descriptor_pool_dma, f->descriptor_pool_size);
189
190	f->data = 0;
191	frame_reset(f);
192
193	return f;
194}
195
196static void frame_delete(struct frame *f)
197{
198	pci_free_consistent(f->video->ohci->dev, PAGE_SIZE, f->header_pool, f->header_pool_dma);
199	pci_free_consistent(f->video->ohci->dev, f->descriptor_pool_size, f->descriptor_pool, f->descriptor_pool_dma);
200	kfree(f);
201}
202
203
204
205
206/*
207   frame_prepare() - build the DMA program for transmitting
208
209   Frame_prepare() must be called OUTSIDE the video->spinlock.
210   However, frame_prepare() must still be serialized, so
211   it should be called WITH the video->mtx taken.
212 */
213
214static void frame_prepare(struct video_card *video, unsigned int this_frame)
215{
216	struct frame *f = video->frames[this_frame];
217	int last_frame;
218
219	struct DMA_descriptor_block *block;
220	dma_addr_t block_dma;
221	struct CIP_header *cip;
222	dma_addr_t cip_dma;
223
224	unsigned int n_descriptors, full_packets, packets_per_frame, payload_size;
225
226	/* these flags denote packets that need special attention */
227	int empty_packet, first_packet, last_packet, mid_packet;
228
229	u32 *branch_address, *last_branch_address = NULL;
230	unsigned long data_p;
231	int first_packet_empty = 0;
232	u32 cycleTimer, ct_sec, ct_cyc, ct_off;
233	unsigned long irq_flags;
234
235	irq_printk("frame_prepare( %d ) ---------------------\n", this_frame);
236
237	full_packets = 0;
238
239
240
241	if (video->pal_or_ntsc == DV1394_PAL)
242		packets_per_frame = DV1394_PAL_PACKETS_PER_FRAME;
243	else
244		packets_per_frame = DV1394_NTSC_PACKETS_PER_FRAME;
245
246	while ( full_packets < packets_per_frame ) {
247		empty_packet = first_packet = last_packet = mid_packet = 0;
248
249		data_p = f->data + full_packets * 480;
250
251		/************************************************/
252		/* allocate a descriptor block and a CIP header */
253		/************************************************/
254
255		/* note: these should NOT cross a page boundary (DMA restriction) */
256
257		if (f->n_packets >= MAX_PACKETS) {
258			printk(KERN_ERR "dv1394: FATAL ERROR: max packet count exceeded\n");
259			return;
260		}
261
262		/* the block surely won't cross a page boundary,
263		   since an even number of descriptor_blocks fit on a page */
264		block = &(f->descriptor_pool[f->n_packets]);
265
266		/* DMA address of the block = offset of block relative
267		    to the kernel base address of the descriptor pool
268		    + DMA base address of the descriptor pool */
269		block_dma = ((unsigned long) block - (unsigned long) f->descriptor_pool) + f->descriptor_pool_dma;
270
271
272		/* the whole CIP pool fits on one page, so no worries about boundaries */
273		if ( ((unsigned long) &(f->header_pool[f->n_packets]) - (unsigned long) f->header_pool)
274		    > PAGE_SIZE) {
275			printk(KERN_ERR "dv1394: FATAL ERROR: no room to allocate CIP header\n");
276			return;
277		}
278
279		cip = &(f->header_pool[f->n_packets]);
280
281		/* DMA address of the CIP header = offset of cip
282		   relative to kernel base address of the header pool
283		   + DMA base address of the header pool */
284		cip_dma = (unsigned long) cip % PAGE_SIZE + f->header_pool_dma;
285
286		/* is this an empty packet? */
287
288		if (video->cip_accum > (video->cip_d - video->cip_n)) {
289			empty_packet = 1;
290			payload_size = 8;
291			video->cip_accum -= (video->cip_d - video->cip_n);
292		} else {
293			payload_size = 488;
294			video->cip_accum += video->cip_n;
295		}
296
297		/* there are three important packets each frame:
298
299		   the first packet in the frame - we ask the card to record the timestamp when
300		                                   this packet is actually sent, so we can monitor
301						   how accurate our timestamps are. Also, the first
302						   packet serves as a semaphore to let us know that
303						   it's OK to free the *previous* frame's DMA buffer
304
305		   the last packet in the frame -  this packet is used to detect buffer underflows.
306		                                   if this is the last ready frame, the last DMA block
307						   will have a branch back to the beginning of the frame
308						   (so that the card will re-send the frame on underflow).
309						   if this branch gets taken, we know that at least one
310						   frame has been dropped. When the next frame is ready,
311						   the branch is pointed to its first packet, and the
312						   semaphore is disabled.
313
314		   a "mid" packet slightly before the end of the frame - this packet should trigger
315		                   an interrupt so we can go and assign a timestamp to the first packet
316				   in the next frame. We don't use the very last packet in the frame
317				   for this purpose, because that would leave very little time to set
318				   the timestamp before DMA starts on the next frame.
319		*/
320
321		if (f->n_packets == 0) {
322			first_packet = 1;
323		} else if ( full_packets == (packets_per_frame-1) ) {
324			last_packet = 1;
325		} else if (f->n_packets == packets_per_frame) {
326			mid_packet = 1;
327		}
328
329
330		/********************/
331		/* setup CIP header */
332		/********************/
333
334		/* the timestamp will be written later from the
335		   mid-frame interrupt handler. For now we just
336		   store the address of the CIP header(s) that
337		   need a timestamp. */
338
339		/* first packet in the frame needs a timestamp */
340		if (first_packet) {
341			f->cip_syt1 = cip;
342			if (empty_packet)
343				first_packet_empty = 1;
344
345		} else if (first_packet_empty && (f->n_packets == 1) ) {
346			/* if the first packet was empty, the second
347			   packet's CIP header also needs a timestamp */
348			f->cip_syt2 = cip;
349		}
350
351		fill_cip_header(cip,
352				/* the node ID number of the OHCI card */
353				reg_read(video->ohci, OHCI1394_NodeID) & 0x3F,
354				video->continuity_counter,
355				video->pal_or_ntsc,
356				0xFFFF /* the timestamp is filled in later */);
357
358		/* advance counter, only for full packets */
359		if ( ! empty_packet )
360			video->continuity_counter++;
361
362		/******************************/
363		/* setup DMA descriptor block */
364		/******************************/
365
366		/* first descriptor - OUTPUT_MORE_IMMEDIATE, for the controller's IT header */
367		fill_output_more_immediate( &(block->u.out.omi), 1, video->channel, 0, payload_size);
368
369		if (empty_packet) {
370			/* second descriptor - OUTPUT_LAST for CIP header */
371			fill_output_last( &(block->u.out.u.empty.ol),
372
373					  /* want completion status on all interesting packets */
374					  (first_packet || mid_packet || last_packet) ? 1 : 0,
375
376					  /* want interrupts on all interesting packets */
377					  (first_packet || mid_packet || last_packet) ? 1 : 0,
378
379					  sizeof(struct CIP_header), /* data size */
380					  cip_dma);
381
382			if (first_packet)
383				f->frame_begin_timestamp = &(block->u.out.u.empty.ol.q[3]);
384			else if (mid_packet)
385				f->mid_frame_timestamp = &(block->u.out.u.empty.ol.q[3]);
386			else if (last_packet) {
387				f->frame_end_timestamp = &(block->u.out.u.empty.ol.q[3]);
388				f->frame_end_branch = &(block->u.out.u.empty.ol.q[2]);
389			}
390
391			branch_address = &(block->u.out.u.empty.ol.q[2]);
392			n_descriptors = 3;
393			if (first_packet)
394				f->first_n_descriptors = n_descriptors;
395
396		} else { /* full packet */
397
398			/* second descriptor - OUTPUT_MORE for CIP header */
399			fill_output_more( &(block->u.out.u.full.om),
400					  sizeof(struct CIP_header), /* data size */
401					  cip_dma);
402
403
404			/* third (and possibly fourth) descriptor - for DV data */
405			/* the 480-byte payload can cross a page boundary; if so,
406			   we need to split it into two DMA descriptors */
407
408			/* does the 480-byte data payload cross a page boundary? */
409			if ( (PAGE_SIZE- ((unsigned long)data_p % PAGE_SIZE) ) < 480 ) {
410
411				/* page boundary crossed */
412
413				fill_output_more( &(block->u.out.u.full.u.cross.om),
414						  /* data size - how much of data_p fits on the first page */
415						  PAGE_SIZE - (data_p % PAGE_SIZE),
416
417						  /* DMA address of data_p */
418						  dma_region_offset_to_bus(&video->dv_buf,
419									   data_p - (unsigned long) video->dv_buf.kvirt));
420
421				fill_output_last( &(block->u.out.u.full.u.cross.ol),
422
423						  /* want completion status on all interesting packets */
424						  (first_packet || mid_packet || last_packet) ? 1 : 0,
425
426						  /* want interrupt on all interesting packets */
427						  (first_packet || mid_packet || last_packet) ? 1 : 0,
428
429						  /* data size - remaining portion of data_p */
430						  480 - (PAGE_SIZE - (data_p % PAGE_SIZE)),
431
432						  /* DMA address of data_p + PAGE_SIZE - (data_p % PAGE_SIZE) */
433						  dma_region_offset_to_bus(&video->dv_buf,
434									   data_p + PAGE_SIZE - (data_p % PAGE_SIZE) - (unsigned long) video->dv_buf.kvirt));
435
436				if (first_packet)
437					f->frame_begin_timestamp = &(block->u.out.u.full.u.cross.ol.q[3]);
438				else if (mid_packet)
439					f->mid_frame_timestamp = &(block->u.out.u.full.u.cross.ol.q[3]);
440				else if (last_packet) {
441					f->frame_end_timestamp = &(block->u.out.u.full.u.cross.ol.q[3]);
442					f->frame_end_branch = &(block->u.out.u.full.u.cross.ol.q[2]);
443				}
444
445				branch_address = &(block->u.out.u.full.u.cross.ol.q[2]);
446
447				n_descriptors = 5;
448				if (first_packet)
449					f->first_n_descriptors = n_descriptors;
450
451				full_packets++;
452
453			} else {
454				/* fits on one page */
455
456				fill_output_last( &(block->u.out.u.full.u.nocross.ol),
457
458						  /* want completion status on all interesting packets */
459						  (first_packet || mid_packet || last_packet) ? 1 : 0,
460
461						  /* want interrupt on all interesting packets */
462						  (first_packet || mid_packet || last_packet) ? 1 : 0,
463
464						  480, /* data size (480 bytes of DV data) */
465
466
467						  /* DMA address of data_p */
468						  dma_region_offset_to_bus(&video->dv_buf,
469									   data_p - (unsigned long) video->dv_buf.kvirt));
470
471				if (first_packet)
472					f->frame_begin_timestamp = &(block->u.out.u.full.u.nocross.ol.q[3]);
473				else if (mid_packet)
474					f->mid_frame_timestamp = &(block->u.out.u.full.u.nocross.ol.q[3]);
475				else if (last_packet) {
476					f->frame_end_timestamp = &(block->u.out.u.full.u.nocross.ol.q[3]);
477					f->frame_end_branch = &(block->u.out.u.full.u.nocross.ol.q[2]);
478				}
479
480				branch_address = &(block->u.out.u.full.u.nocross.ol.q[2]);
481
482				n_descriptors = 4;
483				if (first_packet)
484					f->first_n_descriptors = n_descriptors;
485
486				full_packets++;
487			}
488		}
489
490		/* link this descriptor block into the DMA program by filling in
491		   the branch address of the previous block */
492
493		/* note: we are not linked into the active DMA chain yet */
494
495		if (last_branch_address) {
496			*(last_branch_address) = cpu_to_le32(block_dma | n_descriptors);
497		}
498
499		last_branch_address = branch_address;
500
501
502		f->n_packets++;
503
504	}
505
506	/* when we first assemble a new frame, set the final branch
507	   to loop back up to the top */
508	*(f->frame_end_branch) = cpu_to_le32(f->descriptor_pool_dma | f->first_n_descriptors);
509
510	/* make the latest version of this frame visible to the PCI card */
511	dma_region_sync_for_device(&video->dv_buf, f->data - (unsigned long) video->dv_buf.kvirt, video->frame_size);
512
513	/* lock against DMA interrupt */
514	spin_lock_irqsave(&video->spinlock, irq_flags);
515
516	f->state = FRAME_READY;
517
518	video->n_clear_frames--;
519
520	last_frame = video->first_clear_frame - 1;
521	if (last_frame == -1)
522		last_frame = video->n_frames-1;
523
524	video->first_clear_frame = (video->first_clear_frame + 1) % video->n_frames;
525
526	irq_printk("   frame %d prepared, active_frame = %d, n_clear_frames = %d, first_clear_frame = %d\n last=%d\n",
527		   this_frame, video->active_frame, video->n_clear_frames, video->first_clear_frame, last_frame);
528
529	irq_printk("   begin_ts %08lx mid_ts %08lx end_ts %08lx end_br %08lx\n",
530		   (unsigned long) f->frame_begin_timestamp,
531		   (unsigned long) f->mid_frame_timestamp,
532		   (unsigned long) f->frame_end_timestamp,
533		   (unsigned long) f->frame_end_branch);
534
535	if (video->active_frame != -1) {
536
537		/* if DMA is already active, we are almost done */
538		/* just link us onto the active DMA chain */
539		if (video->frames[last_frame]->frame_end_branch) {
540			u32 temp;
541
542			/* point the previous frame's tail to this frame's head */
543			*(video->frames[last_frame]->frame_end_branch) = cpu_to_le32(f->descriptor_pool_dma | f->first_n_descriptors);
544
545			/* this write MUST precede the next one, or we could silently drop frames */
546			wmb();
547
548			/* disable the want_status semaphore on the last packet */
549			temp = le32_to_cpu(*(video->frames[last_frame]->frame_end_branch - 2));
550			temp &= 0xF7CFFFFF;
551			*(video->frames[last_frame]->frame_end_branch - 2) = cpu_to_le32(temp);
552
553			/* flush these writes to memory ASAP */
554			flush_pci_write(video->ohci);
555
556			/* NOTE:
557			   ideally the writes should be "atomic": if
558			   the OHCI card reads the want_status flag in
559			   between them, we'll falsely report a
560			   dropped frame. Hopefully this window is too
561			   small to really matter, and the consequence
562			   is rather harmless. */
563
564
565			irq_printk("     new frame %d linked onto DMA chain\n", this_frame);
566
567		} else {
568			printk(KERN_ERR "dv1394: last frame not ready???\n");
569		}
570
571	} else {
572
573		u32 transmit_sec, transmit_cyc;
574		u32 ts_cyc, ts_off;
575
576		/* DMA is stopped, so this is the very first frame */
577		video->active_frame = this_frame;
578
579	        /* set CommandPtr to address and size of first descriptor block */
580		reg_write(video->ohci, video->ohci_IsoXmitCommandPtr,
581			  video->frames[video->active_frame]->descriptor_pool_dma |
582			  f->first_n_descriptors);
583
584		/* assign a timestamp based on the current cycle time...
585		   We'll tell the card to begin DMA 100 cycles from now,
586		   and assign a timestamp 103 cycles from now */
587
588		cycleTimer = reg_read(video->ohci, OHCI1394_IsochronousCycleTimer);
589
590		ct_sec = cycleTimer >> 25;
591		ct_cyc = (cycleTimer >> 12) & 0x1FFF;
592		ct_off = cycleTimer & 0xFFF;
593
594		transmit_sec = ct_sec;
595		transmit_cyc = ct_cyc + 100;
596
597		transmit_sec += transmit_cyc/8000;
598		transmit_cyc %= 8000;
599
600		ts_off = ct_off;
601		ts_cyc = transmit_cyc + 3;
602		ts_cyc %= 8000;
603
604		f->assigned_timestamp = (ts_cyc&0xF) << 12;
605
606		/* now actually write the timestamp into the appropriate CIP headers */
607		if (f->cip_syt1) {
608			f->cip_syt1->b[6] = f->assigned_timestamp >> 8;
609			f->cip_syt1->b[7] = f->assigned_timestamp & 0xFF;
610		}
611		if (f->cip_syt2) {
612			f->cip_syt2->b[6] = f->assigned_timestamp >> 8;
613			f->cip_syt2->b[7] = f->assigned_timestamp & 0xFF;
614		}
615
616		/* --- start DMA --- */
617
618		/* clear all bits in ContextControl register */
619
620		reg_write(video->ohci, video->ohci_IsoXmitContextControlClear, 0xFFFFFFFF);
621		wmb();
622
623		/* the OHCI card has the ability to start ISO transmission on a
624		   particular cycle (start-on-cycle). This way we can ensure that
625		   the first DV frame will have an accurate timestamp.
626
627		   However, start-on-cycle only appears to work if the OHCI card
628		   is cycle master! Since the consequences of messing up the first
629		   timestamp are minimal*, just disable start-on-cycle for now.
630
631		   * my DV deck drops the first few frames before it "locks in;"
632		     so the first frame having an incorrect timestamp is inconsequential.
633		*/
634
635
636		video->dma_running = 1;
637
638		/* set the 'run' bit */
639		reg_write(video->ohci, video->ohci_IsoXmitContextControlSet, 0x8000);
640		flush_pci_write(video->ohci);
641
642		/* --- DMA should be running now --- */
643
644		debug_printk("    Cycle = %4u ContextControl = %08x CmdPtr = %08x\n",
645			     (reg_read(video->ohci, OHCI1394_IsochronousCycleTimer) >> 12) & 0x1FFF,
646			     reg_read(video->ohci, video->ohci_IsoXmitContextControlSet),
647			     reg_read(video->ohci, video->ohci_IsoXmitCommandPtr));
648
649		debug_printk("    DMA start - current cycle %4u, transmit cycle %4u (%2u), assigning ts cycle %2u\n",
650			     ct_cyc, transmit_cyc, transmit_cyc & 0xF, ts_cyc & 0xF);
651
652#if DV1394_DEBUG_LEVEL >= 2
653		{
654			/* check if DMA is really running */
655			int i = 0;
656			while (i < 20) {
657				mb();
658				mdelay(1);
659				if (reg_read(video->ohci, video->ohci_IsoXmitContextControlSet) & (1 << 10)) {
660					printk("DMA ACTIVE after %d msec\n", i);
661					break;
662				}
663				i++;
664			}
665
666			printk("set = %08x, cmdPtr = %08x\n",
667			       reg_read(video->ohci, video->ohci_IsoXmitContextControlSet),
668			       reg_read(video->ohci, video->ohci_IsoXmitCommandPtr)
669			       );
670
671			if ( ! (reg_read(video->ohci, video->ohci_IsoXmitContextControlSet) &  (1 << 10)) ) {
672				printk("DMA did NOT go active after 20ms, event = %x\n",
673				       reg_read(video->ohci, video->ohci_IsoXmitContextControlSet) & 0x1F);
674			} else
675				printk("DMA is RUNNING!\n");
676		}
677#endif
678
679	}
680
681
682	spin_unlock_irqrestore(&video->spinlock, irq_flags);
683}
684
685
686
687/*** RECEIVE FUNCTIONS *****************************************************/
688
689/*
690	frame method put_packet
691
692	map and copy the packet data to its location in the frame
693	based upon DIF section and sequence
694*/
695
696static void inline
697frame_put_packet (struct frame *f, struct packet *p)
698{
699	int section_type = p->data[0] >> 5;           /* section type is in bits 5 - 7 */
700	int dif_sequence = p->data[1] >> 4;           /* dif sequence number is in bits 4 - 7 */
701	int dif_block = p->data[2];
702
703	/* sanity check */
704	if (dif_sequence > 11 || dif_block > 149) return;
705
706	switch (section_type) {
707	case 0:           /* 1 Header block */
708	        memcpy( (void *) f->data + dif_sequence * 150 * 80, p->data, 480);
709	        break;
710
711	case 1:           /* 2 Subcode blocks */
712	        memcpy( (void *) f->data + dif_sequence * 150 * 80 + (1 + dif_block) * 80, p->data, 480);
713	        break;
714
715	case 2:           /* 3 VAUX blocks */
716	        memcpy( (void *) f->data + dif_sequence * 150 * 80 + (3 + dif_block) * 80, p->data, 480);
717	        break;
718
719	case 3:           /* 9 Audio blocks interleaved with video */
720	        memcpy( (void *) f->data + dif_sequence * 150 * 80 + (6 + dif_block * 16) * 80, p->data, 480);
721	        break;
722
723	case 4:           /* 135 Video blocks interleaved with audio */
724	        memcpy( (void *) f->data + dif_sequence * 150 * 80 + (7 + (dif_block / 15) + dif_block) * 80, p->data, 480);
725	        break;
726
727	default:           /* we can not handle any other data */
728	        break;
729	}
730}
731
732
733static void start_dma_receive(struct video_card *video)
734{
735	if (video->first_run == 1) {
736		video->first_run = 0;
737
738		/* start DMA once all of the frames are READY */
739		video->n_clear_frames = 0;
740		video->first_clear_frame = -1;
741		video->current_packet = 0;
742		video->active_frame = 0;
743
744		/* reset iso recv control register */
745		reg_write(video->ohci, video->ohci_IsoRcvContextControlClear, 0xFFFFFFFF);
746		wmb();
747
748		/* clear bufferFill, set isochHeader and speed (0=100) */
749		reg_write(video->ohci, video->ohci_IsoRcvContextControlSet, 0x40000000);
750
751		/* match on all tags, listen on channel */
752		reg_write(video->ohci, video->ohci_IsoRcvContextMatch, 0xf0000000 | video->channel);
753
754		/* address and first descriptor block + Z=1 */
755		reg_write(video->ohci, video->ohci_IsoRcvCommandPtr,
756			  video->frames[0]->descriptor_pool_dma | 1); /* Z=1 */
757		wmb();
758
759		video->dma_running = 1;
760
761		/* run */
762		reg_write(video->ohci, video->ohci_IsoRcvContextControlSet, 0x8000);
763		flush_pci_write(video->ohci);
764
765		debug_printk("dv1394: DMA started\n");
766
767#if DV1394_DEBUG_LEVEL >= 2
768		{
769			int i;
770
771			for (i = 0; i < 1000; ++i) {
772				mdelay(1);
773				if (reg_read(video->ohci, video->ohci_IsoRcvContextControlSet) & (1 << 10)) {
774					printk("DMA ACTIVE after %d msec\n", i);
775					break;
776				}
777			}
778			if ( reg_read(video->ohci, video->ohci_IsoRcvContextControlSet) &  (1 << 11) ) {
779				printk("DEAD, event = %x\n",
780					   reg_read(video->ohci, video->ohci_IsoRcvContextControlSet) & 0x1F);
781			} else
782				printk("RUNNING!\n");
783		}
784#endif
785	} else if ( reg_read(video->ohci, video->ohci_IsoRcvContextControlSet) &  (1 << 11) ) {
786		debug_printk("DEAD, event = %x\n",
787			     reg_read(video->ohci, video->ohci_IsoRcvContextControlSet) & 0x1F);
788
789		/* wake */
790		reg_write(video->ohci, video->ohci_IsoRcvContextControlSet, (1 << 12));
791	}
792}
793
794
795/*
796   receive_packets() - build the DMA program for receiving
797*/
798
799static void receive_packets(struct video_card *video)
800{
801	struct DMA_descriptor_block *block = NULL;
802	dma_addr_t block_dma = 0;
803	struct packet *data = NULL;
804	dma_addr_t data_dma = 0;
805	u32 *last_branch_address = NULL;
806	unsigned long irq_flags;
807	int want_interrupt = 0;
808	struct frame *f = NULL;
809	int i, j;
810
811	spin_lock_irqsave(&video->spinlock, irq_flags);
812
813	for (j = 0; j < video->n_frames; j++) {
814
815		/* connect frames */
816		if (j > 0 && f != NULL && f->frame_end_branch != NULL)
817			*(f->frame_end_branch) = cpu_to_le32(video->frames[j]->descriptor_pool_dma | 1); /* set Z=1 */
818
819		f = video->frames[j];
820
821		for (i = 0; i < MAX_PACKETS; i++) {
822			/* locate a descriptor block and packet from the buffer */
823			block = &(f->descriptor_pool[i]);
824			block_dma = ((unsigned long) block - (unsigned long) f->descriptor_pool) + f->descriptor_pool_dma;
825
826			data = ((struct packet*)video->packet_buf.kvirt) + f->frame_num * MAX_PACKETS + i;
827			data_dma = dma_region_offset_to_bus( &video->packet_buf,
828							     ((unsigned long) data - (unsigned long) video->packet_buf.kvirt) );
829
830			/* setup DMA descriptor block */
831			want_interrupt = ((i % (MAX_PACKETS/2)) == 0 || i == (MAX_PACKETS-1));
832			fill_input_last( &(block->u.in.il), want_interrupt, 512, data_dma);
833
834			/* link descriptors */
835			last_branch_address = f->frame_end_branch;
836
837			if (last_branch_address != NULL)
838				*(last_branch_address) = cpu_to_le32(block_dma | 1); /* set Z=1 */
839
840			f->frame_end_branch = &(block->u.in.il.q[2]);
841		}
842
843	} /* next j */
844
845	spin_unlock_irqrestore(&video->spinlock, irq_flags);
846
847}
848
849
850
851/*** MANAGEMENT FUNCTIONS **************************************************/
852
853static int do_dv1394_init(struct video_card *video, struct dv1394_init *init)
854{
855	unsigned long flags, new_buf_size;
856	int i;
857	u64 chan_mask;
858	int retval = -EINVAL;
859
860	debug_printk("dv1394: initialising %d\n", video->id);
861	if (init->api_version != DV1394_API_VERSION)
862		return -EINVAL;
863
864	/* first sanitize all the parameters */
865	if ( (init->n_frames < 2) || (init->n_frames > DV1394_MAX_FRAMES) )
866		return -EINVAL;
867
868	if ( (init->format != DV1394_NTSC) && (init->format != DV1394_PAL) )
869		return -EINVAL;
870
871	if ( (init->syt_offset == 0) || (init->syt_offset > 50) )
872		/* default SYT offset is 3 cycles */
873		init->syt_offset = 3;
874
875	if ( (init->channel > 63) || (init->channel < 0) )
876		init->channel = 63;
877
878	chan_mask = (u64)1 << init->channel;
879
880	/* calculate what size DMA buffer is needed */
881	if (init->format == DV1394_NTSC)
882		new_buf_size = DV1394_NTSC_FRAME_SIZE * init->n_frames;
883	else
884		new_buf_size = DV1394_PAL_FRAME_SIZE * init->n_frames;
885
886	/* round up to PAGE_SIZE */
887	if (new_buf_size % PAGE_SIZE) new_buf_size += PAGE_SIZE - (new_buf_size % PAGE_SIZE);
888
889	/* don't allow the user to allocate the DMA buffer more than once */
890	if (video->dv_buf.kvirt && video->dv_buf_size != new_buf_size) {
891		printk("dv1394: re-sizing the DMA buffer is not allowed\n");
892		return -EINVAL;
893	}
894
895	/* shutdown the card if it's currently active */
896	/* (the card should not be reset if the parameters are screwy) */
897
898	do_dv1394_shutdown(video, 0);
899
900	/* try to claim the ISO channel */
901	spin_lock_irqsave(&video->ohci->IR_channel_lock, flags);
902	if (video->ohci->ISO_channel_usage & chan_mask) {
903		spin_unlock_irqrestore(&video->ohci->IR_channel_lock, flags);
904		retval = -EBUSY;
905		goto err;
906	}
907	video->ohci->ISO_channel_usage |= chan_mask;
908	spin_unlock_irqrestore(&video->ohci->IR_channel_lock, flags);
909
910	video->channel = init->channel;
911
912	/* initialize misc. fields of video */
913	video->n_frames = init->n_frames;
914	video->pal_or_ntsc = init->format;
915
916	video->cip_accum = 0;
917	video->continuity_counter = 0;
918
919	video->active_frame = -1;
920	video->first_clear_frame = 0;
921	video->n_clear_frames = video->n_frames;
922	video->dropped_frames = 0;
923
924	video->write_off = 0;
925
926	video->first_run = 1;
927	video->current_packet = -1;
928	video->first_frame = 0;
929
930	if (video->pal_or_ntsc == DV1394_NTSC) {
931		video->cip_n = init->cip_n != 0 ? init->cip_n : CIP_N_NTSC;
932		video->cip_d = init->cip_d != 0 ? init->cip_d : CIP_D_NTSC;
933		video->frame_size = DV1394_NTSC_FRAME_SIZE;
934	} else {
935		video->cip_n = init->cip_n != 0 ? init->cip_n : CIP_N_PAL;
936		video->cip_d = init->cip_d != 0 ? init->cip_d : CIP_D_PAL;
937		video->frame_size = DV1394_PAL_FRAME_SIZE;
938	}
939
940	video->syt_offset = init->syt_offset;
941
942	/* find and claim DMA contexts on the OHCI card */
943
944	if (video->ohci_it_ctx == -1) {
945		ohci1394_init_iso_tasklet(&video->it_tasklet, OHCI_ISO_TRANSMIT,
946					  it_tasklet_func, (unsigned long) video);
947
948		if (ohci1394_register_iso_tasklet(video->ohci, &video->it_tasklet) < 0) {
949			printk(KERN_ERR "dv1394: could not find an available IT DMA context\n");
950			retval = -EBUSY;
951			goto err;
952		}
953
954		video->ohci_it_ctx = video->it_tasklet.context;
955		debug_printk("dv1394: claimed IT DMA context %d\n", video->ohci_it_ctx);
956	}
957
958	if (video->ohci_ir_ctx == -1) {
959		ohci1394_init_iso_tasklet(&video->ir_tasklet, OHCI_ISO_RECEIVE,
960					  ir_tasklet_func, (unsigned long) video);
961
962		if (ohci1394_register_iso_tasklet(video->ohci, &video->ir_tasklet) < 0) {
963			printk(KERN_ERR "dv1394: could not find an available IR DMA context\n");
964			retval = -EBUSY;
965			goto err;
966		}
967		video->ohci_ir_ctx = video->ir_tasklet.context;
968		debug_printk("dv1394: claimed IR DMA context %d\n", video->ohci_ir_ctx);
969	}
970
971	/* allocate struct frames */
972	for (i = 0; i < init->n_frames; i++) {
973		video->frames[i] = frame_new(i, video);
974
975		if (!video->frames[i]) {
976			printk(KERN_ERR "dv1394: Cannot allocate frame structs\n");
977			retval = -ENOMEM;
978			goto err;
979		}
980	}
981
982	if (!video->dv_buf.kvirt) {
983		/* allocate the ringbuffer */
984		retval = dma_region_alloc(&video->dv_buf, new_buf_size, video->ohci->dev, PCI_DMA_TODEVICE);
985		if (retval)
986			goto err;
987
988		video->dv_buf_size = new_buf_size;
989
990		debug_printk("dv1394: Allocated %d frame buffers, total %u pages (%u DMA pages), %lu bytes\n",
991			     video->n_frames, video->dv_buf.n_pages,
992			     video->dv_buf.n_dma_pages, video->dv_buf_size);
993	}
994
995	/* set up the frame->data pointers */
996	for (i = 0; i < video->n_frames; i++)
997		video->frames[i]->data = (unsigned long) video->dv_buf.kvirt + i * video->frame_size;
998
999	if (!video->packet_buf.kvirt) {
1000		/* allocate packet buffer */
1001		video->packet_buf_size = sizeof(struct packet) * video->n_frames * MAX_PACKETS;
1002		if (video->packet_buf_size % PAGE_SIZE)
1003			video->packet_buf_size += PAGE_SIZE - (video->packet_buf_size % PAGE_SIZE);
1004
1005		retval = dma_region_alloc(&video->packet_buf, video->packet_buf_size,
1006					  video->ohci->dev, PCI_DMA_FROMDEVICE);
1007		if (retval)
1008			goto err;
1009
1010		debug_printk("dv1394: Allocated %d packets in buffer, total %u pages (%u DMA pages), %lu bytes\n",
1011				 video->n_frames*MAX_PACKETS, video->packet_buf.n_pages,
1012				 video->packet_buf.n_dma_pages, video->packet_buf_size);
1013	}
1014
1015	/* set up register offsets for IT context */
1016	/* IT DMA context registers are spaced 16 bytes apart */
1017	video->ohci_IsoXmitContextControlSet = OHCI1394_IsoXmitContextControlSet+16*video->ohci_it_ctx;
1018	video->ohci_IsoXmitContextControlClear = OHCI1394_IsoXmitContextControlClear+16*video->ohci_it_ctx;
1019	video->ohci_IsoXmitCommandPtr = OHCI1394_IsoXmitCommandPtr+16*video->ohci_it_ctx;
1020
1021	/* enable interrupts for IT context */
1022	reg_write(video->ohci, OHCI1394_IsoXmitIntMaskSet, (1 << video->ohci_it_ctx));
1023	debug_printk("dv1394: interrupts enabled for IT context %d\n", video->ohci_it_ctx);
1024
1025	/* set up register offsets for IR context */
1026	/* IR DMA context registers are spaced 32 bytes apart */
1027	video->ohci_IsoRcvContextControlSet = OHCI1394_IsoRcvContextControlSet+32*video->ohci_ir_ctx;
1028	video->ohci_IsoRcvContextControlClear = OHCI1394_IsoRcvContextControlClear+32*video->ohci_ir_ctx;
1029	video->ohci_IsoRcvCommandPtr = OHCI1394_IsoRcvCommandPtr+32*video->ohci_ir_ctx;
1030	video->ohci_IsoRcvContextMatch = OHCI1394_IsoRcvContextMatch+32*video->ohci_ir_ctx;
1031
1032	/* enable interrupts for IR context */
1033	reg_write(video->ohci, OHCI1394_IsoRecvIntMaskSet, (1 << video->ohci_ir_ctx) );
1034	debug_printk("dv1394: interrupts enabled for IR context %d\n", video->ohci_ir_ctx);
1035
1036	return 0;
1037
1038err:
1039	do_dv1394_shutdown(video, 1);
1040	return retval;
1041}
1042
1043/* if the user doesn't bother to call ioctl(INIT) before starting
1044   mmap() or read()/write(), just give him some default values */
1045
1046static int do_dv1394_init_default(struct video_card *video)
1047{
1048	struct dv1394_init init;
1049
1050	init.api_version = DV1394_API_VERSION;
1051	init.n_frames = DV1394_MAX_FRAMES / 4;
1052	init.channel = video->channel;
1053	init.format = video->pal_or_ntsc;
1054	init.cip_n = video->cip_n;
1055	init.cip_d = video->cip_d;
1056	init.syt_offset = video->syt_offset;
1057
1058	return do_dv1394_init(video, &init);
1059}
1060
1061/* do NOT call from interrupt context */
1062static void stop_dma(struct video_card *video)
1063{
1064	unsigned long flags;
1065	int i;
1066
1067	/* no interrupts */
1068	spin_lock_irqsave(&video->spinlock, flags);
1069
1070	video->dma_running = 0;
1071
1072	if ( (video->ohci_it_ctx == -1) && (video->ohci_ir_ctx == -1) )
1073		goto out;
1074
1075	/* stop DMA if in progress */
1076	if ( (video->active_frame != -1) ||
1077	    (reg_read(video->ohci, video->ohci_IsoXmitContextControlClear) & (1 << 10)) ||
1078	    (reg_read(video->ohci, video->ohci_IsoRcvContextControlClear) &  (1 << 10)) ) {
1079
1080		/* clear the .run bits */
1081		reg_write(video->ohci, video->ohci_IsoXmitContextControlClear, (1 << 15));
1082		reg_write(video->ohci, video->ohci_IsoRcvContextControlClear, (1 << 15));
1083		flush_pci_write(video->ohci);
1084
1085		video->active_frame = -1;
1086		video->first_run = 1;
1087
1088		/* wait until DMA really stops */
1089		i = 0;
1090		while (i < 1000) {
1091
1092			/* wait 0.1 millisecond */
1093			udelay(100);
1094
1095			if ( (reg_read(video->ohci, video->ohci_IsoXmitContextControlClear) & (1 << 10)) ||
1096			    (reg_read(video->ohci, video->ohci_IsoRcvContextControlClear)  & (1 << 10)) ) {
1097				/* still active */
1098				debug_printk("dv1394: stop_dma: DMA not stopped yet\n" );
1099				mb();
1100			} else {
1101				debug_printk("dv1394: stop_dma: DMA stopped safely after %d ms\n", i/10);
1102				break;
1103			}
1104
1105			i++;
1106		}
1107
1108		if (i == 1000) {
1109			printk(KERN_ERR "dv1394: stop_dma: DMA still going after %d ms!\n", i/10);
1110		}
1111	}
1112	else
1113		debug_printk("dv1394: stop_dma: already stopped.\n");
1114
1115out:
1116	spin_unlock_irqrestore(&video->spinlock, flags);
1117}
1118
1119
1120
1121static void do_dv1394_shutdown(struct video_card *video, int free_dv_buf)
1122{
1123	int i;
1124
1125	debug_printk("dv1394: shutdown...\n");
1126
1127	/* stop DMA if in progress */
1128	stop_dma(video);
1129
1130	/* release the DMA contexts */
1131	if (video->ohci_it_ctx != -1) {
1132		video->ohci_IsoXmitContextControlSet = 0;
1133		video->ohci_IsoXmitContextControlClear = 0;
1134		video->ohci_IsoXmitCommandPtr = 0;
1135
1136		/* disable interrupts for IT context */
1137		reg_write(video->ohci, OHCI1394_IsoXmitIntMaskClear, (1 << video->ohci_it_ctx));
1138
1139		/* remove tasklet */
1140		ohci1394_unregister_iso_tasklet(video->ohci, &video->it_tasklet);
1141		debug_printk("dv1394: IT context %d released\n", video->ohci_it_ctx);
1142		video->ohci_it_ctx = -1;
1143	}
1144
1145	if (video->ohci_ir_ctx != -1) {
1146		video->ohci_IsoRcvContextControlSet = 0;
1147		video->ohci_IsoRcvContextControlClear = 0;
1148		video->ohci_IsoRcvCommandPtr = 0;
1149		video->ohci_IsoRcvContextMatch = 0;
1150
1151		/* disable interrupts for IR context */
1152		reg_write(video->ohci, OHCI1394_IsoRecvIntMaskClear, (1 << video->ohci_ir_ctx));
1153
1154		/* remove tasklet */
1155		ohci1394_unregister_iso_tasklet(video->ohci, &video->ir_tasklet);
1156		debug_printk("dv1394: IR context %d released\n", video->ohci_ir_ctx);
1157		video->ohci_ir_ctx = -1;
1158	}
1159
1160	/* release the ISO channel */
1161	if (video->channel != -1) {
1162		u64 chan_mask;
1163		unsigned long flags;
1164
1165		chan_mask = (u64)1 << video->channel;
1166
1167		spin_lock_irqsave(&video->ohci->IR_channel_lock, flags);
1168		video->ohci->ISO_channel_usage &= ~(chan_mask);
1169		spin_unlock_irqrestore(&video->ohci->IR_channel_lock, flags);
1170
1171		video->channel = -1;
1172	}
1173
1174	/* free the frame structs */
1175	for (i = 0; i < DV1394_MAX_FRAMES; i++) {
1176		if (video->frames[i])
1177			frame_delete(video->frames[i]);
1178		video->frames[i] = NULL;
1179	}
1180
1181	video->n_frames = 0;
1182
1183	/* we can't free the DMA buffer unless it is guaranteed that
1184	   no more user-space mappings exist */
1185
1186	if (free_dv_buf) {
1187		dma_region_free(&video->dv_buf);
1188		video->dv_buf_size = 0;
1189	}
1190
1191	/* free packet buffer */
1192	dma_region_free(&video->packet_buf);
1193	video->packet_buf_size = 0;
1194
1195	debug_printk("dv1394: shutdown OK\n");
1196}
1197
1198/*
1199       **********************************
1200       *** MMAP() THEORY OF OPERATION ***
1201       **********************************
1202
1203        The ringbuffer cannot be re-allocated or freed while
1204        a user program maintains a mapping of it. (note that a mapping
1205	can persist even after the device fd is closed!)
1206
1207	So, only let the user process allocate the DMA buffer once.
1208	To resize or deallocate it, you must close the device file
1209	and open it again.
1210
1211	Previously Dan M. hacked out a scheme that allowed the DMA
1212	buffer to change by forcefully unmapping it from the user's
1213	address space. It was prone to error because it's very hard to
1214	track all the places the buffer could have been mapped (we
1215	would have had to walk the vma list of every process in the
1216	system to be sure we found all the mappings!). Instead, we
1217	force the user to choose one buffer size and stick with
1218	it. This small sacrifice is worth the huge reduction in
1219	error-prone code in dv1394.
1220*/
1221
1222static int dv1394_mmap(struct file *file, struct vm_area_struct *vma)
1223{
1224	struct video_card *video = file_to_video_card(file);
1225	int retval = -EINVAL;
1226
1227	/* serialize mmap */
1228	mutex_lock(&video->mtx);
1229
1230	if ( ! video_card_initialized(video) ) {
1231		retval = do_dv1394_init_default(video);
1232		if (retval)
1233			goto out;
1234	}
1235
1236	retval = dma_region_mmap(&video->dv_buf, file, vma);
1237out:
1238	mutex_unlock(&video->mtx);
1239	return retval;
1240}
1241
1242/*** DEVICE FILE INTERFACE *************************************************/
1243
1244/* no need to serialize, multiple threads OK */
1245static unsigned int dv1394_poll(struct file *file, struct poll_table_struct *wait)
1246{
1247	struct video_card *video = file_to_video_card(file);
1248	unsigned int mask = 0;
1249	unsigned long flags;
1250
1251	poll_wait(file, &video->waitq, wait);
1252
1253	spin_lock_irqsave(&video->spinlock, flags);
1254	if ( video->n_frames == 0 ) {
1255
1256	} else if ( video->active_frame == -1 ) {
1257		/* nothing going on */
1258		mask |= POLLOUT;
1259	} else {
1260		/* any clear/ready buffers? */
1261		if (video->n_clear_frames >0)
1262			mask |= POLLOUT | POLLIN;
1263	}
1264	spin_unlock_irqrestore(&video->spinlock, flags);
1265
1266	return mask;
1267}
1268
1269static int dv1394_fasync(int fd, struct file *file, int on)
1270{
1271	/* I just copied this code verbatim from Alan Cox's mouse driver example
1272	   (Documentation/DocBook/) */
1273
1274	struct video_card *video = file_to_video_card(file);
1275
1276	int retval = fasync_helper(fd, file, on, &video->fasync);
1277
1278	if (retval < 0)
1279		return retval;
1280        return 0;
1281}
1282
1283static ssize_t dv1394_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
1284{
1285	struct video_card *video = file_to_video_card(file);
1286	DECLARE_WAITQUEUE(wait, current);
1287	ssize_t ret;
1288	size_t cnt;
1289	unsigned long flags;
1290	int target_frame;
1291
1292	/* serialize this to prevent multi-threaded mayhem */
1293	if (file->f_flags & O_NONBLOCK) {
1294		if (!mutex_trylock(&video->mtx))
1295			return -EAGAIN;
1296	} else {
1297		if (mutex_lock_interruptible(&video->mtx))
1298			return -ERESTARTSYS;
1299	}
1300
1301	if ( !video_card_initialized(video) ) {
1302		ret = do_dv1394_init_default(video);
1303		if (ret) {
1304			mutex_unlock(&video->mtx);
1305			return ret;
1306		}
1307	}
1308
1309	ret = 0;
1310	add_wait_queue(&video->waitq, &wait);
1311
1312	while (count > 0) {
1313
1314		/* must set TASK_INTERRUPTIBLE *before* checking for free
1315		   buffers; otherwise we could miss a wakeup if the interrupt
1316		   fires between the check and the schedule() */
1317
1318		set_current_state(TASK_INTERRUPTIBLE);
1319
1320		spin_lock_irqsave(&video->spinlock, flags);
1321
1322		target_frame = video->first_clear_frame;
1323
1324		spin_unlock_irqrestore(&video->spinlock, flags);
1325
1326		if (video->frames[target_frame]->state == FRAME_CLEAR) {
1327
1328			/* how much room is left in the target frame buffer */
1329			cnt = video->frame_size - (video->write_off - target_frame * video->frame_size);
1330
1331		} else {
1332			/* buffer is already used */
1333			cnt = 0;
1334		}
1335
1336		if (cnt > count)
1337			cnt = count;
1338
1339		if (cnt <= 0) {
1340			/* no room left, gotta wait */
1341			if (file->f_flags & O_NONBLOCK) {
1342				if (!ret)
1343					ret = -EAGAIN;
1344				break;
1345			}
1346			if (signal_pending(current)) {
1347				if (!ret)
1348					ret = -ERESTARTSYS;
1349				break;
1350			}
1351
1352			schedule();
1353
1354			continue; /* start over from 'while(count > 0)...' */
1355		}
1356
1357		if (copy_from_user(video->dv_buf.kvirt + video->write_off, buffer, cnt)) {
1358			if (!ret)
1359				ret = -EFAULT;
1360			break;
1361		}
1362
1363		video->write_off = (video->write_off + cnt) % (video->n_frames * video->frame_size);
1364
1365		count -= cnt;
1366		buffer += cnt;
1367		ret += cnt;
1368
1369		if (video->write_off == video->frame_size * ((target_frame + 1) % video->n_frames))
1370				frame_prepare(video, target_frame);
1371	}
1372
1373	remove_wait_queue(&video->waitq, &wait);
1374	set_current_state(TASK_RUNNING);
1375	mutex_unlock(&video->mtx);
1376	return ret;
1377}
1378
1379
1380static ssize_t dv1394_read(struct file *file,  char __user *buffer, size_t count, loff_t *ppos)
1381{
1382	struct video_card *video = file_to_video_card(file);
1383	DECLARE_WAITQUEUE(wait, current);
1384	ssize_t ret;
1385	size_t cnt;
1386	unsigned long flags;
1387	int target_frame;
1388
1389	/* serialize this to prevent multi-threaded mayhem */
1390	if (file->f_flags & O_NONBLOCK) {
1391		if (!mutex_trylock(&video->mtx))
1392			return -EAGAIN;
1393	} else {
1394		if (mutex_lock_interruptible(&video->mtx))
1395			return -ERESTARTSYS;
1396	}
1397
1398	if ( !video_card_initialized(video) ) {
1399		ret = do_dv1394_init_default(video);
1400		if (ret) {
1401			mutex_unlock(&video->mtx);
1402			return ret;
1403		}
1404		video->continuity_counter = -1;
1405
1406		receive_packets(video);
1407
1408		start_dma_receive(video);
1409	}
1410
1411	ret = 0;
1412	add_wait_queue(&video->waitq, &wait);
1413
1414	while (count > 0) {
1415
1416		/* must set TASK_INTERRUPTIBLE *before* checking for free
1417		   buffers; otherwise we could miss a wakeup if the interrupt
1418		   fires between the check and the schedule() */
1419
1420		set_current_state(TASK_INTERRUPTIBLE);
1421
1422		spin_lock_irqsave(&video->spinlock, flags);
1423
1424		target_frame = video->first_clear_frame;
1425
1426		spin_unlock_irqrestore(&video->spinlock, flags);
1427
1428		if (target_frame >= 0 &&
1429			video->n_clear_frames > 0 &&
1430			video->frames[target_frame]->state == FRAME_CLEAR) {
1431
1432			/* how much room is left in the target frame buffer */
1433			cnt = video->frame_size - (video->write_off - target_frame * video->frame_size);
1434
1435		} else {
1436			/* buffer is already used */
1437			cnt = 0;
1438		}
1439
1440		if (cnt > count)
1441			cnt = count;
1442
1443		if (cnt <= 0) {
1444			/* no room left, gotta wait */
1445			if (file->f_flags & O_NONBLOCK) {
1446				if (!ret)
1447					ret = -EAGAIN;
1448				break;
1449			}
1450			if (signal_pending(current)) {
1451				if (!ret)
1452					ret = -ERESTARTSYS;
1453				break;
1454			}
1455
1456			schedule();
1457
1458			continue; /* start over from 'while(count > 0)...' */
1459		}
1460
1461		if (copy_to_user(buffer, video->dv_buf.kvirt + video->write_off, cnt)) {
1462				if (!ret)
1463					ret = -EFAULT;
1464				break;
1465		}
1466
1467		video->write_off = (video->write_off + cnt) % (video->n_frames * video->frame_size);
1468
1469		count -= cnt;
1470		buffer += cnt;
1471		ret += cnt;
1472
1473		if (video->write_off == video->frame_size * ((target_frame + 1) % video->n_frames)) {
1474			spin_lock_irqsave(&video->spinlock, flags);
1475			video->n_clear_frames--;
1476			video->first_clear_frame = (video->first_clear_frame + 1) % video->n_frames;
1477			spin_unlock_irqrestore(&video->spinlock, flags);
1478		}
1479	}
1480
1481	remove_wait_queue(&video->waitq, &wait);
1482	set_current_state(TASK_RUNNING);
1483	mutex_unlock(&video->mtx);
1484	return ret;
1485}
1486
1487
1488/*** DEVICE IOCTL INTERFACE ************************************************/
1489
1490static long dv1394_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1491{
1492	struct video_card *video = file_to_video_card(file);
1493	unsigned long flags;
1494	int ret = -EINVAL;
1495	void __user *argp = (void __user *)arg;
1496
1497	DECLARE_WAITQUEUE(wait, current);
1498
1499	/* serialize this to prevent multi-threaded mayhem */
1500	if (file->f_flags & O_NONBLOCK) {
1501		if (!mutex_trylock(&video->mtx))
1502			return -EAGAIN;
1503	} else {
1504		if (mutex_lock_interruptible(&video->mtx))
1505			return -ERESTARTSYS;
1506	}
1507
1508	switch(cmd)
1509	{
1510	case DV1394_IOC_SUBMIT_FRAMES: {
1511		unsigned int n_submit;
1512
1513		if ( !video_card_initialized(video) ) {
1514			ret = do_dv1394_init_default(video);
1515			if (ret)
1516				goto out;
1517		}
1518
1519		n_submit = (unsigned int) arg;
1520
1521		if (n_submit > video->n_frames) {
1522			ret = -EINVAL;
1523			goto out;
1524		}
1525
1526		while (n_submit > 0) {
1527
1528			add_wait_queue(&video->waitq, &wait);
1529			set_current_state(TASK_INTERRUPTIBLE);
1530
1531			spin_lock_irqsave(&video->spinlock, flags);
1532
1533			/* wait until video->first_clear_frame is really CLEAR */
1534			while (video->frames[video->first_clear_frame]->state != FRAME_CLEAR) {
1535
1536				spin_unlock_irqrestore(&video->spinlock, flags);
1537
1538				if (signal_pending(current)) {
1539					remove_wait_queue(&video->waitq, &wait);
1540					set_current_state(TASK_RUNNING);
1541					ret = -EINTR;
1542					goto out;
1543				}
1544
1545				schedule();
1546				set_current_state(TASK_INTERRUPTIBLE);
1547
1548				spin_lock_irqsave(&video->spinlock, flags);
1549			}
1550			spin_unlock_irqrestore(&video->spinlock, flags);
1551
1552			remove_wait_queue(&video->waitq, &wait);
1553			set_current_state(TASK_RUNNING);
1554
1555			frame_prepare(video, video->first_clear_frame);
1556
1557			n_submit--;
1558		}
1559
1560		ret = 0;
1561		break;
1562	}
1563
1564	case DV1394_IOC_WAIT_FRAMES: {
1565		unsigned int n_wait;
1566
1567		if ( !video_card_initialized(video) ) {
1568			ret = -EINVAL;
1569			goto out;
1570		}
1571
1572		n_wait = (unsigned int) arg;
1573
1574		/* since we re-run the last frame on underflow, we will
1575		   never actually have n_frames clear frames; at most only
1576		   n_frames - 1 */
1577
1578		if (n_wait > (video->n_frames-1) ) {
1579			ret = -EINVAL;
1580			goto out;
1581		}
1582
1583		add_wait_queue(&video->waitq, &wait);
1584		set_current_state(TASK_INTERRUPTIBLE);
1585
1586		spin_lock_irqsave(&video->spinlock, flags);
1587
1588		while (video->n_clear_frames < n_wait) {
1589
1590			spin_unlock_irqrestore(&video->spinlock, flags);
1591
1592			if (signal_pending(current)) {
1593				remove_wait_queue(&video->waitq, &wait);
1594				set_current_state(TASK_RUNNING);
1595				ret = -EINTR;
1596				goto out;
1597			}
1598
1599			schedule();
1600			set_current_state(TASK_INTERRUPTIBLE);
1601
1602			spin_lock_irqsave(&video->spinlock, flags);
1603		}
1604
1605		spin_unlock_irqrestore(&video->spinlock, flags);
1606
1607		remove_wait_queue(&video->waitq, &wait);
1608		set_current_state(TASK_RUNNING);
1609		ret = 0;
1610		break;
1611	}
1612
1613	case DV1394_IOC_RECEIVE_FRAMES: {
1614		unsigned int n_recv;
1615
1616		if ( !video_card_initialized(video) ) {
1617			ret = -EINVAL;
1618			goto out;
1619		}
1620
1621		n_recv = (unsigned int) arg;
1622
1623		/* at least one frame must be active */
1624		if (n_recv > (video->n_frames-1) ) {
1625			ret = -EINVAL;
1626			goto out;
1627		}
1628
1629		spin_lock_irqsave(&video->spinlock, flags);
1630
1631		/* release the clear frames */
1632		video->n_clear_frames -= n_recv;
1633
1634		/* advance the clear frame cursor */
1635		video->first_clear_frame = (video->first_clear_frame + n_recv) % video->n_frames;
1636
1637		/* reset dropped_frames */
1638		video->dropped_frames = 0;
1639
1640		spin_unlock_irqrestore(&video->spinlock, flags);
1641
1642		ret = 0;
1643		break;
1644	}
1645
1646	case DV1394_IOC_START_RECEIVE: {
1647		if ( !video_card_initialized(video) ) {
1648			ret = do_dv1394_init_default(video);
1649			if (ret)
1650				goto out;
1651		}
1652
1653		video->continuity_counter = -1;
1654
1655		receive_packets(video);
1656
1657		start_dma_receive(video);
1658
1659		ret = 0;
1660		break;
1661	}
1662
1663	case DV1394_IOC_INIT: {
1664		struct dv1394_init init;
1665		if (!argp) {
1666			ret = do_dv1394_init_default(video);
1667		} else {
1668			if (copy_from_user(&init, argp, sizeof(init))) {
1669				ret = -EFAULT;
1670				goto out;
1671			}
1672			ret = do_dv1394_init(video, &init);
1673		}
1674		break;
1675	}
1676
1677	case DV1394_IOC_SHUTDOWN:
1678		do_dv1394_shutdown(video, 0);
1679		ret = 0;
1680		break;
1681
1682
1683        case DV1394_IOC_GET_STATUS: {
1684		struct dv1394_status status;
1685
1686		if ( !video_card_initialized(video) ) {
1687			ret = -EINVAL;
1688			goto out;
1689		}
1690
1691		status.init.api_version = DV1394_API_VERSION;
1692		status.init.channel = video->channel;
1693		status.init.n_frames = video->n_frames;
1694		status.init.format = video->pal_or_ntsc;
1695		status.init.cip_n = video->cip_n;
1696		status.init.cip_d = video->cip_d;
1697		status.init.syt_offset = video->syt_offset;
1698
1699		status.first_clear_frame = video->first_clear_frame;
1700
1701		/* the rest of the fields need to be locked against the interrupt */
1702		spin_lock_irqsave(&video->spinlock, flags);
1703
1704		status.active_frame = video->active_frame;
1705		status.n_clear_frames = video->n_clear_frames;
1706
1707		status.dropped_frames = video->dropped_frames;
1708
1709		/* reset dropped_frames */
1710		video->dropped_frames = 0;
1711
1712		spin_unlock_irqrestore(&video->spinlock, flags);
1713
1714		if (copy_to_user(argp, &status, sizeof(status))) {
1715			ret = -EFAULT;
1716			goto out;
1717		}
1718
1719		ret = 0;
1720		break;
1721	}
1722
1723	default:
1724		break;
1725	}
1726
1727 out:
1728	mutex_unlock(&video->mtx);
1729	return ret;
1730}
1731
1732/*** DEVICE FILE INTERFACE CONTINUED ***************************************/
1733
1734static int dv1394_open(struct inode *inode, struct file *file)
1735{
1736	struct video_card *video = NULL;
1737
1738	if (file->private_data) {
1739		video = (struct video_card*) file->private_data;
1740
1741	} else {
1742		/* look up the card by ID */
1743		unsigned long flags;
1744
1745		spin_lock_irqsave(&dv1394_cards_lock, flags);
1746		if (!list_empty(&dv1394_cards)) {
1747			struct video_card *p;
1748			list_for_each_entry(p, &dv1394_cards, list) {
1749				if ((p->id) == ieee1394_file_to_instance(file)) {
1750					video = p;
1751					break;
1752				}
1753			}
1754		}
1755		spin_unlock_irqrestore(&dv1394_cards_lock, flags);
1756
1757		if (!video) {
1758			debug_printk("dv1394: OHCI card %d not found", ieee1394_file_to_instance(file));
1759			return -ENODEV;
1760		}
1761
1762		file->private_data = (void*) video;
1763	}
1764
1765#ifndef DV1394_ALLOW_MORE_THAN_ONE_OPEN
1766
1767	if ( test_and_set_bit(0, &video->open) ) {
1768		/* video is already open by someone else */
1769		return -EBUSY;
1770 	}
1771
1772#endif
1773
1774	return 0;
1775}
1776
1777
1778static int dv1394_release(struct inode *inode, struct file *file)
1779{
1780	struct video_card *video = file_to_video_card(file);
1781
1782	/* OK to free the DMA buffer, no more mappings can exist */
1783	do_dv1394_shutdown(video, 1);
1784
1785	/* clean up async I/O users */
1786	dv1394_fasync(-1, file, 0);
1787
1788	/* give someone else a turn */
1789	clear_bit(0, &video->open);
1790
1791	return 0;
1792}
1793
1794
1795/*** DEVICE DRIVER HANDLERS ************************************************/
1796
1797static void it_tasklet_func(unsigned long data)
1798{
1799	int wake = 0;
1800	struct video_card *video = (struct video_card*) data;
1801
1802	spin_lock(&video->spinlock);
1803
1804	if (!video->dma_running)
1805		goto out;
1806
1807	irq_printk("ContextControl = %08x, CommandPtr = %08x\n",
1808	       reg_read(video->ohci, video->ohci_IsoXmitContextControlSet),
1809	       reg_read(video->ohci, video->ohci_IsoXmitCommandPtr)
1810	       );
1811
1812
1813	if ( (video->ohci_it_ctx != -1) &&
1814	    (reg_read(video->ohci, video->ohci_IsoXmitContextControlSet) & (1 << 10)) ) {
1815
1816		struct frame *f;
1817		unsigned int frame, i;
1818
1819
1820		if (video->active_frame == -1)
1821			frame = 0;
1822		else
1823			frame = video->active_frame;
1824
1825		/* check all the DMA-able frames */
1826		for (i = 0; i < video->n_frames; i++, frame = (frame+1) % video->n_frames) {
1827
1828			irq_printk("IRQ checking frame %d...", frame);
1829			f = video->frames[frame];
1830			if (f->state != FRAME_READY) {
1831				irq_printk("clear, skipping\n");
1832				/* we don't own this frame */
1833				continue;
1834			}
1835
1836			irq_printk("DMA\n");
1837
1838			/* check the frame begin semaphore to see if we can free the previous frame */
1839			if ( *(f->frame_begin_timestamp) ) {
1840				int prev_frame;
1841				struct frame *prev_f;
1842
1843
1844
1845				/* don't reset, need this later *(f->frame_begin_timestamp) = 0; */
1846				irq_printk("  BEGIN\n");
1847
1848				prev_frame = frame - 1;
1849				if (prev_frame == -1)
1850					prev_frame += video->n_frames;
1851				prev_f = video->frames[prev_frame];
1852
1853				/* make sure we can actually garbage collect
1854				   this frame */
1855				if ( (prev_f->state == FRAME_READY) &&
1856				    prev_f->done && (!f->done) )
1857				{
1858					frame_reset(prev_f);
1859					video->n_clear_frames++;
1860					wake = 1;
1861					video->active_frame = frame;
1862
1863					irq_printk("  BEGIN - freeing previous frame %d, new active frame is %d\n", prev_frame, frame);
1864				} else {
1865					irq_printk("  BEGIN - can't free yet\n");
1866				}
1867
1868				f->done = 1;
1869			}
1870
1871
1872			/* see if we need to set the timestamp for the next frame */
1873			if ( *(f->mid_frame_timestamp) ) {
1874				struct frame *next_frame;
1875				u32 begin_ts, ts_cyc, ts_off;
1876
1877				*(f->mid_frame_timestamp) = 0;
1878
1879				begin_ts = le32_to_cpu(*(f->frame_begin_timestamp));
1880
1881				irq_printk("  MIDDLE - first packet was sent at cycle %4u (%2u), assigned timestamp was (%2u) %4u\n",
1882					   begin_ts & 0x1FFF, begin_ts & 0xF,
1883					   f->assigned_timestamp >> 12, f->assigned_timestamp & 0xFFF);
1884
1885				/* prepare next frame and assign timestamp */
1886				next_frame = video->frames[ (frame+1) % video->n_frames ];
1887
1888				if (next_frame->state == FRAME_READY) {
1889					irq_printk("  MIDDLE - next frame is ready, good\n");
1890				} else {
1891					debug_printk("dv1394: Underflow! At least one frame has been dropped.\n");
1892					next_frame = f;
1893				}
1894
1895				/* set the timestamp to the timestamp of the last frame sent,
1896				   plus the length of the last frame sent, plus the syt latency */
1897				ts_cyc = begin_ts & 0xF;
1898				/* advance one frame, plus syt latency (typically 2-3) */
1899				ts_cyc += f->n_packets + video->syt_offset ;
1900
1901				ts_off = 0;
1902
1903				ts_cyc += ts_off/3072;
1904				ts_off %= 3072;
1905
1906				next_frame->assigned_timestamp = ((ts_cyc&0xF) << 12) + ts_off;
1907				if (next_frame->cip_syt1) {
1908					next_frame->cip_syt1->b[6] = next_frame->assigned_timestamp >> 8;
1909					next_frame->cip_syt1->b[7] = next_frame->assigned_timestamp & 0xFF;
1910				}
1911				if (next_frame->cip_syt2) {
1912					next_frame->cip_syt2->b[6] = next_frame->assigned_timestamp >> 8;
1913					next_frame->cip_syt2->b[7] = next_frame->assigned_timestamp & 0xFF;
1914				}
1915
1916			}
1917
1918			/* see if the frame looped */
1919			if ( *(f->frame_end_timestamp) ) {
1920
1921				*(f->frame_end_timestamp) = 0;
1922
1923				debug_printk("  END - the frame looped at least once\n");
1924
1925				video->dropped_frames++;
1926			}
1927
1928		} /* for (each frame) */
1929	}
1930
1931	if (wake) {
1932		kill_fasync(&video->fasync, SIGIO, POLL_OUT);
1933
1934		/* wake readers/writers/ioctl'ers */
1935		wake_up_interruptible(&video->waitq);
1936	}
1937
1938out:
1939	spin_unlock(&video->spinlock);
1940}
1941
1942static void ir_tasklet_func(unsigned long data)
1943{
1944	int wake = 0;
1945	struct video_card *video = (struct video_card*) data;
1946
1947	spin_lock(&video->spinlock);
1948
1949	if (!video->dma_running)
1950		goto out;
1951
1952	if ( (video->ohci_ir_ctx != -1) &&
1953	    (reg_read(video->ohci, video->ohci_IsoRcvContextControlSet) & (1 << 10)) ) {
1954
1955		int sof=0; /* start-of-frame flag */
1956		struct frame *f;
1957		u16 packet_length, packet_time;
1958		int i, dbc=0;
1959		struct DMA_descriptor_block *block = NULL;
1960		u16 xferstatus;
1961
1962		int next_i, prev_i;
1963		struct DMA_descriptor_block *next = NULL;
1964		dma_addr_t next_dma = 0;
1965		struct DMA_descriptor_block *prev = NULL;
1966
1967		/* loop over all descriptors in all frames */
1968		for (i = 0; i < video->n_frames*MAX_PACKETS; i++) {
1969			struct packet *p = dma_region_i(&video->packet_buf, struct packet, video->current_packet);
1970
1971			/* make sure we are seeing the latest changes to p */
1972			dma_region_sync_for_cpu(&video->packet_buf,
1973						(unsigned long) p - (unsigned long) video->packet_buf.kvirt,
1974						sizeof(struct packet));
1975
1976			packet_length = le16_to_cpu(p->data_length);
1977			packet_time   = le16_to_cpu(p->timestamp);
1978
1979			irq_printk("received packet %02d, timestamp=%04x, length=%04x, sof=%02x%02x\n", video->current_packet,
1980				   packet_time, packet_length,
1981				   p->data[0], p->data[1]);
1982
1983			/* get the descriptor based on packet_buffer cursor */
1984			f = video->frames[video->current_packet / MAX_PACKETS];
1985			block = &(f->descriptor_pool[video->current_packet % MAX_PACKETS]);
1986			xferstatus = le32_to_cpu(block->u.in.il.q[3]) >> 16;
1987			xferstatus &= 0x1F;
1988			irq_printk("ir_tasklet_func: xferStatus/resCount [%d] = 0x%08x\n", i, le32_to_cpu(block->u.in.il.q[3]) );
1989
1990			/* get the current frame */
1991			f = video->frames[video->active_frame];
1992
1993			/* exclude empty packet */
1994			if (packet_length > 8 && xferstatus == 0x11) {
1995				/* check for start of frame */
1996				/* DRD> Changed to check section type ([0]>>5==0)
1997				   and dif sequence ([1]>>4==0) */
1998				sof = ( (p->data[0] >> 5) == 0 && (p->data[1] >> 4) == 0);
1999
2000				dbc = (int) (p->cip_h1 >> 24);
2001				if ( video->continuity_counter != -1 && dbc > ((video->continuity_counter + 1) % 256) )
2002				{
2003					printk(KERN_WARNING "dv1394: discontinuity detected, dropping all frames\n" );
2004					video->dropped_frames += video->n_clear_frames + 1;
2005					video->first_frame = 0;
2006					video->n_clear_frames = 0;
2007					video->first_clear_frame = -1;
2008				}
2009				video->continuity_counter = dbc;
2010
2011				if (!video->first_frame) {
2012					if (sof) {
2013						video->first_frame = 1;
2014					}
2015
2016				} else if (sof) {
2017					/* close current frame */
2018					frame_reset(f);  /* f->state = STATE_CLEAR */
2019					video->n_clear_frames++;
2020					if (video->n_clear_frames > video->n_frames) {
2021						video->dropped_frames++;
2022						printk(KERN_WARNING "dv1394: dropped a frame during reception\n" );
2023						video->n_clear_frames = video->n_frames-1;
2024						video->first_clear_frame = (video->first_clear_frame + 1) % video->n_frames;
2025					}
2026					if (video->first_clear_frame == -1)
2027						video->first_clear_frame = video->active_frame;
2028
2029					/* get the next frame */
2030					video->active_frame = (video->active_frame + 1) % video->n_frames;
2031					f = video->frames[video->active_frame];
2032					irq_printk("   frame received, active_frame = %d, n_clear_frames = %d, first_clear_frame = %d\n",
2033						   video->active_frame, video->n_clear_frames, video->first_clear_frame);
2034				}
2035				if (video->first_frame) {
2036					if (sof) {
2037						/* open next frame */
2038						f->state = FRAME_READY;
2039					}
2040
2041					/* copy to buffer */
2042					if (f->n_packets > (video->frame_size / 480)) {
2043						printk(KERN_ERR "frame buffer overflow during receive\n");
2044					}
2045
2046					frame_put_packet(f, p);
2047
2048				} /* first_frame */
2049			}
2050
2051			/* stop, end of ready packets */
2052			else if (xferstatus == 0) {
2053				break;
2054			}
2055
2056			/* reset xferStatus & resCount */
2057			block->u.in.il.q[3] = cpu_to_le32(512);
2058
2059			/* terminate dma chain at this (next) packet */
2060			next_i = video->current_packet;
2061			f = video->frames[next_i / MAX_PACKETS];
2062			next = &(f->descriptor_pool[next_i % MAX_PACKETS]);
2063			next_dma = ((unsigned long) block - (unsigned long) f->descriptor_pool) + f->descriptor_pool_dma;
2064			next->u.in.il.q[0] |= 3 << 20; /* enable interrupt */
2065			next->u.in.il.q[2] = 0; /* disable branch */
2066
2067			/* link previous to next */
2068			prev_i = (next_i == 0) ? (MAX_PACKETS * video->n_frames - 1) : (next_i - 1);
2069			f = video->frames[prev_i / MAX_PACKETS];
2070			prev = &(f->descriptor_pool[prev_i % MAX_PACKETS]);
2071			if (prev_i % (MAX_PACKETS/2)) {
2072				prev->u.in.il.q[0] &= ~(3 << 20); /* no interrupt */
2073			} else {
2074				prev->u.in.il.q[0] |= 3 << 20; /* enable interrupt */
2075			}
2076			prev->u.in.il.q[2] = cpu_to_le32(next_dma | 1); /* set Z=1 */
2077			wmb();
2078
2079			/* wake up DMA in case it fell asleep */
2080			reg_write(video->ohci, video->ohci_IsoRcvContextControlSet, (1 << 12));
2081
2082			/* advance packet_buffer cursor */
2083			video->current_packet = (video->current_packet + 1) % (MAX_PACKETS * video->n_frames);
2084
2085		} /* for all packets */
2086
2087		wake = 1; /* why the hell not? */
2088
2089	} /* receive interrupt */
2090
2091	if (wake) {
2092		kill_fasync(&video->fasync, SIGIO, POLL_IN);
2093
2094		/* wake readers/writers/ioctl'ers */
2095		wake_up_interruptible(&video->waitq);
2096	}
2097
2098out:
2099	spin_unlock(&video->spinlock);
2100}
2101
2102static struct cdev dv1394_cdev;
2103static const struct file_operations dv1394_fops=
2104{
2105	.owner =	THIS_MODULE,
2106	.poll =         dv1394_poll,
2107	.unlocked_ioctl = dv1394_ioctl,
2108#ifdef CONFIG_COMPAT
2109	.compat_ioctl = dv1394_compat_ioctl,
2110#endif
2111	.mmap =		dv1394_mmap,
2112	.open =		dv1394_open,
2113	.write =        dv1394_write,
2114	.read =         dv1394_read,
2115	.release =	dv1394_release,
2116	.fasync =       dv1394_fasync,
2117};
2118
2119
2120/*** HOTPLUG STUFF **********************************************************/
2121/*
2122 * Export information about protocols/devices supported by this driver.
2123 */
2124static struct ieee1394_device_id dv1394_id_table[] = {
2125	{
2126		.match_flags	= IEEE1394_MATCH_SPECIFIER_ID | IEEE1394_MATCH_VERSION,
2127		.specifier_id	= AVC_UNIT_SPEC_ID_ENTRY & 0xffffff,
2128		.version	= AVC_SW_VERSION_ENTRY & 0xffffff
2129	},
2130	{ }
2131};
2132
2133MODULE_DEVICE_TABLE(ieee1394, dv1394_id_table);
2134
2135static struct hpsb_protocol_driver dv1394_driver = {
2136	.name		= "dv1394",
2137	.id_table	= dv1394_id_table,
2138};
2139
2140
2141/*** IEEE1394 HPSB CALLBACKS ***********************************************/
2142
2143static int dv1394_init(struct ti_ohci *ohci, enum pal_or_ntsc format, enum modes mode)
2144{
2145	struct video_card *video;
2146	unsigned long flags;
2147	int i;
2148
2149	video = kzalloc(sizeof(*video), GFP_KERNEL);
2150	if (!video) {
2151		printk(KERN_ERR "dv1394: cannot allocate video_card\n");
2152		return -1;
2153	}
2154
2155	video->ohci = ohci;
2156	/* lower 2 bits of id indicate which of four "plugs"
2157	   per host */
2158	video->id = ohci->host->id << 2;
2159	if (format == DV1394_NTSC)
2160		video->id |= mode;
2161	else
2162		video->id |= 2 + mode;
2163
2164	video->ohci_it_ctx = -1;
2165	video->ohci_ir_ctx = -1;
2166
2167	video->ohci_IsoXmitContextControlSet = 0;
2168	video->ohci_IsoXmitContextControlClear = 0;
2169	video->ohci_IsoXmitCommandPtr = 0;
2170
2171	video->ohci_IsoRcvContextControlSet = 0;
2172	video->ohci_IsoRcvContextControlClear = 0;
2173	video->ohci_IsoRcvCommandPtr = 0;
2174	video->ohci_IsoRcvContextMatch = 0;
2175
2176	video->n_frames = 0; /* flag that video is not initialized */
2177	video->channel = 63; /* default to broadcast channel */
2178	video->active_frame = -1;
2179
2180	/* initialize the following */
2181	video->pal_or_ntsc = format;
2182	video->cip_n = 0; /* 0 = use builtin default */
2183	video->cip_d = 0;
2184	video->syt_offset = 0;
2185	video->mode = mode;
2186
2187	for (i = 0; i < DV1394_MAX_FRAMES; i++)
2188		video->frames[i] = NULL;
2189
2190	dma_region_init(&video->dv_buf);
2191	video->dv_buf_size = 0;
2192	dma_region_init(&video->packet_buf);
2193	video->packet_buf_size = 0;
2194
2195	clear_bit(0, &video->open);
2196	spin_lock_init(&video->spinlock);
2197	video->dma_running = 0;
2198	mutex_init(&video->mtx);
2199	init_waitqueue_head(&video->waitq);
2200	video->fasync = NULL;
2201
2202	spin_lock_irqsave(&dv1394_cards_lock, flags);
2203	INIT_LIST_HEAD(&video->list);
2204	list_add_tail(&video->list, &dv1394_cards);
2205	spin_unlock_irqrestore(&dv1394_cards_lock, flags);
2206
2207	debug_printk("dv1394: dv1394_init() OK on ID %d\n", video->id);
2208	return 0;
2209}
2210
2211static void dv1394_remove_host(struct hpsb_host *host)
2212{
2213	struct video_card *video, *tmp_video;
2214	unsigned long flags;
2215	int found_ohci_card = 0;
2216
2217	do {
2218		video = NULL;
2219		spin_lock_irqsave(&dv1394_cards_lock, flags);
2220		list_for_each_entry(tmp_video, &dv1394_cards, list) {
2221			if ((tmp_video->id >> 2) == host->id) {
2222				list_del(&tmp_video->list);
2223				video = tmp_video;
2224				found_ohci_card = 1;
2225				break;
2226			}
2227		}
2228		spin_unlock_irqrestore(&dv1394_cards_lock, flags);
2229
2230		if (video) {
2231			do_dv1394_shutdown(video, 1);
2232			kfree(video);
2233		}
2234	} while (video);
2235
2236	if (found_ohci_card)
2237		class_device_destroy(hpsb_protocol_class, MKDEV(IEEE1394_MAJOR,
2238			   IEEE1394_MINOR_BLOCK_DV1394 * 16 + (host->id << 2)));
2239}
2240
2241static void dv1394_add_host(struct hpsb_host *host)
2242{
2243	struct ti_ohci *ohci;
2244	int id = host->id;
2245
2246	/* We only work with the OHCI-1394 driver */
2247	if (strcmp(host->driver->name, OHCI1394_DRIVER_NAME))
2248		return;
2249
2250	ohci = (struct ti_ohci *)host->hostdata;
2251
2252	class_device_create(hpsb_protocol_class, NULL, MKDEV(
2253		IEEE1394_MAJOR,	IEEE1394_MINOR_BLOCK_DV1394 * 16 + (id<<2)),
2254		NULL, "dv1394-%d", id);
2255
2256	dv1394_init(ohci, DV1394_NTSC, MODE_RECEIVE);
2257	dv1394_init(ohci, DV1394_NTSC, MODE_TRANSMIT);
2258	dv1394_init(ohci, DV1394_PAL, MODE_RECEIVE);
2259	dv1394_init(ohci, DV1394_PAL, MODE_TRANSMIT);
2260}
2261
2262
2263/* Bus reset handler. In the event of a bus reset, we may need to
2264   re-start the DMA contexts - otherwise the user program would
2265   end up waiting forever.
2266*/
2267
2268static void dv1394_host_reset(struct hpsb_host *host)
2269{
2270	struct ti_ohci *ohci;
2271	struct video_card *video = NULL, *tmp_vid;
2272	unsigned long flags;
2273
2274	/* We only work with the OHCI-1394 driver */
2275	if (strcmp(host->driver->name, OHCI1394_DRIVER_NAME))
2276		return;
2277
2278	ohci = (struct ti_ohci *)host->hostdata;
2279
2280
2281	/* find the corresponding video_cards */
2282	spin_lock_irqsave(&dv1394_cards_lock, flags);
2283	list_for_each_entry(tmp_vid, &dv1394_cards, list) {
2284		if ((tmp_vid->id >> 2) == host->id) {
2285			video = tmp_vid;
2286			break;
2287		}
2288	}
2289	spin_unlock_irqrestore(&dv1394_cards_lock, flags);
2290
2291	if (!video)
2292		return;
2293
2294
2295	spin_lock_irqsave(&video->spinlock, flags);
2296
2297	if (!video->dma_running)
2298		goto out;
2299
2300	/* check IT context */
2301	if (video->ohci_it_ctx != -1) {
2302		u32 ctx;
2303
2304		ctx = reg_read(video->ohci, video->ohci_IsoXmitContextControlSet);
2305
2306		/* if (RUN but not ACTIVE) */
2307		if ( (ctx & (1<<15)) &&
2308		    !(ctx & (1<<10)) ) {
2309
2310			debug_printk("dv1394: IT context stopped due to bus reset; waking it up\n");
2311
2312			/* to be safe, assume a frame has been dropped. User-space programs
2313			   should handle this condition like an underflow. */
2314			video->dropped_frames++;
2315
2316			/* for some reason you must clear, then re-set the RUN bit to restart DMA */
2317
2318			/* clear RUN */
2319			reg_write(video->ohci, video->ohci_IsoXmitContextControlClear, (1 << 15));
2320			flush_pci_write(video->ohci);
2321
2322			/* set RUN */
2323			reg_write(video->ohci, video->ohci_IsoXmitContextControlSet, (1 << 15));
2324			flush_pci_write(video->ohci);
2325
2326			/* set the WAKE bit (just in case; this isn't strictly necessary) */
2327			reg_write(video->ohci, video->ohci_IsoXmitContextControlSet, (1 << 12));
2328			flush_pci_write(video->ohci);
2329
2330			irq_printk("dv1394: AFTER IT restart ctx 0x%08x ptr 0x%08x\n",
2331				   reg_read(video->ohci, video->ohci_IsoXmitContextControlSet),
2332				   reg_read(video->ohci, video->ohci_IsoXmitCommandPtr));
2333		}
2334	}
2335
2336	/* check IR context */
2337	if (video->ohci_ir_ctx != -1) {
2338		u32 ctx;
2339
2340		ctx = reg_read(video->ohci, video->ohci_IsoRcvContextControlSet);
2341
2342		/* if (RUN but not ACTIVE) */
2343		if ( (ctx & (1<<15)) &&
2344		    !(ctx & (1<<10)) ) {
2345
2346			debug_printk("dv1394: IR context stopped due to bus reset; waking it up\n");
2347
2348			/* to be safe, assume a frame has been dropped. User-space programs
2349			   should handle this condition like an overflow. */
2350			video->dropped_frames++;
2351
2352			/* for some reason you must clear, then re-set the RUN bit to restart DMA */
2353
2354			/* clear RUN */
2355			reg_write(video->ohci, video->ohci_IsoRcvContextControlClear, (1 << 15));
2356			flush_pci_write(video->ohci);
2357
2358			/* set RUN */
2359			reg_write(video->ohci, video->ohci_IsoRcvContextControlSet, (1 << 15));
2360			flush_pci_write(video->ohci);
2361
2362			/* set the WAKE bit (just in case; this isn't strictly necessary) */
2363			reg_write(video->ohci, video->ohci_IsoRcvContextControlSet, (1 << 12));
2364			flush_pci_write(video->ohci);
2365
2366			irq_printk("dv1394: AFTER IR restart ctx 0x%08x ptr 0x%08x\n",
2367				   reg_read(video->ohci, video->ohci_IsoRcvContextControlSet),
2368				   reg_read(video->ohci, video->ohci_IsoRcvCommandPtr));
2369		}
2370	}
2371
2372out:
2373	spin_unlock_irqrestore(&video->spinlock, flags);
2374
2375	/* wake readers/writers/ioctl'ers */
2376	wake_up_interruptible(&video->waitq);
2377}
2378
2379static struct hpsb_highlevel dv1394_highlevel = {
2380	.name =		"dv1394",
2381	.add_host =	dv1394_add_host,
2382	.remove_host =	dv1394_remove_host,
2383	.host_reset =   dv1394_host_reset,
2384};
2385
2386#ifdef CONFIG_COMPAT
2387
2388#define DV1394_IOC32_INIT       _IOW('#', 0x06, struct dv1394_init32)
2389#define DV1394_IOC32_GET_STATUS _IOR('#', 0x0c, struct dv1394_status32)
2390
2391struct dv1394_init32 {
2392	u32 api_version;
2393	u32 channel;
2394	u32 n_frames;
2395	u32 format;
2396	u32 cip_n;
2397	u32 cip_d;
2398	u32 syt_offset;
2399};
2400
2401struct dv1394_status32 {
2402	struct dv1394_init32 init;
2403	s32 active_frame;
2404	u32 first_clear_frame;
2405	u32 n_clear_frames;
2406	u32 dropped_frames;
2407};
2408
2409/* RED-PEN: this should use compat_alloc_userspace instead */
2410
2411static int handle_dv1394_init(struct file *file, unsigned int cmd, unsigned long arg)
2412{
2413	struct dv1394_init32 dv32;
2414	struct dv1394_init dv;
2415	mm_segment_t old_fs;
2416	int ret;
2417
2418	if (file->f_op->unlocked_ioctl != dv1394_ioctl)
2419		return -EFAULT;
2420
2421	if (copy_from_user(&dv32, (void __user *)arg, sizeof(dv32)))
2422		return -EFAULT;
2423
2424	dv.api_version = dv32.api_version;
2425	dv.channel = dv32.channel;
2426	dv.n_frames = dv32.n_frames;
2427	dv.format = dv32.format;
2428	dv.cip_n = (unsigned long)dv32.cip_n;
2429	dv.cip_d = (unsigned long)dv32.cip_d;
2430	dv.syt_offset = dv32.syt_offset;
2431
2432	old_fs = get_fs();
2433	set_fs(KERNEL_DS);
2434	ret = dv1394_ioctl(file, DV1394_IOC_INIT, (unsigned long)&dv);
2435	set_fs(old_fs);
2436
2437	return ret;
2438}
2439
2440static int handle_dv1394_get_status(struct file *file, unsigned int cmd, unsigned long arg)
2441{
2442	struct dv1394_status32 dv32;
2443	struct dv1394_status dv;
2444	mm_segment_t old_fs;
2445	int ret;
2446
2447	if (file->f_op->unlocked_ioctl != dv1394_ioctl)
2448		return -EFAULT;
2449
2450	old_fs = get_fs();
2451	set_fs(KERNEL_DS);
2452	ret = dv1394_ioctl(file, DV1394_IOC_GET_STATUS, (unsigned long)&dv);
2453	set_fs(old_fs);
2454
2455	if (!ret) {
2456		dv32.init.api_version = dv.init.api_version;
2457		dv32.init.channel = dv.init.channel;
2458		dv32.init.n_frames = dv.init.n_frames;
2459		dv32.init.format = dv.init.format;
2460		dv32.init.cip_n = (u32)dv.init.cip_n;
2461		dv32.init.cip_d = (u32)dv.init.cip_d;
2462		dv32.init.syt_offset = dv.init.syt_offset;
2463		dv32.active_frame = dv.active_frame;
2464		dv32.first_clear_frame = dv.first_clear_frame;
2465		dv32.n_clear_frames = dv.n_clear_frames;
2466		dv32.dropped_frames = dv.dropped_frames;
2467
2468		if (copy_to_user((struct dv1394_status32 __user *)arg, &dv32, sizeof(dv32)))
2469			ret = -EFAULT;
2470	}
2471
2472	return ret;
2473}
2474
2475
2476
2477static long dv1394_compat_ioctl(struct file *file, unsigned int cmd,
2478			       unsigned long arg)
2479{
2480	switch (cmd) {
2481	case DV1394_IOC_SHUTDOWN:
2482	case DV1394_IOC_SUBMIT_FRAMES:
2483	case DV1394_IOC_WAIT_FRAMES:
2484	case DV1394_IOC_RECEIVE_FRAMES:
2485	case DV1394_IOC_START_RECEIVE:
2486		return dv1394_ioctl(file, cmd, arg);
2487
2488	case DV1394_IOC32_INIT:
2489		return handle_dv1394_init(file, cmd, arg);
2490	case DV1394_IOC32_GET_STATUS:
2491		return handle_dv1394_get_status(file, cmd, arg);
2492	default:
2493		return -ENOIOCTLCMD;
2494	}
2495}
2496
2497#endif /* CONFIG_COMPAT */
2498
2499
2500/*** KERNEL MODULE HANDLERS ************************************************/
2501
2502MODULE_AUTHOR("Dan Maas <dmaas@dcine.com>, Dan Dennedy <dan@dennedy.org>");
2503MODULE_DESCRIPTION("driver for DV input/output on OHCI board");
2504MODULE_SUPPORTED_DEVICE("dv1394");
2505MODULE_LICENSE("GPL");
2506
2507static void __exit dv1394_exit_module(void)
2508{
2509	hpsb_unregister_protocol(&dv1394_driver);
2510	hpsb_unregister_highlevel(&dv1394_highlevel);
2511	cdev_del(&dv1394_cdev);
2512}
2513
2514static int __init dv1394_init_module(void)
2515{
2516	int ret;
2517
2518	printk(KERN_WARNING
2519	       "NOTE: The dv1394 driver is unsupported and may be removed in a "
2520	       "future Linux release. Use raw1394 instead.\n");
2521
2522	cdev_init(&dv1394_cdev, &dv1394_fops);
2523	dv1394_cdev.owner = THIS_MODULE;
2524	kobject_set_name(&dv1394_cdev.kobj, "dv1394");
2525	ret = cdev_add(&dv1394_cdev, IEEE1394_DV1394_DEV, 16);
2526	if (ret) {
2527		printk(KERN_ERR "dv1394: unable to register character device\n");
2528		return ret;
2529	}
2530
2531	hpsb_register_highlevel(&dv1394_highlevel);
2532
2533	ret = hpsb_register_protocol(&dv1394_driver);
2534	if (ret) {
2535		printk(KERN_ERR "dv1394: failed to register protocol\n");
2536		hpsb_unregister_highlevel(&dv1394_highlevel);
2537		cdev_del(&dv1394_cdev);
2538		return ret;
2539	}
2540
2541	return 0;
2542}
2543
2544module_init(dv1394_init_module);
2545module_exit(dv1394_exit_module);
2546