Subversion Repositories Projects

Rev

Rev 298 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
244 dhylands 1
/****************************************************************************
2
*
3
*   Copyright (c) 2006 Dave Hylands     <dhylands@gmail.com>
4
*
5
*   This program is free software; you can redistribute it and/or modify
6
*   it under the terms of the GNU General Public License version 2 as
7
*   published by the Free Software Foundation.
8
*
9
*   Alternatively, this software may be distributed under the terms of BSD
10
*   license.
11
*
12
*   See README and COPYING for more details.
13
*
14
****************************************************************************
15
*
16
*   This driver allows multiple GPIO pins to be monitored and allows a user
17
*   mode program to be notified when the pin changes.
18
*
19
****************************************************************************/
20
 
21
/* ---- Include Files ---------------------------------------------------- */
22
 
23
#include <linux/module.h>
24
#include <linux/init.h>
25
#include <linux/list.h>
26
#include <linux/fs.h>
27
#include <linux/spinlock.h>
28
#include <linux/proc_fs.h>
29
#include <linux/sysctl.h>
30
#include <linux/poll.h>
31
#include <linux/interrupt.h>
32
#include <linux/device.h>
33
#include <linux/cdev.h>
34
#include <linux/seq_file.h>
35
#include <linux/spinlock.h>
36
#include <linux/version.h>
37
#include <linux/sched.h>
268 dhylands 38
#include <linux/slab.h>
269 dhylands 39
#include <linux/version.h>
244 dhylands 40
 
41
#include <asm/uaccess.h>
42
#include <asm/ioctls.h>
43
 
320 dhylands 44
#include <linux/gpio.h>
244 dhylands 45
 
46
#include "gpio-event-drv.h"
47
 
48
/* ---- Public Variables ------------------------------------------------- */
49
/* ---- Private Constants and Types -------------------------------------- */
50
 
51
#define GPIO_EVENT_DEV_NAME "gpio-event"
52
 
53
#define DEBUG_ENABLED   1
54
 
55
#if DEBUG_ENABLED
56
#   define DEBUG( flag, fmt, args... ) do { if ( gDebug ## flag ) printk( "%s: " fmt, __FUNCTION__ , ## args ); } while (0)
57
#else
58
#   define DEBUG( flag, fmt, args... )
59
#endif  
60
 
61
/* ---- Private Variables ------------------------------------------------ */
62
 
63
static char gBanner[] __initdata = KERN_INFO "GPIO Event Monitor 0.1 Compiled: " __DATE__ " at " __TIME__ "\n";
64
 
65
static  int         gDebugTrace = 0;
66
static  int         gDebugIoctl = 0;
67
static  int         gDebugError = 1;
68
static  int         gLostEvents = 0;
69
 
70
static  struct ctl_table_header    *gSysCtlHeader;
71
 
269 dhylands 72
#if ( LINUX_VERSION_CODE >= KERNEL_VERSION( 2, 6, 33 ))
73
#define CTL_NAME(x)
74
#else
75
#define CTL_NAME(x)     .ctl_name = x,
76
#endif
77
 
244 dhylands 78
static struct ctl_table gSysCtlSample[] =
79
{
80
    {
269 dhylands 81
        CTL_NAME(1)
244 dhylands 82
        .procname       = "lost-events",
83
        .data           = &gLostEvents,
84
        .maxlen         = sizeof( int ),
85
        .mode           = 0644,
86
        .proc_handler   = &proc_dointvec
87
    },
88
    {
269 dhylands 89
        CTL_NAME(101)
244 dhylands 90
        .procname       = "debug-trace",
91
        .data           = &gDebugTrace,
92
        .maxlen         = sizeof( int ),
93
        .mode           = 0644,
94
        .proc_handler   = &proc_dointvec
95
    },
96
    {
269 dhylands 97
        CTL_NAME(102)
244 dhylands 98
        .procname       = "debug-ioctl",
99
        .data           = &gDebugIoctl,
100
        .maxlen         = sizeof( int ),
101
        .mode           = 0644,
102
        .proc_handler   = &proc_dointvec
103
    },
104
    {
269 dhylands 105
        CTL_NAME(103)
244 dhylands 106
        .procname       = "debug-error",
107
        .data           = &gDebugError,
108
        .maxlen         = sizeof( int ),
109
        .mode           = 0644,
110
        .proc_handler   = &proc_dointvec
111
    },
112
    { 0 }
113
};
114
 
115
static struct ctl_table gSysCtl[] =
116
{
117
    {
269 dhylands 118
        CTL_NAME(CTL_GPIO_EVENT)
244 dhylands 119
        .procname       = "gpio-event",
120
        .mode           = 0555,
121
        .child          = gSysCtlSample
122
    },
123
    { 0 }
124
};
125
 
126
/*
127
 * An instance of GPIO_FileData_t is maintained for file open
128
 */
129
 
130
#define GPIO_EVENT_QUEUE_LEN    20
131
 
132
// GPIO_EVENT_BUFFER_SIZE needs to be big enough to hold the ASCII version
133
// of the GPIO_Event_t as well as the binary version of the GPIO_Event_t
134
 
135
#define GPIO_EVENT_BUFFER_SIZE  32
136
 
