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