
/**
 @Name:		ps.c
 @Purpose:	@User:  Fill in purpose

 Message Types:
	@User:  Document messages (requests and replies) here
	Op	Short Descr	Request			Reply
	-----------------------------------------------------------
	0	Hello		[0]  instance #		plugin id
				[1]  command = 0	instance #
 Notation:
	- this:  struct rp_instance * (ptr to plugin instance)
 Post-Conditions:
   ps_load
	- Plugin class (ps_class) structure is initialized
	- ps_get_class() is registered with PCU
   ps_create_instance
	- Plugin instance memory is allocated and initialized
	  (base class and its extension):
	  this->rpclass = &ps_class
	  ... other members of base class ...
   ps_bind_instance
   
   ps_handle_packet
   
   ps_handle_message
   
   ps_unbind_instance
   
   ps_free_instance
	- Plugin instance memory is free
   ps_unload
	- All instances are free
	- Class is not registered with PCU
*/

#include "stdinc.h"

#include "ps.h"

MOD_MISC("ps")

// Static plugin class structure.
// Each kernel module has one class structure that is initialized by
// the plugin and a pointer to it is returned. The class structure can then
// be used to create plugin instances. Note that this is a structure and 
// not a pointer.
static struct rp_class ps_class;

// @User:  Add class-wide global variables here
struct rp_instance *global_ps_inst_ptr;

void
ps_handle_packet(
  struct rp_instance *this,		// points to instance structure
  void *bufferList)			// points to list of pkt buffers
{
  struct ps_instance *inst = (struct ps_instance *)this;
  // @User:  Add code to handle packets here

  u_int16_t port;				// incoming pkt port
  struct msr_bufhdr_t *buffer;		// incoming pkt buffer
  struct ip *iph;
  int s;
  HDRQ_t *hdrs = bufferList;
  
  s = PLUGIN_SPLCLOCK_FCT();		// Lock the critical section
  
  buffer = TAILQ_FIRST(hdrs);
  iph = msr_pkt_iph(buffer);
  TAILQ_REMOVE(hdrs, buffer, qlist);	// Remove the packet from the list

  // Get the destination port
  port = msr_ipdport(iph);
  
  // Add the packet to the appropriate priority queue
  switch(port % 4){
    case 0:
      if(inst->first_s < 5){
	TAILQ_INSERT_TAIL(&inst->first_q, buffer, qlist);
	inst->first_s++;
      }
      break;
    case 1:
      if(inst->second_s < 5){
	TAILQ_INSERT_TAIL(&inst->second_q, buffer, qlist);
	inst->second_s++;
      }
      break;
    case 2:
      if(inst->third_s < 5){
	TAILQ_INSERT_TAIL(&inst->third_q, buffer, qlist);
	inst->third_s++;
      }
      break;
    case 3:
      if(inst->fourth_s < 5){
	TAILQ_INSERT_TAIL(&inst->fourth_q, buffer, qlist);
	inst->fourth_s++;
      }
      break;
    default:
     TAILQ_INSERT_TAIL(&inst->fourth_q, buffer, qlist);
     inst->fourth_s++;
  }

  // Re-enable interrupts
  PLUGIN_SPLX_FCT(s);
  return;
  
}

// Callback function
void ps_callback(void) {
  struct ps_instance *myinst;
  int s;
  struct msr_bufhdr_t *buffer;	  //pkt buffer

  // Do some checking so nothing happens if instance hasn't been created
  if (global_ps_inst_ptr == NULL) return;
  myinst = (struct ps_instance *) global_ps_inst_ptr;
  if (myinst == NULL) return;

  s = PLUGIN_SPLCLOCK_FCT(); // Disable interrupts
  
  if(myinst->first_s > 0){
    buffer = TAILQ_FIRST(&myinst->first_q);
    TAILQ_REMOVE(&myinst->first_q, buffer, qlist);
    
    // Send the packet
    PLUGIN_IP_FWD_FCT(buffer); //What happens when it returns -1?
    myinst->first_s--;
  }
  else if(myinst->second_s > 0){
    buffer = TAILQ_FIRST(&myinst->second_q);
    TAILQ_REMOVE(&myinst->second_q, buffer, qlist);
    
    // Send the packet
    PLUGIN_IP_FWD_FCT(buffer); //What happens when it returns -1?
    myinst->second_s--;
  }
  else if(myinst->third_s > 0){
    buffer = TAILQ_FIRST(&myinst->third_q);
    TAILQ_REMOVE(&myinst->third_q, buffer, qlist);
    
    // Send the packet
    PLUGIN_IP_FWD_FCT(buffer); //What happens when it returns -1?
    myinst->third_s--;
  }
  else if(myinst->fourth_s > 0){
    buffer = TAILQ_FIRST(&myinst->fourth_q);
    TAILQ_REMOVE(&myinst->fourth_q, buffer, qlist);
    
    // Send the packet
    PLUGIN_IP_FWD_FCT(buffer); //What happens when it returns -1?
    myinst->fourth_s--;
  }
  
  PLUGIN_SPLX_FCT(s); // Renable interrupts
  return;
}