137
typedef struct
138
{
139
    struct list_head        list;
140
    wait_queue_head_t       waitQueue;
141
 
142
    spinlock_t              queueLock;
143
    GPIO_Event_t            queueData[ GPIO_EVENT_QUEUE_LEN ];
144
    volatile int            getIndex;
145
    volatile int            putIndex;
146
    volatile int            numEvents;
147
 
148
    GPIO_EventReadMode_t    readMode;
149
 
150
    char                    buffer[ GPIO_EVENT_BUFFER_SIZE ];
151
    int                     bufBytes;
152
 
153
} GPIO_FileData_t;
154
 
155
/*
156
 * An instance of GPIO_PinData_t is maintained for each GPIO line which is
157
 * monitored,
158
 */
159
 
160
typedef enum
161
{
162
    PIN_LOW             = 0,    // Matches level of GPIO line
163
    PIN_HIGH            = 1,
164
    PIN_BOUNCING_LOW,
165
    PIN_BOUNCING_HIGH,
166
} PinState_t;
167
 
168
typedef struct
169
{
170
    struct  list_head       list;               // list of all pins
171
 
172
    int                     gpio;               // The gpio line being monitored
173
 
174
    // We maintain two lists, a global list of pins, and a list associated with each open
175
 
176
 
177
    struct  timer_list      debounceTimer;      // Timer to wake u up after an edge
178
    uint8_t                 debounceMilliSec;   // debounce time in milliseconds
179
    char                    devName[ 16 ];      // gpio xx event
180
 
181
    GPIO_EventEdgeType_t    edgeType;   // Type of edge(s) we're looking for.
182
 
183
    PinState_t              pinState;          // Was the GPIO line low or high?
184
 
185
} GPIO_PinData_t;
186
 
187
static  volatile    int     gReportLostEvents = 1;
188
 
189
static  struct class       *gGpioEventClass = NULL;
190
static  struct  cdev        gGpioEventCDev;
191
static  dev_t               gGpioEventDevNum = 0;
192
 
292 dhylands 193
static  DEFINE_SPINLOCK( gFileListLock );
194
static  DEFINE_SPINLOCK( gPinListLock );
244 dhylands 195
 
196
static  LIST_HEAD( gFileList );
197
static  LIST_HEAD( gPinList );
198
 
199
static struct proc_dir_entry *gProcGpioEvent;
200
static struct proc_dir_entry *gProcPins;
201
 
202
 
203
/* ---- Private Function Prototypes -------------------------------------- */
204
/* ---- Functions -------------------------------------------------------- */
205
 
206
typedef struct
207
{
208
    unsigned    long    flags;
209
    struct list_head   *list;
210
 
211
} pin_seq_t;
212
 
213
/****************************************************************************
214
*
215
*  pin_seq_start
216
*
217
*   seq_file iterator which goes through the pins being monitored
218
*
219
****************************************************************************/
220
 
221
static void *pin_seq_start( struct seq_file *s, loff_t *pos )
222
{
223
    pin_seq_t  *ps;
224
    loff_t      i;
225
 
226
    s->private = NULL;
227
 
228
    if (( ps = kcalloc( 1, sizeof( pin_seq_t ), GFP_KERNEL )) == NULL )
229
    {
230
        return ERR_PTR( -ENOMEM );
231
    }
232
    s->private = ps;
233
 
234
    spin_lock_irqsave( &gPinListLock, ps->flags );
235
 
236
    if ( list_empty( &gPinList ))
237
    {
238
        DEBUG( Trace, "list_empty\n" );
239
        return NULL;
240
    }
241
    ps->list = gPinList.next;
242
 
243
    for ( i = 0; i < *pos; i++ )
244
    {
245
        if ( list_is_last( ps->list, &gPinList ))
246
        {
247
            DEBUG( Trace, "No item @ %llu\n", i + 1 );
248
            return NULL;
249
        }
250
        ps->list = ps->list->next;
251
    }
252
 
253
 
254
    DEBUG( Trace, "ps->list = 0x%08lx, *pos = %llu\n", (long)ps->list, *pos );
255
 
256
    return ps->list;
257
 
258
} // pin_seq_start
259
 
260
/****************************************************************************
261
*
262
*  pin_seq_show
263
*
264
*   seq_file iterator which goes through the pins being monitored
265
*
266
****************************************************************************/
267
 
268
static int pin_seq_show( struct seq_file *s, void *v )
269
{
270
    GPIO_PinData_t *pin = list_entry( v, GPIO_PinData_t, list );
271
    char           *edgeTypeStr;
272
 
273
    DEBUG( Trace, "v = 0x%08lx\n", (long)v );
274
 
275
    switch ( pin->edgeType )
276
    {
277
        case GPIO_EventRisingEdge:  edgeTypeStr = "Rising ";    break;
278
        case GPIO_EventFallingEdge: edgeTypeStr = "Falling";    break;
279
        case GPIO_EventBothEdges:   edgeTypeStr = "Both   ";    break;
280
        default:                    edgeTypeStr = "Unknown";    break;
281
    }
282
 
283
    seq_printf( s, "GPIO: %3d Edge: %s Debounce: %d msec\n", pin->gpio, edgeTypeStr, pin->debounceMilliSec );
284
 
285
    return 0;
286
 
287
} // pin_seq_show
288
 
