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