void
ps_init_class() {		// initialize plugin class
//
// Initialize class struct:
//   classid - user defined
//   itype   - RP_INTERFACE_TYPE_PKT - for read-only plugins. The handle packet
//             signature is <handle_packet(struct rp_instance *this, void *pkt)>
//             RP_INTERFACE_TYPE_HLIST for plugins that will modify pkts or want
//             to source or sink data. The signature is
//              <handle_packet(struct rp_instance *this, void *plist)>
//   create_instance = function pointer to your create instance method.

  int poll_freq = cbPeriod;
  int ticks = PLUGIN_MSR_USEC2TICKS_FCT(poll_freq);
  
  ps_class.classid = ps_ID;
  ps_class.itype   = RP_INTERFACE_TYPE_HLIST;
  ps_class.create_instance = ps_create_instance;

  global_ps_inst_ptr = NULL;

  PLUGIN_MSR_CLOCK_HANDLER_FCT(ps_callback,
			      MSR_CLOCK_HANDLER_PCU_ID, ticks);
  
  return;
}

// --| create and initialize an instance of ps |--
struct rp_instance *
ps_create_instance(
  struct rp_class *myclass,		// points to class structure
  u_int32_t instanceid)			// new instance identifier
{
  struct ps_instance *myinst; 

  // allocate memory for local instance struct
  MSR_PLUGIN_MALLOC(myinst,struct ps_instance *, 
                    sizeof(struct ps_instance),
                    M_MSR, 
                    M_WAITOK);
  if (myinst == NULL)	return NULL;

  // fill in instance pointers to local methods
  myinst->rootinstance.rpclass         = &ps_class;
  myinst->rootinstance.handle_packet   = ps_handle_packet;
  myinst->rootinstance.free_instance   = ps_free_instance;
  myinst->rootinstance.bind_instance   = ps_bind_instance;
  myinst->rootinstance.unbind_instance = ps_unbind_instance;
  myinst->rootinstance.handle_msg      = ps_handle_msg;

  myinst->rootinstance.instanceid = instanceid;

  // @User:  Initialize instance variables here

  TAILQ_INIT(&myinst->first_q);
  TAILQ_INIT(&myinst->second_q);
  TAILQ_INIT(&myinst->third_q);
  TAILQ_INIT(&myinst->fourth_q);

  myinst->first_s = 0;
  myinst->second_s = 0;
  myinst->third_s = 0;
  myinst->fourth_s = 0;
  
  global_ps_inst_ptr = (struct rp_instance *) myinst;
  
  return (struct rp_instance *)myinst;
}