289
/****************************************************************************
290
*
291
*  pin_seq_next
292
*
293
*   seq_file iterator which goes through the pins being monitored
294
*
295
****************************************************************************/
296
 
297
static void *pin_seq_next( struct seq_file *s, void *v, loff_t *pos )
298
{
299
    pin_seq_t  *ps = s->private;
300
 
301
    DEBUG( Trace, "v = 0x%08lx *pos = %llu\n", (long)v, *pos );
302
 
303
    if ( list_is_last( ps->list, &gPinList ))
304
    {
305
        DEBUG( Trace, "ps->list = 0x%08lx (end of list)\n", (long)ps->list );
306
 
307
        return NULL;
308
    }
309
    (*pos)++;
310
    ps->list = ps->list->next;
311
 
312
    DEBUG( Trace, "ps->list = 0x%08lx\n", (long)ps->list );
313
 
314
    return ps->list;
315
 
316
} // pin_seq_next
317
 
318
/****************************************************************************
319
*
320
*  pin_seq_stop
321
*
322
*   seq_file iterator which goes through the pins being monitored
323
*
324
****************************************************************************/
325
 
326
static void pin_seq_stop( struct seq_file *s, void *v )
327
{
328
    pin_seq_t  *ps = s->private;
329
 
330
    DEBUG( Trace, "v = 0x%08lx\n", (long)v );
331
 
332
    if ( ps != NULL )
333
    {
334
        spin_unlock_irqrestore( &gPinListLock, ps->flags );
335
        kfree( ps );
336
    }
337
 
338
} // pin_seq_stop
339
 
340
/****************************************************************************
341
*
342
*  pin_seq_ops
343
*
344
*   Ties all of the pin_seq_xxx routines together.
345
*
346
****************************************************************************/
347
 
348
static struct seq_operations pin_seq_ops =
349
{
350
        .start = pin_seq_start,
351
        .next  = pin_seq_next,
352
        .stop  = pin_seq_stop,
353
        .show  = pin_seq_show
354
};
355
 
356
/****************************************************************************
357
*
358
*  pins_proc_open
359
*
360
*   Open method for /proc/gpio-event/pin
361
*
362
****************************************************************************/
363
 
364
static int pins_proc_open( struct inode *inode, struct file *file )
365
{
366
    DEBUG( Trace, "called\n" );
367
 
368
    return seq_open( file, &pin_seq_ops );
369
}
370
 
371
/****************************************************************************
372
*
373
*  pin_proc_ops
374
*
375
*   File operations for our /proc/gpio-event/pins file
376
*
377
****************************************************************************/
378
 
379
static struct file_operations pins_proc_ops =
380
{
381
        .owner   = THIS_MODULE,
382
        .open    = pins_proc_open,
383
        .read    = seq_read,
384
        .llseek  = seq_lseek,
385
        .release = seq_release
386
};
387
 
388
 
389
 
390
/****************************************************************************
391
*
392
*  find_pin
393
*
394
*   Searches the list to see if 'gpio' is currently being monitored.
395
*
396
****************************************************************************/
397
 
398
static GPIO_PinData_t *find_pin( int gpio )
399
{
400
    struct  list_head   *pin;
401
 
402
    assert_spin_locked( &gPinListLock );
403
 
404
    list_for_each( pin, &gPinList )
405
    {
406
        GPIO_PinData_t *pinData = list_entry( pin, GPIO_PinData_t, list );
407
 
408
        if ( pinData->gpio == gpio )
409
        {
410
            return pinData;
411
        }
412
    }
413
 
414
    return NULL;
415
 
416
} // find_pin
417
 
418
/****************************************************************************
419
*
420
*  gpio_event_queue_event
421
*
422
*   Queues an sample event from the bottom half to the top half. This
423
*   function queues up the event on every file that's open.
424
*
425
****************************************************************************/
426
 
427
static void gpio_event_queue_event( const GPIO_Event_t *gpioEvent )
428
{
429
    unsigned long       flags;
430
    struct list_head   *file;
431
 
432
    DEBUG( Trace, "gpio %d:%c@%ld.%06ld\n",
433
           gpioEvent->gpio,
434
           gpioEvent->edgeType == GPIO_EventRisingEdge ? 'R' : 'F',
435
           gpioEvent->time.tv_sec,
436
           gpioEvent->time.tv_usec );
437
 
438
    // Queue up the event on all of the open files
439
    //
440
    // This function is only called from the ISR, with interrupts already
441
    // disabled.
442
 
443
    spin_lock_irqsave( &gFileListLock, flags );
444
 
445
    list_for_each( file, &gFileList )
446
    {
447
        GPIO_FileData_t *fileData = list_entry( file, GPIO_FileData_t, list );
448
 
449
        spin_lock( &fileData->queueLock );
450
        {
451
            if ( fileData->numEvents >= GPIO_EVENT_QUEUE_LEN )
452
            {
453
                // Queue is full - Only report first event lost
454
 
455
                if ( gReportLostEvents )
456
                {
457
                    printk( KERN_ERR "GPIO Event: event lost due to queue full\n" );
458
                    gReportLostEvents = 0;
459
                }
460
                gLostEvents++;
461
            }
462
            else
463
            {
464
                fileData->queueData[ fileData->putIndex++ ] = *gpioEvent;
465
                if ( fileData->putIndex >= GPIO_EVENT_QUEUE_LEN )
466
                {
467
                    fileData->putIndex = 0;
468
                }
469
                fileData->numEvents++;
470
            }
471
        }
472
        spin_unlock( &fileData->queueLock );
473
 
474
        wake_up_interruptible( &fileData->waitQueue );
475
    }
476
    spin_unlock_irqrestore( &gFileListLock, flags );
477
 
478
} // gpio_event_queue_event
479
 
