/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */
#include <iostypes.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>

/* Preserve order to match defs in iostypes.h */
#define IOS_EVENT_NAMED_MAX 7
const char *IOS_EVENT_NAMES[] = 
{  "AES_EVENT"
   ,"SHA_EVENT"
   ,"USB_EVENT"
   ,"FLASH_EVENT"
   ,"IPC_EVENT"
   ,"ADC_EVENT"
   ,"DAC_EVENT"
};
#define PROCFS_PRFX "/proc/irq/"
#define PROCFS_SFX  "irq"
#define PROCFS_MODE O_RDONLY
static int irq = -1;
static int signum = -1;
static char proc[128] = "iose";
static int dbg_run = -1; 
static int unreg = -1;
static const char* name;

static int
eventnum2sig(int e)
{
    if ( e < 0 || e > IOS_NUM_EVENTS )
        return -1;
    signum = IOS_EVENT_MIN + e;
    return 0;
}

static int
event2sig(const char *e)
{
    int i;
    for ( i = 0; i < IOS_EVENT_NAMED_MAX; ++i ) 
        if ( 0 == strcmp(e, IOS_EVENT_NAMES[i]))
            return eventnum2sig(i);
    return -1;
}

static int
parse_args(int argc, char **argv)
{
    char c;
    while ( -1 != (c = getopt(argc, argv, "i:e:E:p:du")) ) {
        switch (c) {
            case 'i':
                irq = atoi(optarg);
                break;
            case 'e':
                if ( -1 == eventnum2sig(atoi(optarg))) goto err;
                break;
            case 'E':
                if ( -1 == event2sig(optarg)) goto err;
                break;
            case 'p':
                strcpy(proc, optarg);
                break;
            case 'd':
                dbg_run = 1;
                break;
            case 'u':
                unreg = 1;
                break;
            default:
//                printf("Unknown option: -%c\n", optopt);
                goto err;
        }
    }
    return 0;
err:
    return -1;
}

static void
usage(void)
{
    printf("-----------------------------------------------\n");
    printf("Usage: reg_irq -i <irq> {-e <e_num> or -E e_name} [-p process] [-d] \n"
           "\t irq    - IRQ \n"
           "\t e_num  - event numbers defined in iostypes.h\n"
           "\t e_name - event name, one of {AES_EVENT, SHA_EVENT, USB_EVENT, FLASH_EVENT, IPC_EVENT, ADC_EVENT, DAC_EVENT } \n"
           "\t p      - name of process to send signal to [iose]\n"
           "\t d      - debug run. Sends periodic signals to process: %s\n"
           "\t u      - unregister handler for specified IRQ"
           , proc);
    printf("-----------------------------------------------\n");
}

static void
print_settings(void)
{
  printf("*** IRQ = %d; Signal = %d; Process = %s\n", irq, signum, proc);
  if ( 1 == dbg_run ) {
      printf("*** Debug run only. Will send periodic signals to iose.\n");
  }
}

void 
handle_intr(void)
{
    char cmd[64];
    sprintf(cmd, "killall -s %d %s", signum, proc);
    system(cmd);
}

void
dbg_irq(void)
{
   while(1) {
       handle_intr();
       sleep(1);
   }
   /* not reached */
}

void
print_irqstate(void)
{
   printf("Interrupts and their registered handlers: \n");
   system("cat /proc/interrupts");
   printf("-----------------------------------------------\n");
}

void
register_irq(void)
{
   FILE *fp;
   char buf[64];
   sprintf(buf,"/var/run/%s_%d", name, irq);
   if ( NULL == (fp = fopen(buf, "w"))) goto err;
   if ( fprintf(fp,"%d", getpid()) < 1 ) goto err;
   fclose(fp);
   return;
err:
       printf("*** Failed to register handler for IRQ: %d\n", irq);
       printf("*** You will not be able to unregister using %s\n", name);
       return;
}

void
monitor_irq(void)
{
    int nirq, err, fd;
    int enable = 0;
    char s[32];
    sprintf(s,"%s%d/%s",PROCFS_PRFX, irq, PROCFS_SFX);
    if ( (fd = open(s, PROCFS_MODE)) < 0 ) {
        printf("*** A handler already exists for IRQ: %d\n", irq);
        perror("*** open failed");
        print_irqstate();
        exit(1);
    }
    register_irq();
    while(1) {
        if ( -1 == (err = read(fd, &nirq, sizeof(nirq))) ) {
            switch ( errno ){
                case EINTR:
                    continue;
                case EBUSY:
                    if ( -1 == write(fd, &enable, sizeof(enable)) ) {
                        printf("*** A handler already exists for IRQ: %d\n", irq);
                        print_irqstate();
                        exit(1);
                    }
                    continue;
                default:
                    printf("*** Interrupt device read returned EINVAL\n");
                    break;
            }
        }
        else 
            handle_intr();
    }
    /* not reached */
    return;
}

void
unregister_irq()
{
   FILE *fp;
   char buf[64];
   int pid;
   sprintf(buf,"/var/run/%s_%d", name, irq);
   if ( NULL == (fp = fopen(buf, "r"))) goto err;
   if ( fscanf(fp,"%d", &pid) < 1 ) goto err;
   printf("%s: killing process pid: %d\n", name, pid);
   sprintf(buf,"kill -9 %d", pid);
   system(buf);
   fclose(fp);
   sprintf(buf,"/var/run/%s_%d", name, irq);
   unlink(buf);
   return;
err:
       printf("*** Did not find an IOSE handler for IRQ: %d\n", irq);
       print_irqstate();
       exit(1);
}

/* To register IRQ handler:
 *      Specify -i IRQ# -e event# or -E event_name
 * To register dummy handler:
 *      Specify -i IRQ# -e event# or -E event_name -d
 * To unregister handler for IRQ #:
 *      Specify -u -i IRQ#
 * Adding a -d to anything will print some more info
 */

int 
main(int argc, char *argv[])
{
    name = argv[0];
    if ( -1 == parse_args(argc, argv) ) goto err;
    if ( (-1 == irq) && ( (1 != dbg_run) || (-1 == signum))) goto err; 
    if ( (-1 == signum)  && ( (1 != unreg) || (-1 == irq) )) goto err;
    
    if ( 1 == unreg ) {
        unregister_irq();
        goto done;
    }
    print_settings();
    if ( -1 == dbg_run )
        monitor_irq();
    else
        dbg_irq();
done:
    return 0;
err:
    usage();
    if ( -1 != dbg_run)
        print_irqstate();
    return 0;
}