/*
 @Purpose: Handle control messages.
	The request buffer 'buf' is 44 Bytes (11 ints) long. The same array
	will be used for the reply msg (i.e., request buffer is reused for
	the reply buffer and is overwritten).
 	Request Buffer (1 word = 1 int):
		Word 0	Instance number of receiver
		Word 1	Command (Operation Code)
		Word 2	Arg 0 (if any)
		...
		Word 10	Arg 8 (if any)
	Note 1:	By convention, command 0 is the 'hello' command which returns
		the plugin id and the instance number.  All other commands are
		at the discretion of the user.
	Note 2: The word preceding buf[0] contains the message header and
		contains the values of 'flags', 'seq' and '*len' which are
		passed to this routine.
 @User: Append request codes and reply args to the list below.
 Request Codes:		Reply (#: args):
	0: Hello	2: ps_ID, id
	*: Hello	2: ps_ID, id
*/
int
ps_handle_msg(
  struct rp_instance *this,	// points to instance structure
  void *buf,			// points to request/reply buffer
  u_int8_t flags,		// flags
  u_int8_t seq,			// sequence number
  u_int8_t *len)		// IN:  request is in buf[0] thru buf[*len/4-1]
				// OUT:	reply is in buf[0] thru buf[*len/4-1]
{
  struct ps_instance *inst = (struct ps_instance *)this;
  u_int32_t *vals	= (u_int32_t *)buf;
  u_int32_t id		= (u_int32_t)ntohl(*vals);
  u_int32_t cmnd	= (u_int32_t)ntohl(*(vals + 1));
  struct msr_bufhdr_t *hdr;

  *vals	= (u_int32_t)htonl(ps_ID);
  *(vals + 1)	= (u_int32_t)htonl(id);

  switch (cmnd) {
    case 0:	// Hello
      *len = 2 * sizeof(u_int32_t);
      break;
    case 1:
      // @User:  Add code to handle other messages here
    default:
      // @User:  Usually, a copy of the most common command reply
      *len = 2 * sizeof(u_int32_t);
      break;
  }

  return 0;
}



// --| Free instance structure |--
void
ps_free_instance(
  struct rp_instance *this)	// points to instance structure
{
  if (this) {
    MSR_PLUGIN_FREE(this, M_MSR);
  }
}

// --| Bind plugin instance to filter |--
void
ps_bind_instance(
  struct rp_instance *this)	// points to instance structure
{
  struct ps_instance *inst = (struct ps_instance *)this;

  // @User:  Define what occurs when binding your plugin here
}

// --| Unbind plugin instance from filter
void
ps_unbind_instance(
  struct rp_instance *this)	// points to instance structure
{
  struct ps_instance *inst = (struct ps_instance *)this;

  // @User:  Define what occurs when unbinding your plugin here
}

/**
	----------------------------------------------------------------
 @User: YOU SHOULD NOT NEED TO MAKE ANY CHANGES TO THE REST OF THIS FILE
	----------------------------------------------------------------
*/

struct rp_class *
ps_get_class() {	// return class structure
  return &ps_class;
}

// External kernel module entry point.
//
// This function must match the name of the .o file.
// It is called each time the module is loaded or unloaded.
// The stat information is not needed here, so we will 
// leave it lkm_nofunc().
//

int
ps  (
  struct lkm_table *lkmtp,	// points to loadable kernel module table
  int cmd,			// command:  load or unload
  int ver,			// version
  struct kernel_plugin_fct_struct *fctPtr)
				// points to table of kernel functions
{
  // Do NOT put anything before the kernel_plugin_fcts is set, especially if
  // it uses any of the MSR_ macros!!!
  if (kernel_plugin_fcts == NULL) {
    kernel_plugin_fcts = fctPtr;
    kernel_plugin_variables = fctPtr->pluginVariables;
  }

  MSR_PLUGIN_DISPATCH(lkmtp, cmd, ver, ps_load, ps_unload,
							PLUGIN_LKM_NOFUNC_FCT);
}

// This function is called each time the module is loaded
int
ps_load(
  struct lkm_table *lkmtp,	// points to loadable kernel module table
  int cmd)			// command (should be load)
{
  int err;

  if (PLUGIN_LKM_EXISTS_FCT(lkmtp)) {	// avoid loading twice
    return (EEXIST);
  }
  ps_init_class();

  err = PLUGIN_PCU_REGISTER_CLASS_FCT(ps_get_class());
  if (err != RP_OK) {
    return -1;
  }

  return 0;
}

// This function is called each time the module is unloaded.
// Remove all existing instances and then remove class.
int
ps_unload(
  struct lkm_table *lkmtp,	// points to loadable kernel module table
  int cmd)			// command (should beunload)
{
  struct rp_class *rpclass;
  u_int32_t cid;

  rpclass = ps_get_class();
  cid = rpclass->classid;

  if (PLUGIN_PCU_FREE_ALL_INSTANCES_FCT(rpclass) != RP_OK) {
    return -1;
  }


  return 0;
}