480
/****************************************************************************
481
*
482
*  gpio_event_dequeue_event
483
*
484
*   Removes an event from the queue
485
*
486
****************************************************************************/
487
 
488
static int gpio_event_dequeue_event( GPIO_FileData_t *fileData, GPIO_Event_t *gpioEvent )
489
{
490
    unsigned long   flags;
491
    int             eventAvailable = 0;
492
 
493
    spin_lock_irqsave( &fileData->queueLock, flags );
494
    {
495
        if ( fileData->numEvents > 0 )
496
        {
497
            *gpioEvent = fileData->queueData[ fileData->getIndex++ ];
498
            if ( fileData->getIndex >= GPIO_EVENT_QUEUE_LEN )
499
            {
500
                fileData->getIndex = 0;
501
            }
502
            fileData->numEvents--;
503
 
504
            eventAvailable = 1;
505
 
506
            if ( fileData->numEvents == 0 )
507
            {
508
                // Since somebody is reading the queue now, indicate that we
509
                // can report lost events again
510
 
511
                gReportLostEvents = 1;
512
            }
513
        }
514
    }
515
    spin_unlock_irqrestore( &fileData->queueLock, flags );
516
 
517
    DEBUG( Trace, "gpio %d:%c@%ld.%06ld\n",
518
           gpioEvent->gpio,
519
           gpioEvent->edgeType == GPIO_EventRisingEdge ? 'R' : 'F',
520
           gpioEvent->time.tv_sec,
521
           gpioEvent->time.tv_usec );
522
 
523
    return eventAvailable;
524
 
525
} // gpio_event_dequeue_event
526
 
527
/****************************************************************************
528
*
529
*  gpio_event_irq
530
*
531
****************************************************************************/
532
 
533
static irqreturn_t gpio_event_irq( int irq, void *dev_id )
534
{
535
    GPIO_PinData_t         *pinData = (GPIO_PinData_t *)dev_id;
536
    GPIO_Event_t            gpioEvent;
537
    int                     currLevel = gpio_get_value( pinData->gpio );
538
 
539
    // We're called with interrupts disabled.
540
 
541
    (void)irq;
542
 
543
    do_gettimeofday( &gpioEvent.time );
544
    gpioEvent.gpio = pinData->gpio;
545
 
546
    if ( pinData->debounceMilliSec == 0 )
547
    {
548
        // We assume that this is a clean signal
549
 
550
        pinData->pinState = (PinState_t)currLevel;
551
 
552
        if ( pinData->edgeType == GPIO_EventBothEdges )
553
        {
554
            // There's no register to tell which edge just occurred. So we
555
            // assume that it just changed into its current level.
556
 
557
            if ( currLevel )
558
            {
559
                // Pin is currently high, so this must be a rising edge
560
 
561
                gpioEvent.edgeType = GPIO_EventRisingEdge;
562
            }
563
            else
564
            {
565
                // Pin is currently low, so this must be a falling edge
566
 
567
                gpioEvent.edgeType = GPIO_EventFallingEdge;
568
            }
569
        }
570
        else
571
        {
572
            // If we're only monitoring one type of edge, then that's the one
573
            // that happened.
574
 
575
            gpioEvent.edgeType = pinData->edgeType;
576
        }
577
        gpio_event_queue_event( &gpioEvent );
578
    }
579
    else
580
    {
581
        gpioEvent.edgeType = 0;
582
 
583
        // If we need to debounce, then we need to monitor both edges, and
584
        // use the debounce timer to figure out the real state. So we don't
585
        // actually know which edge we just got. We use a state machine
586
        // to track things.
587
 
588
        switch ( pinData->pinState )
589
        {
590
            case PIN_LOW:
591
            {
592
                pinData->pinState = PIN_BOUNCING_HIGH;
593
                gpioEvent.edgeType = GPIO_EventRisingEdge;
594
                break;
595
            }
596
 
597
            case PIN_HIGH:
598
            {
599
                pinData->pinState = PIN_BOUNCING_LOW;
600
                gpioEvent.edgeType = GPIO_EventFallingEdge;
601
                break;
602
            }
603
 
604
            default:
605
            {
606
                break;
607
            }
608
        }
609
 
610
        if (( pinData->edgeType & gpioEvent.edgeType ) != 0 )
611
        {
612
            // This is an edge that the user is interested in - send it along.
613
 
614
            gpio_event_queue_event( &gpioEvent );
615
        }
616
 
617
        // Disable interrupts for our gpio to allow debounce to occur. The 
618
        // timer will re-enable the interrupt.
619
 
620
        disable_irq_nosync( irq );
621
 
622
        // Since we have no idea when in the current jiffy that the edge
623
        // occurred, we add 1 to the calculation to guarantee at least one
624
        // whole jiffy.
625
 
626
        mod_timer( &pinData->debounceTimer, jiffies + msecs_to_jiffies( pinData->debounceMilliSec ) + 1 );
627
    }
628
 
629
    return IRQ_HANDLED;
630
 
631
} // gpio_event_irq
632
 
