• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /netgear-R7000-V1.0.7.12_1.2.5/components/opensource/linux/linux-2.6.36/drivers/ieee1394/
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 underflows 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 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	__le32 *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;
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_cyc = transmit_cyc + 3;
601		ts_cyc %= 8000;
602
603		f->assigned_timestamp = (ts_cyc&0xF) << 12;
604
605		/* now actually write the timestamp into the appropriate CIP headers */
606		if (f->cip_syt1) {
607			f->cip_syt1->b[6] = f->assigned_timestamp >> 8;
608			f->cip_syt1->b[7] = f->assigned_timestamp & 0xFF;
609		}
610		if (f->cip_syt2) {
611			f->cip_syt2->b[6] = f->assigned_timestamp >> 8;
612			f->cip_syt2->b[7] = f->assigned_timestamp & 0xFF;
613		}
614
615		/* --- start DMA --- */
616
617		/* clear all bits in ContextControl register */
618
619		reg_write(video->ohci, video->ohci_IsoXmitContextControlClear, 0xFFFFFFFF);
620		wmb();
621
622		/* the OHCI card has the ability to start ISO transmission on a
623		   particular cycle (start-on-cycle). This way we can ensure that
624		   the first DV frame will have an accurate timestamp.
625
626		   However, start-on-cycle only appears to work if the OHCI card
627		   is cycle master! Since the consequences of messing up the first
628		   timestamp are minimal*, just disable start-on-cycle for now.
629
630		   * my DV deck drops the first few frames before it "locks in;"
631		     so the first frame having an incorrect timestamp is inconsequential.
632		*/
633
634
635		video->dma_running = 1;
636
637		/* set the 'run' bit */
638		reg_write(video->ohci, video->ohci_IsoXmitContextControlSet, 0x8000);
639		flush_pci_write(video->ohci);
640
641		/* --- DMA should be running now --- */
642
643		debug_printk("    Cycle = %4u ContextControl = %08x CmdPtr = %08x\n",
644			     (reg_read(video->ohci, OHCI1394_IsochronousCycleTimer) >> 12) & 0x1FFF,
645			     reg_read(video->ohci, video->ohci_IsoXmitContextControlSet),
646			     reg_read(video->ohci, video->ohci_IsoXmitCommandPtr));
647
648		debug_printk("    DMA start - current cycle %4u, transmit cycle %4u (%2u), assigning ts cycle %2u\n",
649			     ct_cyc, transmit_cyc, transmit_cyc & 0xF, ts_cyc & 0xF);
650
651#if DV1394_DEBUG_LEVEL >= 2
652		{
653			/* check if DMA is really running */
654			int i = 0;
655			while (i < 20) {
656				mb();
657				mdelay(1);
658				if (reg_read(video->ohci, video->ohci_IsoXmitContextControlSet) & (1 << 10)) {
659					printk("DMA ACTIVE after %d msec\n", i);
660					break;
661				}
662				i++;
663			}
664
665			printk("set = %08x, cmdPtr = %08x\n",
666			       reg_read(video->ohci, video->ohci_IsoXmitContextControlSet),
667			       reg_read(video->ohci, video->ohci_IsoXmitCommandPtr)
668			       );
669
670			if ( ! (reg_read(video->ohci, video->ohci_IsoXmitContextControlSet) &  (1 << 10)) ) {
671				printk("DMA did NOT go active after 20ms, event = %x\n",
672				       reg_read(video->ohci, video->ohci_IsoXmitContextControlSet) & 0x1F);
673			} else
674				printk("DMA is RUNNING!\n");
675		}
676#endif
677
678	}
679
680
681	spin_unlock_irqrestore(&video->spinlock, irq_flags);
682}
683
684
685
686/*** RECEIVE FUNCTIONS *****************************************************/
687
688/*
689	frame method put_packet
690
691	map and copy the packet data to its location in the frame
692	based upon DIF section and sequence
693*/
694
695static void inline
696frame_put_packet (struct frame *f, struct packet *p)
697{
698	int section_type = p->data[0] >> 5;           /* section type is in bits 5 - 7 */
699	int dif_sequence = p->data[1] >> 4;           /* dif sequence number is in bits 4 - 7 */
700	int dif_block = p->data[2];
701
702	/* sanity check */
703	if (dif_sequence > 11 || dif_block > 149) return;
704
705	switch (section_type) {
706	case 0:           /* 1 Header block */
707	        memcpy( (void *) f->data + dif_sequence * 150 * 80, p->data, 480);
708	        break;
709
710	case 1:           /* 2 Subcode blocks */
711	        memcpy( (void *) f->data + dif_sequence * 150 * 80 + (1 + dif_block) * 80, p->data, 480);
712	        break;
713
714	case 2:           /* 3 VAUX blocks */
715	        memcpy( (void *) f->data + dif_sequence * 150 * 80 + (3 + dif_block) * 80, p->data, 480);
716	        break;
717
718	case 3:           /* 9 Audio blocks interleaved with video */
719	        memcpy( (void *) f->data + dif_sequence * 150 * 80 + (6 + dif_block * 16) * 80, p->data, 480);
720	        break;
721
722	case 4:           /* 135 Video blocks interleaved with audio */
723	        memcpy( (void *) f->data + dif_sequence * 150 * 80 + (7 + (dif_block / 15) + dif_block) * 80, p->data, 480);
724	        break;
725
726	default:           /* we can not handle any other data */
727	        break;
728	}
729}
730
731
732static void start_dma_receive(struct video_card *video)
733{
734	if (video->first_run == 1) {
735		video->first_run = 0;
736
737		/* start DMA once all of the frames are READY */
738		video->n_clear_frames = 0;
739		video->first_clear_frame = -1;
740		video->current_packet = 0;
741		video->active_frame = 0;
742
743		/* reset iso recv control register */
744		reg_write(video->ohci, video->ohci_IsoRcvContextControlClear, 0xFFFFFFFF);
745		wmb();
746
747		/* clear bufferFill, set isochHeader and speed (0=100) */
748		reg_write(video->ohci, video->ohci_IsoRcvContextControlSet, 0x40000000);
749
750		/* match on all tags, listen on channel */
751		reg_write(video->ohci, video->ohci_IsoRcvContextMatch, 0xf0000000 | video->channel);
752
753		/* address and first descriptor block + Z=1 */
754		reg_write(video->ohci, video->ohci_IsoRcvCommandPtr,
755			  video->frames[0]->descriptor_pool_dma | 1); /* Z=1 */
756		wmb();
757
758		video->dma_running = 1;
759
760		/* run */
761		reg_write(video->ohci, video->ohci_IsoRcvContextControlSet, 0x8000);
762		flush_pci_write(video->ohci);
763
764		debug_printk("dv1394: DMA started\n");
765
766#if DV1394_DEBUG_LEVEL >= 2
767		{
768			int i;
769
770			for (i = 0; i < 1000; ++i) {
771				mdelay(1);
772				if (reg_read(video->ohci, video->ohci_IsoRcvContextControlSet) & (1 << 10)) {
773					printk("DMA ACTIVE after %d msec\n", i);
774					break;
775				}
776			}
777			if ( reg_read(video->ohci, video->ohci_IsoRcvContextControlSet) &  (1 << 11) ) {
778				printk("DEAD, event = %x\n",
779					   reg_read(video->ohci, video->ohci_IsoRcvContextControlSet) & 0x1F);
780			} else
781				printk("RUNNING!\n");
782		}
783#endif
784	} else if ( reg_read(video->ohci, video->ohci_IsoRcvContextControlSet) &  (1 << 11) ) {
785		debug_printk("DEAD, event = %x\n",
786			     reg_read(video->ohci, video->ohci_IsoRcvContextControlSet) & 0x1F);
787
788		/* wake */
789		reg_write(video->ohci, video->ohci_IsoRcvContextControlSet, (1 << 12));
790	}
791}
792
793
794/*
795   receive_packets() - build the DMA program for receiving
796*/
797
798static void receive_packets(struct video_card *video)
799{
800	struct DMA_descriptor_block *block = NULL;
801	dma_addr_t block_dma = 0;
802	struct packet *data = NULL;
803	dma_addr_t data_dma = 0;
804	__le32 *last_branch_address = NULL;
805	unsigned long irq_flags;
806	int want_interrupt = 0;
807	struct frame *f = NULL;
808	int i, j;
809
810	spin_lock_irqsave(&video->spinlock, irq_flags);
811
812	for (j = 0; j < video->n_frames; j++) {
813
814		/* connect frames */
815		if (j > 0 && f != NULL && f->frame_end_branch != NULL)
816			*(f->frame_end_branch) = cpu_to_le32(video->frames[j]->descriptor_pool_dma | 1); /* set Z=1 */
817
818		f = video->frames[j];
819
820		for (i = 0; i < MAX_PACKETS; i++) {
821			/* locate a descriptor block and packet from the buffer */
822			block = &(f->descriptor_pool[i]);
823			block_dma = ((unsigned long) block - (unsigned long) f->descriptor_pool) + f->descriptor_pool_dma;
824
825			data = ((struct packet*)video->packet_buf.kvirt) + f->frame_num * MAX_PACKETS + i;
826			data_dma = dma_region_offset_to_bus( &video->packet_buf,
827							     ((unsigned long) data - (unsigned long) video->packet_buf.kvirt) );
828
829			/* setup DMA descriptor block */
830			want_interrupt = ((i % (MAX_PACKETS/2)) == 0 || i == (MAX_PACKETS-1));
831			fill_input_last( &(block->u.in.il), want_interrupt, 512, data_dma);
832
833			/* link descriptors */
834			last_branch_address = f->frame_end_branch;
835
836			if (last_branch_address != NULL)
837				*(last_branch_address) = cpu_to_le32(block_dma | 1); /* set Z=1 */
838
839			f->frame_end_branch = &(block->u.in.il.q[2]);
840		}
841
842	} /* next j */
843
844	spin_unlock_irqrestore(&video->spinlock, irq_flags);
845
846}
847
848
849
850/*** MANAGEMENT FUNCTIONS **************************************************/
851
852static int do_dv1394_init(struct video_card *video, struct dv1394_init *init)
853{
854	unsigned long flags, new_buf_size;
855	int i;
856	u64 chan_mask;
857	int retval = -EINVAL;
858
859	debug_printk("dv1394: initialising %d\n", video->id);
860	if (init->api_version != DV1394_API_VERSION)
861		return -EINVAL;
862
863	/* first sanitize all the parameters */
864	if ( (init->n_frames < 2) || (init->n_frames > DV1394_MAX_FRAMES) )
865		return -EINVAL;
866
867	if ( (init->format != DV1394_NTSC) && (init->format != DV1394_PAL) )
868		return -EINVAL;
869
870	if ( (init->syt_offset == 0) || (init->syt_offset > 50) )
871		/* default SYT offset is 3 cycles */
872		init->syt_offset = 3;
873
874	if (init->channel > 63)
875		init->channel = 63;
876
877	chan_mask = (u64)1 << init->channel;
878
879	/* calculate what size DMA buffer is needed */
880	if (init->format == DV1394_NTSC)
881		new_buf_size = DV1394_NTSC_FRAME_SIZE * init->n_frames;
882	else
883		new_buf_size = DV1394_PAL_FRAME_SIZE * init->n_frames;
884
885	/* round up to PAGE_SIZE */
886	if (new_buf_size % PAGE_SIZE) new_buf_size += PAGE_SIZE - (new_buf_size % PAGE_SIZE);
887
888	/* don't allow the user to allocate the DMA buffer more than once */
889	if (video->dv_buf.kvirt && video->dv_buf_size != new_buf_size) {
890		printk("dv1394: re-sizing the DMA buffer is not allowed\n");
891		return -EINVAL;
892	}
893
894	/* shutdown the card if it's currently active */
895	/* (the card should not be reset if the parameters are screwy) */
896
897	do_dv1394_shutdown(video, 0);
898
899	/* try to claim the ISO channel */
900	spin_lock_irqsave(&video->ohci->IR_channel_lock, flags);
901	if (video->ohci->ISO_channel_usage & chan_mask) {
902		spin_unlock_irqrestore(&video->ohci->IR_channel_lock, flags);
903		retval = -EBUSY;
904		goto err;
905	}
906	video->ohci->ISO_channel_usage |= chan_mask;
907	spin_unlock_irqrestore(&video->ohci->IR_channel_lock, flags);
908
909	video->channel = init->channel;
910
911	/* initialize misc. fields of video */
912	video->n_frames = init->n_frames;
913	video->pal_or_ntsc = init->format;
914
915	video->cip_accum = 0;
916	video->continuity_counter = 0;
917
918	video->active_frame = -1;
919	video->first_clear_frame = 0;
920	video->n_clear_frames = video->n_frames;
921	video->dropped_frames = 0;
922
923	video->write_off = 0;
924
925	video->first_run = 1;
926	video->current_packet = -1;
927	video->first_frame = 0;
928
929	if (video->pal_or_ntsc == DV1394_NTSC) {
930		video->cip_n = init->cip_n != 0 ? init->cip_n : CIP_N_NTSC;
931		video->cip_d = init->cip_d != 0 ? init->cip_d : CIP_D_NTSC;
932		video->frame_size = DV1394_NTSC_FRAME_SIZE;
933	} else {
934		video->cip_n = init->cip_n != 0 ? init->cip_n : CIP_N_PAL;
935		video->cip_d = init->cip_d != 0 ? init->cip_d : CIP_D_PAL;
936		video->frame_size = DV1394_PAL_FRAME_SIZE;
937	}
938
939	video->syt_offset = init->syt_offset;
940
941	/* find and claim DMA contexts on the OHCI card */
942
943	if (video->ohci_it_ctx == -1) {
944		ohci1394_init_iso_tasklet(&video->it_tasklet, OHCI_ISO_TRANSMIT,
945					  it_tasklet_func, (unsigned long) video);
946
947		if (ohci1394_register_iso_tasklet(video->ohci, &video->it_tasklet) < 0) {
948			printk(KERN_ERR "dv1394: could not find an available IT DMA context\n");
949			retval = -EBUSY;
950			goto err;
951		}
952
953		video->ohci_it_ctx = video->it_tasklet.context;
954		debug_printk("dv1394: claimed IT DMA context %d\n", video->ohci_it_ctx);
955	}
956
957	if (video->ohci_ir_ctx == -1) {
958		ohci1394_init_iso_tasklet(&video->ir_tasklet, OHCI_ISO_RECEIVE,
959					  ir_tasklet_func, (unsigned long) video);
960
961		if (ohci1394_register_iso_tasklet(video->ohci, &video->ir_tasklet) < 0) {
962			printk(KERN_ERR "dv1394: could not find an available IR DMA context\n");
963			retval = -EBUSY;
964			goto err;
965		}
966		video->ohci_ir_ctx = video->ir_tasklet.context;
967		debug_printk("dv1394: claimed IR DMA context %d\n", video->ohci_ir_ctx);
968	}
969
970	/* allocate struct frames */
971	for (i = 0; i < init->n_frames; i++) {
972		video->frames[i] = frame_new(i, video);
973
974		if (!video->frames[i]) {
975			printk(KERN_ERR "dv1394: Cannot allocate frame structs\n");
976			retval = -ENOMEM;
977			goto err;
978		}
979	}
980
981	if (!video->dv_buf.kvirt) {
982		/* allocate the ringbuffer */
983		retval = dma_region_alloc(&video->dv_buf, new_buf_size, video->ohci->dev, PCI_DMA_TODEVICE);
984		if (retval)
985			goto err;
986
987		video->dv_buf_size = new_buf_size;
988
989		debug_printk("dv1394: Allocated %d frame buffers, total %u pages (%u DMA pages), %lu bytes\n",
990			     video->n_frames, video->dv_buf.n_pages,
991			     video->dv_buf.n_dma_pages, video->dv_buf_size);
992	}
993
994	/* set up the frame->data pointers */
995	for (i = 0; i < video->n_frames; i++)
996		video->frames[i]->data = (unsigned long) video->dv_buf.kvirt + i * video->frame_size;
997
998	if (!video->packet_buf.kvirt) {
999		/* allocate packet buffer */
1000		video->packet_buf_size = sizeof(struct packet) * video->n_frames * MAX_PACKETS;
1001		if (video->packet_buf_size % PAGE_SIZE)
1002			video->packet_buf_size += PAGE_SIZE - (video->packet_buf_size % PAGE_SIZE);
1003
1004		retval = dma_region_alloc(&video->packet_buf, video->packet_buf_size,
1005					  video->ohci->dev, PCI_DMA_FROMDEVICE);
1006		if (retval)
1007			goto err;
1008
1009		debug_printk("dv1394: Allocated %d packets in buffer, total %u pages (%u DMA pages), %lu bytes\n",
1010				 video->n_frames*MAX_PACKETS, video->packet_buf.n_pages,
1011				 video->packet_buf.n_dma_pages, video->packet_buf_size);
1012	}
1013
1014	/* set up register offsets for IT context */
1015	/* IT DMA context registers are spaced 16 bytes apart */
1016	video->ohci_IsoXmitContextControlSet = OHCI1394_IsoXmitContextControlSet+16*video->ohci_it_ctx;
1017	video->ohci_IsoXmitContextControlClear = OHCI1394_IsoXmitContextControlClear+16*video->ohci_it_ctx;
1018	video->ohci_IsoXmitCommandPtr = OHCI1394_IsoXmitCommandPtr+16*video->ohci_it_ctx;
1019
1020	/* enable interrupts for IT context */
1021	reg_write(video->ohci, OHCI1394_IsoXmitIntMaskSet, (1 << video->ohci_it_ctx));
1022	debug_printk("dv1394: interrupts enabled for IT context %d\n", video->ohci_it_ctx);
1023
1024	/* set up register offsets for IR context */
1025	/* IR DMA context registers are spaced 32 bytes apart */
1026	video->ohci_IsoRcvContextControlSet = OHCI1394_IsoRcvContextControlSet+32*video->ohci_ir_ctx;
1027	video->ohci_IsoRcvContextControlClear = OHCI1394_IsoRcvContextControlClear+32*video->ohci_ir_ctx;
1028	video->ohci_IsoRcvCommandPtr = OHCI1394_IsoRcvCommandPtr+32*video->ohci_ir_ctx;
1029	video->ohci_IsoRcvContextMatch = OHCI1394_IsoRcvContextMatch+32*video->ohci_ir_ctx;
1030
1031	/* enable interrupts for IR context */
1032	reg_write(video->ohci, OHCI1394_IsoRecvIntMaskSet, (1 << video->ohci_ir_ctx) );
1033	debug_printk("dv1394: interrupts enabled for IR context %d\n", video->ohci_ir_ctx);
1034
1035	return 0;
1036
1037err:
1038	do_dv1394_shutdown(video, 1);
1039	return retval;
1040}
1041
1042/* if the user doesn't bother to call ioctl(INIT) before starting
1043   mmap() or read()/write(), just give him some default values */
1044
1045static int do_dv1394_init_default(struct video_card *video)
1046{
1047	struct dv1394_init init;
1048
1049	init.api_version = DV1394_API_VERSION;
1050	init.n_frames = DV1394_MAX_FRAMES / 4;
1051	init.channel = video->channel;
1052	init.format = video->pal_or_ntsc;
1053	init.cip_n = video->cip_n;
1054	init.cip_d = video->cip_d;
1055	init.syt_offset = video->syt_offset;
1056
1057	return do_dv1394_init(video, &init);
1058}
1059
1060/* do NOT call from interrupt context */
1061static void stop_dma(struct video_card *video)
1062{
1063	unsigned long flags;
1064	int i;
1065
1066	/* no interrupts */
1067	spin_lock_irqsave(&video->spinlock, flags);
1068
1069	video->dma_running = 0;
1070
1071	if ( (video->ohci_it_ctx == -1) && (video->ohci_ir_ctx == -1) )
1072		goto out;
1073
1074	/* stop DMA if in progress */
1075	if ( (video->active_frame != -1) ||
1076	    (reg_read(video->ohci, video->ohci_IsoXmitContextControlClear) & (1 << 10)) ||
1077	    (reg_read(video->ohci, video->ohci_IsoRcvContextControlClear) &  (1 << 10)) ) {
1078
1079		/* clear the .run bits */
1080		reg_write(video->ohci, video->ohci_IsoXmitContextControlClear, (1 << 15));
1081		reg_write(video->ohci, video->ohci_IsoRcvContextControlClear, (1 << 15));
1082		flush_pci_write(video->ohci);
1083
1084		video->active_frame = -1;
1085		video->first_run = 1;
1086
1087		/* wait until DMA really stops */
1088		i = 0;
1089		while (i < 1000) {
1090
1091			/* wait 0.1 millisecond */
1092			udelay(100);
1093
1094			if ( (reg_read(video->ohci, video->ohci_IsoXmitContextControlClear) & (1 << 10)) ||
1095			    (reg_read(video->ohci, video->ohci_IsoRcvContextControlClear)  & (1 << 10)) ) {
1096				/* still active */
1097				debug_printk("dv1394: stop_dma: DMA not stopped yet\n" );
1098				mb();
1099			} else {
1100				debug_printk("dv1394: stop_dma: DMA stopped safely after %d ms\n", i/10);
1101				break;
1102			}
1103
1104			i++;
1105		}
1106
1107		if (i == 1000) {
1108			printk(KERN_ERR "dv1394: stop_dma: DMA still going after %d ms!\n", i/10);
1109		}
1110	}
1111	else
1112		debug_printk("dv1394: stop_dma: already stopped.\n");
1113
1114out:
1115	spin_unlock_irqrestore(&video->spinlock, flags);
1116}
1117
1118
1119
1120static void do_dv1394_shutdown(struct video_card *video, int free_dv_buf)
1121{
1122	int i;
1123
1124	debug_printk("dv1394: shutdown...\n");
1125
1126	/* stop DMA if in progress */
1127	stop_dma(video);
1128
1129	/* release the DMA contexts */
1130	if (video->ohci_it_ctx != -1) {
1131		video->ohci_IsoXmitContextControlSet = 0;
1132		video->ohci_IsoXmitContextControlClear = 0;
1133		video->ohci_IsoXmitCommandPtr = 0;
1134
1135		/* disable interrupts for IT context */
1136		reg_write(video->ohci, OHCI1394_IsoXmitIntMaskClear, (1 << video->ohci_it_ctx));
1137
1138		/* remove tasklet */
1139		ohci1394_unregister_iso_tasklet(video->ohci, &video->it_tasklet);
1140		debug_printk("dv1394: IT context %d released\n", video->ohci_it_ctx);
1141		video->ohci_it_ctx = -1;
1142	}
1143
1144	if (video->ohci_ir_ctx != -1) {
1145		video->ohci_IsoRcvContextControlSet = 0;
1146		video->ohci_IsoRcvContextControlClear = 0;
1147		video->ohci_IsoRcvCommandPtr = 0;
1148		video->ohci_IsoRcvContextMatch = 0;
1149
1150		/* disable interrupts for IR context */
1151		reg_write(video->ohci, OHCI1394_IsoRecvIntMaskClear, (1 << video->ohci_ir_ctx));
1152
1153		/* remove tasklet */
1154		ohci1394_unregister_iso_tasklet(video->ohci, &video->ir_tasklet);
1155		debug_printk("dv1394: IR context %d released\n", video->ohci_ir_ctx);
1156		video->ohci_ir_ctx = -1;
1157	}
1158
1159	/* release the ISO channel */
1160	if (video->channel != -1) {
1161		u64 chan_mask;
1162		unsigned long flags;
1163
1164		chan_mask = (u64)1 << video->channel;
1165
1166		spin_lock_irqsave(&video->ohci->IR_channel_lock, flags);
1167		video->ohci->ISO_channel_usage &= ~(chan_mask);
1168		spin_unlock_irqrestore(&video->ohci->IR_channel_lock, flags);
1169
1170		video->channel = -1;
1171	}
1172
1173	/* free the frame structs */
1174	for (i = 0; i < DV1394_MAX_FRAMES; i++) {
1175		if (video->frames[i])
1176			frame_delete(video->frames[i]);
1177		video->frames[i] = NULL;
1178	}
1179
1180	video->n_frames = 0;
1181
1182	/* we can't free the DMA buffer unless it is guaranteed that
1183	   no more user-space mappings exist */
1184
1185	if (free_dv_buf) {
1186		dma_region_free(&video->dv_buf);
1187		video->dv_buf_size = 0;
1188	}
1189
1190	/* free packet buffer */
1191	dma_region_free(&video->packet_buf);
1192	video->packet_buf_size = 0;
1193
1194	debug_printk("dv1394: shutdown OK\n");
1195}
1196
1197/*
1198       **********************************
1199       *** MMAP() THEORY OF OPERATION ***
1200       **********************************
1201
1202        The ringbuffer cannot be re-allocated or freed while
1203        a user program maintains a mapping of it. (note that a mapping
1204	can persist even after the device fd is closed!)
1205
1206	So, only let the user process allocate the DMA buffer once.
1207	To resize or deallocate it, you must close the device file
1208	and open it again.
1209
1210	Previously Dan M. hacked out a scheme that allowed the DMA
1211	buffer to change by forcefully unmapping it from the user's
1212	address space. It was prone to error because it's very hard to
1213	track all the places the buffer could have been mapped (we
1214	would have had to walk the vma list of every process in the
1215	system to be sure we found all the mappings!). Instead, we
1216	force the user to choose one buffer size and stick with
1217	it. This small sacrifice is worth the huge reduction in
1218	error-prone code in dv1394.
1219*/
1220
1221static int dv1394_mmap(struct file *file, struct vm_area_struct *vma)
1222{
1223	struct video_card *video = file_to_video_card(file);
1224	int retval = -EINVAL;
1225
1226	/*
1227	 * We cannot use the blocking variant mutex_lock here because .mmap
1228	 * is called with mmap_sem held, while .ioctl, .read, .write acquire
1229	 * video->mtx and subsequently call copy_to/from_user which will
1230	 * grab mmap_sem in case of a page fault.
1231	 */
1232	if (!mutex_trylock(&video->mtx))
1233		return -EAGAIN;
1234
1235	if ( ! video_card_initialized(video) ) {
1236		retval = do_dv1394_init_default(video);
1237		if (retval)
1238			goto out;
1239	}
1240
1241	retval = dma_region_mmap(&video->dv_buf, file, vma);
1242out:
1243	mutex_unlock(&video->mtx);
1244	return retval;
1245}
1246
1247/*** DEVICE FILE INTERFACE *************************************************/
1248
1249/* no need to serialize, multiple threads OK */
1250static unsigned int dv1394_poll(struct file *file, struct poll_table_struct *wait)
1251{
1252	struct video_card *video = file_to_video_card(file);
1253	unsigned int mask = 0;
1254	unsigned long flags;
1255
1256	poll_wait(file, &video->waitq, wait);
1257
1258	spin_lock_irqsave(&video->spinlock, flags);
1259	if ( video->n_frames == 0 ) {
1260
1261	} else if ( video->active_frame == -1 ) {
1262		/* nothing going on */
1263		mask |= POLLOUT;
1264	} else {
1265		/* any clear/ready buffers? */
1266		if (video->n_clear_frames >0)
1267			mask |= POLLOUT | POLLIN;
1268	}
1269	spin_unlock_irqrestore(&video->spinlock, flags);
1270
1271	return mask;
1272}
1273
1274static int dv1394_fasync(int fd, struct file *file, int on)
1275{
1276	/* I just copied this code verbatim from Alan Cox's mouse driver example
1277	   (Documentation/DocBook/) */
1278
1279	struct video_card *video = file_to_video_card(file);
1280
1281	return fasync_helper(fd, file, on, &video->fasync);
1282}
1283
1284static ssize_t dv1394_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
1285{
1286	struct video_card *video = file_to_video_card(file);
1287	DECLARE_WAITQUEUE(wait, current);
1288	ssize_t ret;
1289	size_t cnt;
1290	unsigned long flags;
1291	int target_frame;
1292
1293	/* serialize this to prevent multi-threaded mayhem */
1294	if (file->f_flags & O_NONBLOCK) {
1295		if (!mutex_trylock(&video->mtx))
1296			return -EAGAIN;
1297	} else {
1298		if (mutex_lock_interruptible(&video->mtx))
1299			return -ERESTARTSYS;
1300	}
1301
1302	if ( !video_card_initialized(video) ) {
1303		ret = do_dv1394_init_default(video);
1304		if (ret) {
1305			mutex_unlock(&video->mtx);
1306			return ret;
1307		}
1308	}
1309
1310	ret = 0;
1311	add_wait_queue(&video->waitq, &wait);
1312
1313	while (count > 0) {
1314
1315		/* must set TASK_INTERRUPTIBLE *before* checking for free
1316		   buffers; otherwise we could miss a wakeup if the interrupt
1317		   fires between the check and the schedule() */
1318
1319		set_current_state(TASK_INTERRUPTIBLE);
1320
1321		spin_lock_irqsave(&video->spinlock, flags);
1322
1323		target_frame = video->first_clear_frame;
1324
1325		spin_unlock_irqrestore(&video->spinlock, flags);
1326
1327		if (video->frames[target_frame]->state == FRAME_CLEAR) {
1328
1329			/* how much room is left in the target frame buffer */
1330			cnt = video->frame_size - (video->write_off - target_frame * video->frame_size);
1331
1332		} else {
1333			/* buffer is already used */
1334			cnt = 0;
1335		}
1336
1337		if (cnt > count)
1338			cnt = count;
1339
1340		if (cnt <= 0) {
1341			/* no room left, gotta wait */
1342			if (file->f_flags & O_NONBLOCK) {
1343				if (!ret)
1344					ret = -EAGAIN;
1345				break;
1346			}
1347			if (signal_pending(current)) {
1348				if (!ret)
1349					ret = -ERESTARTSYS;
1350				break;
1351			}
1352
1353			schedule();
1354
1355			continue; /* start over from 'while(count > 0)...' */
1356		}
1357
1358		if (copy_from_user(video->dv_buf.kvirt + video->write_off, buffer, cnt)) {
1359			if (!ret)
1360				ret = -EFAULT;
1361			break;
1362		}
1363
1364		video->write_off = (video->write_off + cnt) % (video->n_frames * video->frame_size);
1365
1366		count -= cnt;
1367		buffer += cnt;
1368		ret += cnt;
1369
1370		if (video->write_off == video->frame_size * ((target_frame + 1) % video->n_frames))
1371				frame_prepare(video, target_frame);
1372	}
1373
1374	remove_wait_queue(&video->waitq, &wait);
1375	set_current_state(TASK_RUNNING);
1376	mutex_unlock(&video->mtx);
1377	return ret;
1378}
1379
1380
1381static ssize_t dv1394_read(struct file *file,  char __user *buffer, size_t count, loff_t *ppos)
1382{
1383	struct video_card *video = file_to_video_card(file);
1384	DECLARE_WAITQUEUE(wait, current);
1385	ssize_t ret;
1386	size_t cnt;
1387	unsigned long flags;
1388	int target_frame;
1389
1390	/* serialize this to prevent multi-threaded mayhem */
1391	if (file->f_flags & O_NONBLOCK) {
1392		if (!mutex_trylock(&video->mtx))
1393			return -EAGAIN;
1394	} else {
1395		if (mutex_lock_interruptible(&video->mtx))
1396			return -ERESTARTSYS;
1397	}
1398
1399	if ( !video_card_initialized(video) ) {
1400		ret = do_dv1394_init_default(video);
1401		if (ret) {
1402			mutex_unlock(&video->mtx);
1403			return ret;
1404		}
1405		video->continuity_counter = -1;
1406
1407		receive_packets(video);
1408
1409		start_dma_receive(video);
1410	}
1411
1412	ret = 0;
1413	add_wait_queue(&video->waitq, &wait);
1414
1415	while (count > 0) {
1416
1417		/* must set TASK_INTERRUPTIBLE *before* checking for free
1418		   buffers; otherwise we could miss a wakeup if the interrupt
1419		   fires between the check and the schedule() */
1420
1421		set_current_state(TASK_INTERRUPTIBLE);
1422
1423		spin_lock_irqsave(&video->spinlock, flags);
1424
1425		target_frame = video->first_clear_frame;
1426
1427		spin_unlock_irqrestore(&video->spinlock, flags);
1428
1429		if (target_frame >= 0 &&
1430			video->n_clear_frames > 0 &&
1431			video->frames[target_frame]->state == FRAME_CLEAR) {
1432
1433			/* how much room is left in the target frame buffer */
1434			cnt = video->frame_size - (video->write_off - target_frame * video->frame_size);
1435
1436		} else {
1437			/* buffer is already used */
1438			cnt = 0;
1439		}
1440
1441		if (cnt > count)
1442			cnt = count;
1443
1444		if (cnt <= 0) {
1445			/* no room left, gotta wait */
1446			if (file->f_flags & O_NONBLOCK) {
1447				if (!ret)
1448					ret = -EAGAIN;
1449				break;
1450			}
1451			if (signal_pending(current)) {
1452				if (!ret)
1453					ret = -ERESTARTSYS;
1454				break;
1455			}
1456
1457			schedule();
1458
1459			continue; /* start over from 'while(count > 0)...' */
1460		}
1461
1462		if (copy_to_user(buffer, video->dv_buf.kvirt + video->write_off, cnt)) {
1463				if (!ret)
1464					ret = -EFAULT;
1465				break;
1466		}
1467
1468		video->write_off = (video->write_off + cnt) % (video->n_frames * video->frame_size);
1469
1470		count -= cnt;
1471		buffer += cnt;
1472		ret += cnt;
1473
1474		if (video->write_off == video->frame_size * ((target_frame + 1) % video->n_frames)) {
1475			spin_lock_irqsave(&video->spinlock, flags);
1476			video->n_clear_frames--;
1477			video->first_clear_frame = (video->first_clear_frame + 1) % video->n_frames;
1478			spin_unlock_irqrestore(&video->spinlock, flags);
1479		}
1480	}
1481
1482	remove_wait_queue(&video->waitq, &wait);
1483	set_current_state(TASK_RUNNING);
1484	mutex_unlock(&video->mtx);
1485	return ret;
1486}
1487
1488
1489/*** DEVICE IOCTL INTERFACE ************************************************/
1490
1491static long dv1394_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1492{
1493	struct video_card *video = file_to_video_card(file);
1494	unsigned long flags;
1495	int ret = -EINVAL;
1496	void __user *argp = (void __user *)arg;
1497
1498	DECLARE_WAITQUEUE(wait, current);
1499
1500	/* serialize this to prevent multi-threaded mayhem */
1501	if (file->f_flags & O_NONBLOCK) {
1502		if (!mutex_trylock(&video->mtx))
1503			return -EAGAIN;
1504	} else {
1505		if (mutex_lock_interruptible(&video->mtx))
1506			return -ERESTARTSYS;
1507	}
1508
1509	switch(cmd)
1510	{
1511	case DV1394_IOC_SUBMIT_FRAMES: {
1512		unsigned int n_submit;
1513
1514		if ( !video_card_initialized(video) ) {
1515			ret = do_dv1394_init_default(video);
1516			if (ret)
1517				goto out;
1518		}
1519
1520		n_submit = (unsigned int) arg;
1521
1522		if (n_submit > video->n_frames) {
1523			ret = -EINVAL;
1524			goto out;
1525		}
1526
1527		while (n_submit > 0) {
1528
1529			add_wait_queue(&video->waitq, &wait);
1530			set_current_state(TASK_INTERRUPTIBLE);
1531
1532			spin_lock_irqsave(&video->spinlock, flags);
1533
1534			/* wait until video->first_clear_frame is really CLEAR */
1535			while (video->frames[video->first_clear_frame]->state != FRAME_CLEAR) {
1536
1537				spin_unlock_irqrestore(&video->spinlock, flags);
1538
1539				if (signal_pending(current)) {
1540					remove_wait_queue(&video->waitq, &wait);
1541					set_current_state(TASK_RUNNING);
1542					ret = -EINTR;
1543					goto out;
1544				}
1545
1546				schedule();
1547				set_current_state(TASK_INTERRUPTIBLE);
1548
1549				spin_lock_irqsave(&video->spinlock, flags);
1550			}
1551			spin_unlock_irqrestore(&video->spinlock, flags);
1552
1553			remove_wait_queue(&video->waitq, &wait);
1554			set_current_state(TASK_RUNNING);
1555
1556			frame_prepare(video, video->first_clear_frame);
1557
1558			n_submit--;
1559		}
1560
1561		ret = 0;
1562		break;
1563	}
1564
1565	case DV1394_IOC_WAIT_FRAMES: {
1566		unsigned int n_wait;
1567
1568		if ( !video_card_initialized(video) ) {
1569			ret = -EINVAL;
1570			goto out;
1571		}
1572
1573		n_wait = (unsigned int) arg;
1574
1575		/* since we re-run the last frame on underflow, we will
1576		   never actually have n_frames clear frames; at most only
1577		   n_frames - 1 */
1578
1579		if (n_wait > (video->n_frames-1) ) {
1580			ret = -EINVAL;
1581			goto out;
1582		}
1583
1584		add_wait_queue(&video->waitq, &wait);
1585		set_current_state(TASK_INTERRUPTIBLE);
1586
1587		spin_lock_irqsave(&video->spinlock, flags);
1588
1589		while (video->n_clear_frames < n_wait) {
1590
1591			spin_unlock_irqrestore(&video->spinlock, flags);
1592
1593			if (signal_pending(current)) {
1594				remove_wait_queue(&video->waitq, &wait);
1595				set_current_state(TASK_RUNNING);
1596				ret = -EINTR;
1597				goto out;
1598			}
1599
1600			schedule();
1601			set_current_state(TASK_INTERRUPTIBLE);
1602
1603			spin_lock_irqsave(&video->spinlock, flags);
1604		}
1605
1606		spin_unlock_irqrestore(&video->spinlock, flags);
1607
1608		remove_wait_queue(&video->waitq, &wait);
1609		set_current_state(TASK_RUNNING);
1610		ret = 0;
1611		break;
1612	}
1613
1614	case DV1394_IOC_RECEIVE_FRAMES: {
1615		unsigned int n_recv;
1616
1617		if ( !video_card_initialized(video) ) {
1618			ret = -EINVAL;
1619			goto out;
1620		}
1621
1622		n_recv = (unsigned int) arg;
1623
1624		/* at least one frame must be active */
1625		if (n_recv > (video->n_frames-1) ) {
1626			ret = -EINVAL;
1627			goto out;
1628		}
1629
1630		spin_lock_irqsave(&video->spinlock, flags);
1631
1632		/* release the clear frames */
1633		video->n_clear_frames -= n_recv;
1634
1635		/* advance the clear frame cursor */
1636		video->first_clear_frame = (video->first_clear_frame + n_recv) % video->n_frames;
1637
1638		/* reset dropped_frames */
1639		video->dropped_frames = 0;
1640
1641		spin_unlock_irqrestore(&video->spinlock, flags);
1642
1643		ret = 0;
1644		break;
1645	}
1646
1647	case DV1394_IOC_START_RECEIVE: {
1648		if ( !video_card_initialized(video) ) {
1649			ret = do_dv1394_init_default(video);
1650			if (ret)
1651				goto out;
1652		}
1653
1654		video->continuity_counter = -1;
1655
1656		receive_packets(video);
1657
1658		start_dma_receive(video);
1659
1660		ret = 0;
1661		break;
1662	}
1663
1664	case DV1394_IOC_INIT: {
1665		struct dv1394_init init;
1666		if (!argp) {
1667			ret = do_dv1394_init_default(video);
1668		} else {
1669			if (copy_from_user(&init, argp, sizeof(init))) {
1670				ret = -EFAULT;
1671				goto out;
1672			}
1673			ret = do_dv1394_init(video, &init);
1674		}
1675		break;
1676	}
1677
1678	case DV1394_IOC_SHUTDOWN:
1679		do_dv1394_shutdown(video, 0);
1680		ret = 0;
1681		break;
1682
1683
1684        case DV1394_IOC_GET_STATUS: {
1685		struct dv1394_status status;
1686
1687		if ( !video_card_initialized(video) ) {
1688			ret = -EINVAL;
1689			goto out;
1690		}
1691
1692		status.init.api_version = DV1394_API_VERSION;
1693		status.init.channel = video->channel;
1694		status.init.n_frames = video->n_frames;
1695		status.init.format = video->pal_or_ntsc;
1696		status.init.cip_n = video->cip_n;
1697		status.init.cip_d = video->cip_d;
1698		status.init.syt_offset = video->syt_offset;
1699
1700		status.first_clear_frame = video->first_clear_frame;
1701
1702		/* the rest of the fields need to be locked against the interrupt */
1703		spin_lock_irqsave(&video->spinlock, flags);
1704
1705		status.active_frame = video->active_frame;
1706		status.n_clear_frames = video->n_clear_frames;
1707
1708		status.dropped_frames = video->dropped_frames;
1709
1710		/* reset dropped_frames */
1711		video->dropped_frames = 0;
1712
1713		spin_unlock_irqrestore(&video->spinlock, flags);
1714
1715		if (copy_to_user(argp, &status, sizeof(status))) {
1716			ret = -EFAULT;
1717			goto out;
1718		}
1719
1720		ret = 0;
1721		break;
1722	}
1723
1724	default:
1725		break;
1726	}
1727
1728 out:
1729	mutex_unlock(&video->mtx);
1730	return ret;
1731}
1732
1733/*** DEVICE FILE INTERFACE CONTINUED ***************************************/
1734
1735static int dv1394_open(struct inode *inode, struct file *file)
1736{
1737	struct video_card *video = NULL;
1738
1739	if (file->private_data) {
1740		video = file->private_data;
1741
1742	} else {
1743		/* look up the card by ID */
1744		unsigned long flags;
1745		int idx = ieee1394_file_to_instance(file);
1746
1747		spin_lock_irqsave(&dv1394_cards_lock, flags);
1748		if (!list_empty(&dv1394_cards)) {
1749			struct video_card *p;
1750			list_for_each_entry(p, &dv1394_cards, list) {
1751				if ((p->id) == idx) {
1752					video = p;
1753					break;
1754				}
1755			}
1756		}
1757		spin_unlock_irqrestore(&dv1394_cards_lock, flags);
1758
1759		if (!video) {
1760			debug_printk("dv1394: OHCI card %d not found", idx);
1761			return -ENODEV;
1762		}
1763
1764		file->private_data = (void*) video;
1765	}
1766
1767#ifndef DV1394_ALLOW_MORE_THAN_ONE_OPEN
1768
1769	if ( test_and_set_bit(0, &video->open) ) {
1770		/* video is already open by someone else */
1771		return -EBUSY;
1772 	}
1773
1774#endif
1775
1776	printk(KERN_INFO "%s: NOTE, the dv1394 interface is unsupported "
1777	       "and will not be available in the new firewire driver stack. "
1778	       "Try libraw1394 based programs instead.\n", current->comm);
1779
1780	return nonseekable_open(inode, file);
1781}
1782
1783
1784static int dv1394_release(struct inode *inode, struct file *file)
1785{
1786	struct video_card *video = file_to_video_card(file);
1787
1788	/* OK to free the DMA buffer, no more mappings can exist */
1789	do_dv1394_shutdown(video, 1);
1790
1791	/* give someone else a turn */
1792	clear_bit(0, &video->open);
1793
1794	return 0;
1795}
1796
1797
1798/*** DEVICE DRIVER HANDLERS ************************************************/
1799
1800static void it_tasklet_func(unsigned long data)
1801{
1802	int wake = 0;
1803	struct video_card *video = (struct video_card*) data;
1804
1805	spin_lock(&video->spinlock);
1806
1807	if (!video->dma_running)
1808		goto out;
1809
1810	irq_printk("ContextControl = %08x, CommandPtr = %08x\n",
1811	       reg_read(video->ohci, video->ohci_IsoXmitContextControlSet),
1812	       reg_read(video->ohci, video->ohci_IsoXmitCommandPtr)
1813	       );
1814
1815
1816	if ( (video->ohci_it_ctx != -1) &&
1817	    (reg_read(video->ohci, video->ohci_IsoXmitContextControlSet) & (1 << 10)) ) {
1818
1819		struct frame *f;
1820		unsigned int frame, i;
1821
1822
1823		if (video->active_frame == -1)
1824			frame = 0;
1825		else
1826			frame = video->active_frame;
1827
1828		/* check all the DMA-able frames */
1829		for (i = 0; i < video->n_frames; i++, frame = (frame+1) % video->n_frames) {
1830
1831			irq_printk("IRQ checking frame %d...", frame);
1832			f = video->frames[frame];
1833			if (f->state != FRAME_READY) {
1834				irq_printk("clear, skipping\n");
1835				/* we don't own this frame */
1836				continue;
1837			}
1838
1839			irq_printk("DMA\n");
1840
1841			/* check the frame begin semaphore to see if we can free the previous frame */
1842			if ( *(f->frame_begin_timestamp) ) {
1843				int prev_frame;
1844				struct frame *prev_f;
1845
1846
1847
1848				/* don't reset, need this later *(f->frame_begin_timestamp) = 0; */
1849				irq_printk("  BEGIN\n");
1850
1851				prev_frame = frame - 1;
1852				if (prev_frame == -1)
1853					prev_frame += video->n_frames;
1854				prev_f = video->frames[prev_frame];
1855
1856				/* make sure we can actually garbage collect
1857				   this frame */
1858				if ( (prev_f->state == FRAME_READY) &&
1859				    prev_f->done && (!f->done) )
1860				{
1861					frame_reset(prev_f);
1862					video->n_clear_frames++;
1863					wake = 1;
1864					video->active_frame = frame;
1865
1866					irq_printk("  BEGIN - freeing previous frame %d, new active frame is %d\n", prev_frame, frame);
1867				} else {
1868					irq_printk("  BEGIN - can't free yet\n");
1869				}
1870
1871				f->done = 1;
1872			}
1873
1874
1875			/* see if we need to set the timestamp for the next frame */
1876			if ( *(f->mid_frame_timestamp) ) {
1877				struct frame *next_frame;
1878				u32 begin_ts, ts_cyc, ts_off;
1879
1880				*(f->mid_frame_timestamp) = 0;
1881
1882				begin_ts = le32_to_cpu(*(f->frame_begin_timestamp));
1883
1884				irq_printk("  MIDDLE - first packet was sent at cycle %4u (%2u), assigned timestamp was (%2u) %4u\n",
1885					   begin_ts & 0x1FFF, begin_ts & 0xF,
1886					   f->assigned_timestamp >> 12, f->assigned_timestamp & 0xFFF);
1887
1888				/* prepare next frame and assign timestamp */
1889				next_frame = video->frames[ (frame+1) % video->n_frames ];
1890
1891				if (next_frame->state == FRAME_READY) {
1892					irq_printk("  MIDDLE - next frame is ready, good\n");
1893				} else {
1894					debug_printk("dv1394: Underflow! At least one frame has been dropped.\n");
1895					next_frame = f;
1896				}
1897
1898				/* set the timestamp to the timestamp of the last frame sent,
1899				   plus the length of the last frame sent, plus the syt latency */
1900				ts_cyc = begin_ts & 0xF;
1901				/* advance one frame, plus syt latency (typically 2-3) */
1902				ts_cyc += f->n_packets + video->syt_offset ;
1903
1904				ts_off = 0;
1905
1906				ts_cyc += ts_off/3072;
1907				ts_off %= 3072;
1908
1909				next_frame->assigned_timestamp = ((ts_cyc&0xF) << 12) + ts_off;
1910				if (next_frame->cip_syt1) {
1911					next_frame->cip_syt1->b[6] = next_frame->assigned_timestamp >> 8;
1912					next_frame->cip_syt1->b[7] = next_frame->assigned_timestamp & 0xFF;
1913				}
1914				if (next_frame->cip_syt2) {
1915					next_frame->cip_syt2->b[6] = next_frame->assigned_timestamp >> 8;
1916					next_frame->cip_syt2->b[7] = next_frame->assigned_timestamp & 0xFF;
1917				}
1918
1919			}
1920
1921			/* see if the frame looped */
1922			if ( *(f->frame_end_timestamp) ) {
1923
1924				*(f->frame_end_timestamp) = 0;
1925
1926				debug_printk("  END - the frame looped at least once\n");
1927
1928				video->dropped_frames++;
1929			}
1930
1931		} /* for (each frame) */
1932	}
1933
1934	if (wake) {
1935		kill_fasync(&video->fasync, SIGIO, POLL_OUT);
1936
1937		/* wake readers/writers/ioctl'ers */
1938		wake_up_interruptible(&video->waitq);
1939	}
1940
1941out:
1942	spin_unlock(&video->spinlock);
1943}
1944
1945static void ir_tasklet_func(unsigned long data)
1946{
1947	int wake = 0;
1948	struct video_card *video = (struct video_card*) data;
1949
1950	spin_lock(&video->spinlock);
1951
1952	if (!video->dma_running)
1953		goto out;
1954
1955	if ( (video->ohci_ir_ctx != -1) &&
1956	    (reg_read(video->ohci, video->ohci_IsoRcvContextControlSet) & (1 << 10)) ) {
1957
1958		int sof=0; /* start-of-frame flag */
1959		struct frame *f;
1960		u16 packet_length;
1961		int i, dbc=0;
1962		struct DMA_descriptor_block *block = NULL;
1963		u16 xferstatus;
1964
1965		int next_i, prev_i;
1966		struct DMA_descriptor_block *next = NULL;
1967		dma_addr_t next_dma = 0;
1968		struct DMA_descriptor_block *prev = NULL;
1969
1970		/* loop over all descriptors in all frames */
1971		for (i = 0; i < video->n_frames*MAX_PACKETS; i++) {
1972			struct packet *p = dma_region_i(&video->packet_buf, struct packet, video->current_packet);
1973
1974			/* make sure we are seeing the latest changes to p */
1975			dma_region_sync_for_cpu(&video->packet_buf,
1976						(unsigned long) p - (unsigned long) video->packet_buf.kvirt,
1977						sizeof(struct packet));
1978
1979			packet_length = le16_to_cpu(p->data_length);
1980
1981			/* get the descriptor based on packet_buffer cursor */
1982			f = video->frames[video->current_packet / MAX_PACKETS];
1983			block = &(f->descriptor_pool[video->current_packet % MAX_PACKETS]);
1984			xferstatus = le32_to_cpu(block->u.in.il.q[3]) >> 16;
1985			xferstatus &= 0x1F;
1986			irq_printk("ir_tasklet_func: xferStatus/resCount [%d] = 0x%08x\n", i, le32_to_cpu(block->u.in.il.q[3]) );
1987
1988			/* get the current frame */
1989			f = video->frames[video->active_frame];
1990
1991			/* exclude empty packet */
1992			if (packet_length > 8 && xferstatus == 0x11) {
1993				/* check for start of frame */
1994				/* DRD> Changed to check section type ([0]>>5==0)
1995				   and dif sequence ([1]>>4==0) */
1996				sof = ( (p->data[0] >> 5) == 0 && (p->data[1] >> 4) == 0);
1997
1998				dbc = (int) (p->cip_h1 >> 24);
1999				if ( video->continuity_counter != -1 && dbc > ((video->continuity_counter + 1) % 256) )
2000				{
2001					printk(KERN_WARNING "dv1394: discontinuity detected, dropping all frames\n" );
2002					video->dropped_frames += video->n_clear_frames + 1;
2003					video->first_frame = 0;
2004					video->n_clear_frames = 0;
2005					video->first_clear_frame = -1;
2006				}
2007				video->continuity_counter = dbc;
2008
2009				if (!video->first_frame) {
2010					if (sof) {
2011						video->first_frame = 1;
2012					}
2013
2014				} else if (sof) {
2015					/* close current frame */
2016					frame_reset(f);  /* f->state = STATE_CLEAR */
2017					video->n_clear_frames++;
2018					if (video->n_clear_frames > video->n_frames) {
2019						video->dropped_frames++;
2020						printk(KERN_WARNING "dv1394: dropped a frame during reception\n" );
2021						video->n_clear_frames = video->n_frames-1;
2022						video->first_clear_frame = (video->first_clear_frame + 1) % video->n_frames;
2023					}
2024					if (video->first_clear_frame == -1)
2025						video->first_clear_frame = video->active_frame;
2026
2027					/* get the next frame */
2028					video->active_frame = (video->active_frame + 1) % video->n_frames;
2029					f = video->frames[video->active_frame];
2030					irq_printk("   frame received, active_frame = %d, n_clear_frames = %d, first_clear_frame = %d\n",
2031						   video->active_frame, video->n_clear_frames, video->first_clear_frame);
2032				}
2033				if (video->first_frame) {
2034					if (sof) {
2035						/* open next frame */
2036						f->state = FRAME_READY;
2037					}
2038
2039					/* copy to buffer */
2040					if (f->n_packets > (video->frame_size / 480)) {
2041						printk(KERN_ERR "frame buffer overflow during receive\n");
2042					}
2043
2044					frame_put_packet(f, p);
2045
2046				} /* first_frame */
2047			}
2048
2049			/* stop, end of ready packets */
2050			else if (xferstatus == 0) {
2051				break;
2052			}
2053
2054			/* reset xferStatus & resCount */
2055			block->u.in.il.q[3] = cpu_to_le32(512);
2056
2057			/* terminate dma chain at this (next) packet */
2058			next_i = video->current_packet;
2059			f = video->frames[next_i / MAX_PACKETS];
2060			next = &(f->descriptor_pool[next_i % MAX_PACKETS]);
2061			next_dma = ((unsigned long) block - (unsigned long) f->descriptor_pool) + f->descriptor_pool_dma;
2062			next->u.in.il.q[0] |= cpu_to_le32(3 << 20); /* enable interrupt */
2063			next->u.in.il.q[2] = cpu_to_le32(0); /* disable branch */
2064
2065			/* link previous to next */
2066			prev_i = (next_i == 0) ? (MAX_PACKETS * video->n_frames - 1) : (next_i - 1);
2067			f = video->frames[prev_i / MAX_PACKETS];
2068			prev = &(f->descriptor_pool[prev_i % MAX_PACKETS]);
2069			if (prev_i % (MAX_PACKETS/2)) {
2070				prev->u.in.il.q[0] &= ~cpu_to_le32(3 << 20); /* no interrupt */
2071			} else {
2072				prev->u.in.il.q[0] |= cpu_to_le32(3 << 20); /* enable interrupt */
2073			}
2074			prev->u.in.il.q[2] = cpu_to_le32(next_dma | 1); /* set Z=1 */
2075			wmb();
2076
2077			/* wake up DMA in case it fell asleep */
2078			reg_write(video->ohci, video->ohci_IsoRcvContextControlSet, (1 << 12));
2079
2080			/* advance packet_buffer cursor */
2081			video->current_packet = (video->current_packet + 1) % (MAX_PACKETS * video->n_frames);
2082
2083		} /* for all packets */
2084
2085		wake = 1; /* why the hell not? */
2086
2087	} /* receive interrupt */
2088
2089	if (wake) {
2090		kill_fasync(&video->fasync, SIGIO, POLL_IN);
2091
2092		/* wake readers/writers/ioctl'ers */
2093		wake_up_interruptible(&video->waitq);
2094	}
2095
2096out:
2097	spin_unlock(&video->spinlock);
2098}
2099
2100static struct cdev dv1394_cdev;
2101static const struct file_operations dv1394_fops=
2102{
2103	.owner =	THIS_MODULE,
2104	.poll =		dv1394_poll,
2105	.unlocked_ioctl = dv1394_ioctl,
2106#ifdef CONFIG_COMPAT
2107	.compat_ioctl = dv1394_compat_ioctl,
2108#endif
2109	.mmap =		dv1394_mmap,
2110	.open =		dv1394_open,
2111	.write =	dv1394_write,
2112	.read =		dv1394_read,
2113	.release =	dv1394_release,
2114	.fasync =	dv1394_fasync,
2115	.llseek =	no_llseek,
2116};
2117
2118
2119/*** HOTPLUG STUFF **********************************************************/
2120/*
2121 * Export information about protocols/devices supported by this driver.
2122 */
2123#ifdef MODULE
2124static const 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#endif /* MODULE */
2135
2136static struct hpsb_protocol_driver dv1394_driver = {
2137	.name = "dv1394",
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		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	device_create(hpsb_protocol_class, NULL,
2253		      MKDEV(IEEE1394_MAJOR,
2254			    IEEE1394_MINOR_BLOCK_DV1394 * 16 + (id<<2)),
2255		      NULL, "dv1394-%d", id);
2256
2257	dv1394_init(ohci, DV1394_NTSC, MODE_RECEIVE);
2258	dv1394_init(ohci, DV1394_NTSC, MODE_TRANSMIT);
2259	dv1394_init(ohci, DV1394_PAL, MODE_RECEIVE);
2260	dv1394_init(ohci, DV1394_PAL, MODE_TRANSMIT);
2261}
2262
2263
2264/* Bus reset handler. In the event of a bus reset, we may need to
2265   re-start the DMA contexts - otherwise the user program would
2266   end up waiting forever.
2267*/
2268
2269static void dv1394_host_reset(struct hpsb_host *host)
2270{
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	/* find the corresponding video_cards */
2279	spin_lock_irqsave(&dv1394_cards_lock, flags);
2280	list_for_each_entry(tmp_vid, &dv1394_cards, list) {
2281		if ((tmp_vid->id >> 2) == host->id) {
2282			video = tmp_vid;
2283			break;
2284		}
2285	}
2286	spin_unlock_irqrestore(&dv1394_cards_lock, flags);
2287
2288	if (!video)
2289		return;
2290
2291
2292	spin_lock_irqsave(&video->spinlock, flags);
2293
2294	if (!video->dma_running)
2295		goto out;
2296
2297	/* check IT context */
2298	if (video->ohci_it_ctx != -1) {
2299		u32 ctx;
2300
2301		ctx = reg_read(video->ohci, video->ohci_IsoXmitContextControlSet);
2302
2303		/* if (RUN but not ACTIVE) */
2304		if ( (ctx & (1<<15)) &&
2305		    !(ctx & (1<<10)) ) {
2306
2307			debug_printk("dv1394: IT context stopped due to bus reset; waking it up\n");
2308
2309			/* to be safe, assume a frame has been dropped. User-space programs
2310			   should handle this condition like an underflow. */
2311			video->dropped_frames++;
2312
2313			/* for some reason you must clear, then re-set the RUN bit to restart DMA */
2314
2315			/* clear RUN */
2316			reg_write(video->ohci, video->ohci_IsoXmitContextControlClear, (1 << 15));
2317			flush_pci_write(video->ohci);
2318
2319			/* set RUN */
2320			reg_write(video->ohci, video->ohci_IsoXmitContextControlSet, (1 << 15));
2321			flush_pci_write(video->ohci);
2322
2323			/* set the WAKE bit (just in case; this isn't strictly necessary) */
2324			reg_write(video->ohci, video->ohci_IsoXmitContextControlSet, (1 << 12));
2325			flush_pci_write(video->ohci);
2326
2327			irq_printk("dv1394: AFTER IT restart ctx 0x%08x ptr 0x%08x\n",
2328				   reg_read(video->ohci, video->ohci_IsoXmitContextControlSet),
2329				   reg_read(video->ohci, video->ohci_IsoXmitCommandPtr));
2330		}
2331	}
2332
2333	/* check IR context */
2334	if (video->ohci_ir_ctx != -1) {
2335		u32 ctx;
2336
2337		ctx = reg_read(video->ohci, video->ohci_IsoRcvContextControlSet);
2338
2339		/* if (RUN but not ACTIVE) */
2340		if ( (ctx & (1<<15)) &&
2341		    !(ctx & (1<<10)) ) {
2342
2343			debug_printk("dv1394: IR context stopped due to bus reset; waking it up\n");
2344
2345			/* to be safe, assume a frame has been dropped. User-space programs
2346			   should handle this condition like an overflow. */
2347			video->dropped_frames++;
2348
2349			/* for some reason you must clear, then re-set the RUN bit to restart DMA */
2350
2351			/* clear RUN */
2352			reg_write(video->ohci, video->ohci_IsoRcvContextControlClear, (1 << 15));
2353			flush_pci_write(video->ohci);
2354
2355			/* set RUN */
2356			reg_write(video->ohci, video->ohci_IsoRcvContextControlSet, (1 << 15));
2357			flush_pci_write(video->ohci);
2358
2359			/* set the WAKE bit (just in case; this isn't strictly necessary) */
2360			reg_write(video->ohci, video->ohci_IsoRcvContextControlSet, (1 << 12));
2361			flush_pci_write(video->ohci);
2362
2363			irq_printk("dv1394: AFTER IR restart ctx 0x%08x ptr 0x%08x\n",
2364				   reg_read(video->ohci, video->ohci_IsoRcvContextControlSet),
2365				   reg_read(video->ohci, video->ohci_IsoRcvCommandPtr));
2366		}
2367	}
2368
2369out:
2370	spin_unlock_irqrestore(&video->spinlock, flags);
2371
2372	/* wake readers/writers/ioctl'ers */
2373	wake_up_interruptible(&video->waitq);
2374}
2375
2376static struct hpsb_highlevel dv1394_highlevel = {
2377	.name =		"dv1394",
2378	.add_host =	dv1394_add_host,
2379	.remove_host =	dv1394_remove_host,
2380	.host_reset =   dv1394_host_reset,
2381};
2382
2383#ifdef CONFIG_COMPAT
2384
2385#define DV1394_IOC32_INIT       _IOW('#', 0x06, struct dv1394_init32)
2386#define DV1394_IOC32_GET_STATUS _IOR('#', 0x0c, struct dv1394_status32)
2387
2388struct dv1394_init32 {
2389	u32 api_version;
2390	u32 channel;
2391	u32 n_frames;
2392	u32 format;
2393	u32 cip_n;
2394	u32 cip_d;
2395	u32 syt_offset;
2396};
2397
2398struct dv1394_status32 {
2399	struct dv1394_init32 init;
2400	s32 active_frame;
2401	u32 first_clear_frame;
2402	u32 n_clear_frames;
2403	u32 dropped_frames;
2404};
2405
2406/* RED-PEN: this should use compat_alloc_userspace instead */
2407
2408static int handle_dv1394_init(struct file *file, unsigned int cmd, unsigned long arg)
2409{
2410	struct dv1394_init32 dv32;
2411	struct dv1394_init dv;
2412	mm_segment_t old_fs;
2413	int ret;
2414
2415	if (file->f_op->unlocked_ioctl != dv1394_ioctl)
2416		return -EFAULT;
2417
2418	if (copy_from_user(&dv32, (void __user *)arg, sizeof(dv32)))
2419		return -EFAULT;
2420
2421	dv.api_version = dv32.api_version;
2422	dv.channel = dv32.channel;
2423	dv.n_frames = dv32.n_frames;
2424	dv.format = dv32.format;
2425	dv.cip_n = (unsigned long)dv32.cip_n;
2426	dv.cip_d = (unsigned long)dv32.cip_d;
2427	dv.syt_offset = dv32.syt_offset;
2428
2429	old_fs = get_fs();
2430	set_fs(KERNEL_DS);
2431	ret = dv1394_ioctl(file, DV1394_IOC_INIT, (unsigned long)&dv);
2432	set_fs(old_fs);
2433
2434	return ret;
2435}
2436
2437static int handle_dv1394_get_status(struct file *file, unsigned int cmd, unsigned long arg)
2438{
2439	struct dv1394_status32 dv32;
2440	struct dv1394_status dv;
2441	mm_segment_t old_fs;
2442	int ret;
2443
2444	if (file->f_op->unlocked_ioctl != dv1394_ioctl)
2445		return -EFAULT;
2446
2447	old_fs = get_fs();
2448	set_fs(KERNEL_DS);
2449	ret = dv1394_ioctl(file, DV1394_IOC_GET_STATUS, (unsigned long)&dv);
2450	set_fs(old_fs);
2451
2452	if (!ret) {
2453		dv32.init.api_version = dv.init.api_version;
2454		dv32.init.channel = dv.init.channel;
2455		dv32.init.n_frames = dv.init.n_frames;
2456		dv32.init.format = dv.init.format;
2457		dv32.init.cip_n = (u32)dv.init.cip_n;
2458		dv32.init.cip_d = (u32)dv.init.cip_d;
2459		dv32.init.syt_offset = dv.init.syt_offset;
2460		dv32.active_frame = dv.active_frame;
2461		dv32.first_clear_frame = dv.first_clear_frame;
2462		dv32.n_clear_frames = dv.n_clear_frames;
2463		dv32.dropped_frames = dv.dropped_frames;
2464
2465		if (copy_to_user((struct dv1394_status32 __user *)arg, &dv32, sizeof(dv32)))
2466			ret = -EFAULT;
2467	}
2468
2469	return ret;
2470}
2471
2472
2473
2474static long dv1394_compat_ioctl(struct file *file, unsigned int cmd,
2475			       unsigned long arg)
2476{
2477	switch (cmd) {
2478	case DV1394_IOC_SHUTDOWN:
2479	case DV1394_IOC_SUBMIT_FRAMES:
2480	case DV1394_IOC_WAIT_FRAMES:
2481	case DV1394_IOC_RECEIVE_FRAMES:
2482	case DV1394_IOC_START_RECEIVE:
2483		return dv1394_ioctl(file, cmd, arg);
2484
2485	case DV1394_IOC32_INIT:
2486		return handle_dv1394_init(file, cmd, arg);
2487	case DV1394_IOC32_GET_STATUS:
2488		return handle_dv1394_get_status(file, cmd, arg);
2489	default:
2490		return -ENOIOCTLCMD;
2491	}
2492}
2493
2494#endif /* CONFIG_COMPAT */
2495
2496
2497/*** KERNEL MODULE HANDLERS ************************************************/
2498
2499MODULE_AUTHOR("Dan Maas <dmaas@dcine.com>, Dan Dennedy <dan@dennedy.org>");
2500MODULE_DESCRIPTION("driver for DV input/output on OHCI board");
2501MODULE_SUPPORTED_DEVICE("dv1394");
2502MODULE_LICENSE("GPL");
2503
2504static void __exit dv1394_exit_module(void)
2505{
2506	hpsb_unregister_protocol(&dv1394_driver);
2507	hpsb_unregister_highlevel(&dv1394_highlevel);
2508	cdev_del(&dv1394_cdev);
2509}
2510
2511static int __init dv1394_init_module(void)
2512{
2513	int ret;
2514
2515	cdev_init(&dv1394_cdev, &dv1394_fops);
2516	dv1394_cdev.owner = THIS_MODULE;
2517	ret = cdev_add(&dv1394_cdev, IEEE1394_DV1394_DEV, 16);
2518	if (ret) {
2519		printk(KERN_ERR "dv1394: unable to register character device\n");
2520		return ret;
2521	}
2522
2523	hpsb_register_highlevel(&dv1394_highlevel);
2524
2525	ret = hpsb_register_protocol(&dv1394_driver);
2526	if (ret) {
2527		printk(KERN_ERR "dv1394: failed to register protocol\n");
2528		hpsb_unregister_highlevel(&dv1394_highlevel);
2529		cdev_del(&dv1394_cdev);
2530		return ret;
2531	}
2532
2533	return 0;
2534}
2535
2536module_init(dv1394_init_module);
2537module_exit(dv1394_exit_module);
2538