633
/****************************************************************************
634
*
635
*  gpio_event_timer
636
*
637
****************************************************************************/
638
 
639
void gpio_event_timer( unsigned long data )
640
{
641
    GPIO_PinData_t         *pinData = (GPIO_PinData_t *)data;
642
 
643
    // This function is called when the debounce timer for a gpio expires.
644
    // We record the state of the pin so that we can figure out what the 
645
    // next edge will be.
646
 
647
    pinData->pinState = ( gpio_get_value( pinData->gpio ) != 0 );
648
 
649
    // Turn interrupts back on so we can catch the next edge
650
 
651
    enable_irq( gpio_to_irq( pinData->gpio ));
652
 
653
} // gpio_event_timer
654
 
655
/****************************************************************************
656
*
657
*  gpio_event_monitor
658
*
659
****************************************************************************/
660
 
661
static int gpio_event_monitor( GPIO_EventMonitor_t *monitor )
662
{
663
    int             rc = 0;
664
    unsigned long   flags;
665
    GPIO_PinData_t *pinData;
666
    unsigned long   irqFlags;
667
 
668
    spin_lock_irqsave( &gPinListLock, flags );
669
 
670
    if ( monitor->onOff )
671
    {
672
        // Check to make sure we aren't already monitoring the gpio
673
 
674
        if (( pinData = find_pin( monitor->gpio )) != NULL )
675
        {
676
            // We are already monitoring the pin. Unmonitor the pin and then
677
            // proceed.
678
 
679
            monitor->onOff = 0;
680
 
681
            spin_unlock_irqrestore( &gPinListLock, flags );
682
            gpio_event_monitor( monitor );
683
            spin_lock_irqsave( &gPinListLock, flags );
684
        }
685
 
686
        if (( pinData = kcalloc( 1, sizeof( *pinData ), GFP_KERNEL )) == NULL )
687
        {
688
            DEBUG( Error, "GPIO %d: Out of memory\n", monitor->gpio );
689
            rc = -ENOMEM;
690
            goto out;
691
        }
692
 
693
        INIT_LIST_HEAD( &pinData->list );
694
 
695
        snprintf( pinData->devName, sizeof( pinData->devName ), "gpio %d event", monitor->gpio );
696
 
697
        // Note:
698
        //     Calling request_irq will automatically set the pin to be an input.
699
 
700
        irqFlags = 0;
701
 
702
        if ( monitor->debounceMilliSec == 0 )
703
        {
704
            // A clean signal is being presented, so we can just look for
705
            // a particular edge
706
 
298 dhylands 707
            if (( monitor->edgeType & GPIO_EventRisingEdge ) != 0 )
244 dhylands 708
            {
709
                irqFlags |= IRQF_TRIGGER_RISING;
710
            }
298 dhylands 711
            if (( monitor->edgeType & GPIO_EventFallingEdge ) != 0 )
244 dhylands 712
            {
713
                irqFlags |= IRQF_TRIGGER_FALLING;
714
            }
715
        }
716
        else
717
        {
718
            // Since we need to debounce, we need to look for both types of
719
            // edges, since we get both types of edges whenever a bounce
720
            // happens.
721
 
722
            irqFlags |= IRQF_TRIGGER_RISING;
723
            irqFlags |= IRQF_TRIGGER_FALLING;
724
        }
725
 
726
        if (( rc = request_irq( gpio_to_irq( monitor->gpio ), gpio_event_irq, irqFlags, pinData->devName, pinData )) != 0 )
727
        {
728
            DEBUG( Error, "Unable to register irq for GPIO %d\n", monitor->gpio );
729
            kfree( pinData );
730
            goto out;
731
        }
732
 
733
        pinData->gpio             = monitor->gpio;
734
        pinData->edgeType         = monitor->edgeType;
735
        pinData->debounceMilliSec = monitor->debounceMilliSec;
736
 
737
        init_timer( &pinData->debounceTimer );
738
 
739
        pinData->debounceTimer.data = (unsigned long)pinData;
740
        pinData->debounceTimer.function = gpio_event_timer;
741
 
742
        list_add_tail( &pinData->list, &gPinList );
743
 
744
        if ( gpio_get_value( pinData->gpio ) == 0 )
745
        {
746
            pinData->pinState = PIN_LOW;
747
        }
748
        else
749
        {
750
            pinData->pinState = PIN_HIGH;
751
        }
752
    }
753
    else
754
    {
755
        if (( pinData = find_pin( monitor->gpio )) == NULL )
756
        {
757
            DEBUG( Error, "GPIO %d isn't being monitored\n", monitor->gpio );
758
            rc = -ENXIO;
759
            goto out;
760
        }
761
 
762
        // We've found the gpio being monitored - turn things off.
763
 
764
        free_irq( gpio_to_irq( pinData->gpio ), pinData );
765
 
766
        del_timer_sync( &pinData->debounceTimer );
767
        list_del( &pinData->list );
768
 
769
        kfree( pinData );
770
    }
771
 
772
out:
773
 
774
    spin_unlock_irqrestore( &gPinListLock, flags );
775
 
776
    return rc;
777
 
778
} // gpio_event_monitor
779
 
780
/****************************************************************************
781
*
782
*   gpio_event_ioctl
783
*
784
*   Called to process ioctl requests
785
*
786
*****************************************************************************/
787
 
283 dhylands 788
long gpio_event_ioctl( struct file *file, unsigned int cmd, unsigned long arg )
244 dhylands 789
{
790
    GPIO_FileData_t    *fileData;
791
 
792
    DEBUG( Trace, "type: '%c' cmd: 0x%x\n", _IOC_TYPE( cmd ), _IOC_NR( cmd ));
793
 
794
    fileData = file->private_data;
795
 
796
    switch ( cmd )
797
    {
798
        case GPIO_EVENT_IOCTL_MONITOR_GPIO:
799
        {
800
            GPIO_EventMonitor_t monitor;
801
 
802
            if ( copy_from_user( &monitor, (void *)arg, sizeof( monitor )) != 0 )
803
            {
804
                return -EFAULT;
805
            }
806
            return gpio_event_monitor( &monitor );
807
        }
808
 
809
        case GPIO_EVENT_IOCTL_SET_READ_MODE:
810
        {
811
            fileData->readMode = (GPIO_EventReadMode_t)arg;
812
            break;
813
        }
814
 
815
        case TCGETS:
816
        {
817
            // When cat opens this device, we get this ioctl
818
            return -ENOTTY;
819
        }
820
 
821
        default:
822
        {
823
            DEBUG( Error, "Unrecognized ioctl: '0x%x'\n", cmd );
824
            return -ENOTTY;
825
        }
826
    }
827
 
828
    return 0;
829
 
830
} // gpio_event_ioctl
831
 
832
/****************************************************************************
833
*
834
*  gpio_event_open
835
*
836
****************************************************************************/
837
 
838
static int gpio_event_open( struct inode *inode, struct file *file )
839
{
840
    unsigned long       flags;
841
    GPIO_FileData_t    *fileData;
842
 
843
    DEBUG( Trace, "gpio_event_open called, major = %d, minor = %d\n", MAJOR( inode->i_rdev ),  MINOR( inode->i_rdev ));
844
 
845
    // Allocate a per-open data structure
846
 
847
    if (( fileData = kcalloc( 1, sizeof( *fileData ), GFP_KERNEL )) == NULL )
848
    {
849
        return -ENOMEM;
850
    }
851
 
852
    INIT_LIST_HEAD( &fileData->list );
853
 
854
    init_waitqueue_head( &fileData->waitQueue );
855
 
856
    spin_lock_init( &fileData->queueLock );
857
 
858
    fileData->getIndex = 0;
859
    fileData->putIndex = 0;
860
    fileData->numEvents = 0;
861
    fileData->bufBytes = 0;
862
 
863
    fileData->readMode = GPIO_EventReadModeAscii;
864
 
865
    file->private_data = fileData;
866
 
867
    spin_lock_irqsave( &gFileListLock, flags );
868
    {
869
        list_add_tail( &fileData->list, &gFileList );
870
    }
871
    spin_unlock_irqrestore( &gFileListLock, flags );
872
 
873
    return 0;
874
 
875
} // gpio_event_open
876
 
877
/****************************************************************************
878
*
879
*  gpio_event_read
880
*
881
****************************************************************************/
882
 
883
static ssize_t gpio_event_read( struct file *file, char *buffer, size_t spaceRemaining, loff_t *ppos )
884
{
885
    int                 rc;
886
    ssize_t             bytesCopied = 0;
887
    ssize_t             bytesToCopy;
888
    GPIO_FileData_t    *fileData = file->private_data;
889
 
890
    DEBUG( Trace, "gpio_event_read called, major = %d, minor = %d\n", MAJOR( file->f_dentry->d_inode->i_rdev ), MINOR( file->f_dentry->d_inode->i_rdev ));
891
 
892
    if ( spaceRemaining == 0 )
893
    {
894
        return 0;
895
    }
896
 
897
    // First of all, return any unread data from the previous call
898
 
899
    if ( fileData->bufBytes > 0 )
900
    {
901
        if ( spaceRemaining < fileData->bufBytes )
902
        {
903
            bytesCopied = spaceRemaining;
904
        }
905
        else
906
        {
907
            bytesCopied = fileData->bufBytes;
908
        }
909
 
910
        if ( copy_to_user( &buffer[0], &fileData->buffer[0], bytesCopied ) != 0 )
911
        {
912
            return -EFAULT;
913
        }
914
        if ( fileData->bufBytes > bytesCopied )
915
        {
916
            memmove( &fileData->buffer[ 0 ], &fileData->buffer[ bytesCopied ], fileData->bufBytes - bytesCopied );
917
        }
918
        fileData->bufBytes -= bytesCopied;
919
 
920
        if ( fileData->bufBytes > 0 )
921
        {
922
            // We copied some data, but not all of it. Return early.
923
 
924
            return bytesCopied;
925
        }
926
    }
927
 
928
    do
929
    {
930
        if ((( file->f_flags & O_NONBLOCK ) != 0 ) && ( fileData->numEvents == 0 ))
931
        {
932
            // File was opened non-blocking and no more data is available
933
            // We don't want to wait for an event, so exit from the loop
934
 
935
            break;
936
        }
937
 
938
        rc = wait_event_interruptible( fileData->waitQueue, ( fileData->numEvents > 0 ));
939
        if ( rc != 0 )
940
        {
941
            return rc;
942
        }
943
 
944
        if ( fileData->readMode == GPIO_EventReadModeBinary )
945
        {
946
            gpio_event_dequeue_event( fileData, (GPIO_Event_t *)&fileData->buffer[0] );
947
 
948
            fileData->bufBytes = sizeof( GPIO_Event_t );
949
 
950
        }
951
        else
952
        {
953
            GPIO_Event_t    gpioEvent;
954
 
955
            gpio_event_dequeue_event( fileData, &gpioEvent );
956
 
957
            // ASCII Mode output:
958
            //
959
            // nn E tttttttt.tttttt
960
            //
961
            // Where nn is the base-10 GPIO number
962
            //       E is R or F (for rising or falling edge)
963
            //       tttttttt.tttttt is the timestamp with microsecond resolution
964
 
965
            fileData->bufBytes = snprintf( fileData->buffer, sizeof( fileData->buffer ),
966
                                           "%2d %c %ld.%06ld\n",
967
                                           gpioEvent.gpio,
968
                                           (( gpioEvent.edgeType == GPIO_EventRisingEdge ) ? 'R' : 'F' ),
969
                                           gpioEvent.time.tv_sec,
970
                                           gpioEvent.time.tv_usec );
971
        }
972
 
973
        if ( spaceRemaining >= fileData->bufBytes )
974
        {
975
            bytesToCopy = fileData->bufBytes;
976
        }
977
        else
978
        {
979
            bytesToCopy = spaceRemaining;
980
        }
981
 
982
        if ( copy_to_user( &buffer[ bytesCopied ], &fileData->buffer[0], bytesToCopy ) != 0 )
983
        {
984
            return -EFAULT;
985
        }
986
        spaceRemaining -= bytesToCopy;
987
        bytesCopied += bytesToCopy;
988
        fileData->bufBytes -= bytesToCopy;
989
 
990
        if ( fileData->bufBytes > 0 )
991
        {
992
            // We couldn't copy all of the data out of the buffer. Move the
993
            // remaining data to the beginning of the buffer and exit.
994
 
995
            memmove( &fileData->buffer[ 0 ], &fileData->buffer[ bytesToCopy ], fileData->bufBytes );
996
            return bytesCopied;
997
        }
998
    } while (( fileData->numEvents > 0 ) && ( spaceRemaining > 0 ));
999
 
1000
    if ((( file->f_flags & O_NONBLOCK ) != 0 ) && ( bytesCopied == 0 ))
1001
    {
1002
        // File was opened non-blocking and we didn't copy any data.
1003
 
1004
        return -EAGAIN;
1005
    }
1006
 
1007
    return bytesCopied;
1008
 
1009
} // gpio_event_read
1010
 
1011
/****************************************************************************
1012
*
1013
*  gpio_event_poll - used by select & poll
1014
*
1015
****************************************************************************/
1016
 
1017
static unsigned int gpio_event_poll(struct file *file, poll_table *wait)
1018
{
1019
    unsigned long       flags;
1020
    GPIO_FileData_t    *fileData = file->private_data;
1021
    unsigned int        mask = 0;
1022
 
1023
    poll_wait( file, &fileData->waitQueue, wait );
1024
 
1025
    spin_lock_irqsave( &fileData->queueLock, flags );
1026
    {
1027
        if (( fileData->bufBytes > 0 ) || ( fileData->numEvents > 0 ))
1028
        {
1029
            mask |= POLLIN | POLLRDNORM;    // readable
1030
        }
1031
    }
1032
    spin_unlock_irqrestore( &fileData->queueLock, flags );
1033
 
1034
    return mask;
1035
 
1036
} // gpio_event_poll
1037
 
1038
/****************************************************************************
1039
*
1040
*  gpio_event_release
1041
*
1042
****************************************************************************/
1043
 
1044
static int gpio_event_release( struct inode *inode, struct file *file )
1045
{
1046
    unsigned long       flags;
1047
    GPIO_FileData_t    *fileData = file->private_data;
1048
 
1049
    DEBUG( Trace, "gpio_event_release called\n" );
1050
 
1051
    spin_lock_irqsave( &gFileListLock, flags );
1052
    {
1053
        list_del( &fileData->list );
1054
    }
1055
    spin_unlock_irqrestore( &gFileListLock, flags );
1056
 
1057
    kfree( fileData );
1058
 
1059
    return 0;
1060
 
1061
} // gpio_event_release
1062
 
1063
/****************************************************************************
1064
*
1065
*   File Operations (these are the device driver entry points)
1066
*
1067
****************************************************************************/
1068
 
1069
struct file_operations gpio_event_fops =
1070
{
283 dhylands 1071
    owner:              THIS_MODULE,
1072
    unlocked_ioctl:     gpio_event_ioctl,
1073
    open:               gpio_event_open,
1074
    poll:               gpio_event_poll,
1075
    release:            gpio_event_release,
1076
    read:               gpio_event_read,
244 dhylands 1077
};
1078
 
1079
/****************************************************************************
1080
*
1081
*  gpio_event_init
1082
*
1083
*     Called to perform module initialization when the module is loaded
1084
*
1085
****************************************************************************/
1086
 
1087
static int __init gpio_event_init( void )
1088
{
1089
    int rc;
1090
 
1091
    DEBUG( Trace, "called\n" );
1092
 
1093
    printk( gBanner );
1094
 
1095
    // Get a major number
1096
 
1097
    if (( rc = alloc_chrdev_region( &gGpioEventDevNum, 0, 1, GPIO_EVENT_DEV_NAME )) < 0 )
1098
    {
1099
        printk( KERN_WARNING "sample: Unable to allocate major, err: %d\n", rc );
1100
        return rc;
1101
    }
1102
    DEBUG( Trace, "allocated major:%d minor:%d\n", MAJOR( gGpioEventDevNum ), MINOR( gGpioEventDevNum ));
1103
 
1104
    // Register our proc entries.
1105
 
1106
    gProcGpioEvent = create_proc_entry( "gpio-event", S_IFDIR | S_IRUGO | S_IXUGO, NULL );
1107
    if ( gProcGpioEvent == NULL )
1108
    {
1109
        return -ENOMEM;
1110
    }
1111
    gProcPins = create_proc_entry( "pins", 0444, gProcGpioEvent );
1112
    if ( gProcPins != NULL )
1113
    {
1114
        gProcPins->proc_fops = &pins_proc_ops;
1115
    }
1116
 
1117
#if ( LINUX_VERSION_CODE <= KERNEL_VERSION( 2, 6, 20 ))
1118
    gSysCtlHeader = register_sysctl_table( gSysCtl, 0 );
1119
    if ( gSysCtlHeader != NULL )
1120
    {
1121
        gSysCtlHeader->ctl_table->child->de->owner = THIS_MODULE;
1122
    }
1123
#else
1124
    gSysCtlHeader = register_sysctl_table( gSysCtl );
1125
#endif
1126
 
1127
    // Register our device. The device becomes "active" as soon as cdev_add 
1128
    // is called.
1129
 
1130
    cdev_init( &gGpioEventCDev, &gpio_event_fops );
1131
    gGpioEventCDev.owner = THIS_MODULE;
1132
 
1133
    if (( rc = cdev_add( &gGpioEventCDev, gGpioEventDevNum, 1 )) != 0 )
1134
    {
1135
        printk( KERN_WARNING "sample: cdev_add failed: %d\n", rc );
1136
        return rc;
1137
    }
1138
 
1139
    // Create a class, so that udev will make the /dev entry
1140
 
1141
    gGpioEventClass = class_create( THIS_MODULE, GPIO_EVENT_DEV_NAME );
1142
    if ( IS_ERR( gGpioEventClass ))
1143
    {
1144
        printk( KERN_WARNING "sample: Unable to create class\n" );
1145
        return -1;
1146
    }
1147
 
1148
    device_create( gGpioEventClass, NULL, gGpioEventDevNum, NULL, GPIO_EVENT_DEV_NAME );
1149
 
1150
    return 0;
1151
 
1152
} // gpio_event_init
1153
 
1154
/****************************************************************************
1155
*
1156
*  gpio_event_exit
1157
*
1158
*       Called to perform module cleanup when the module is unloaded.
1159
*
1160
****************************************************************************/
1161
 
1162
static void __exit gpio_event_exit( void )
1163
{
1164
    struct  list_head  *next;
1165
    struct  list_head  *pin;
1166
    GPIO_EventMonitor_t monitor;
1167
 
1168
    DEBUG( Trace, "called\n" );
1169
 
1170
    // If there are any pins which are currently being monitored, then we 
1171
    // need to unmonitor them.
1172
 
1173
    memset( &monitor, 0, sizeof( monitor ));
1174
 
1175
    list_for_each_safe( pin, next, &gPinList )
1176
    {
1177
        GPIO_PinData_t *pinData = list_entry( pin, GPIO_PinData_t, list );
1178
 
1179
        monitor.gpio = pinData->gpio;
1180
 
1181
        gpio_event_monitor( &monitor );
1182
    }
1183
 
1184
    // Deregister our driver
1185
 
1186
    device_destroy( gGpioEventClass, gGpioEventDevNum );
1187
    class_destroy( gGpioEventClass );
1188
 
1189
    cdev_del( &gGpioEventCDev );
1190
 
1191
    if ( gSysCtlHeader != NULL )
1192
    {
1193
        unregister_sysctl_table( gSysCtlHeader );
1194
    }
1195
    remove_proc_entry( "pins", gProcGpioEvent );
1196
    remove_proc_entry( "gpio-event", NULL );    
1197
 
1198
    unregister_chrdev_region( gGpioEventDevNum, 1 );
1199
 
1200
} // gpio_event_exit
1201
 
1202
/****************************************************************************/
1203
 
1204
module_init(gpio_event_init);
1205
module_exit(gpio_event_exit);
1206
 
1207
MODULE_AUTHOR("Dave Hylands");
1208
MODULE_DESCRIPTION("GPIO Event Driver");
1209
MODULE_LICENSE("Dual BSD/GPL");
1210