/*
 *   Pure Data Packet system implementation: Packet Manager
 *   Copyright (c) by Tom Schouten <tom@zwizwa.be>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */



#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <pf/typedefs.h>
#include <pf/symbol.h>
#include <pf/stream.h>
#include <pf/packet.h>
#include <pf/mem.h>
#include <pf/list.h>
#include <pf/type.h>
#include <pf/debug.h>

#define D if (0)

/*
  in order to improve this, it should be split into
  3 clearly distinct parts:
  [ ref count management ] <-> [ reuse fifo ] <- [ packet store ]
  
  it happens rarely that a new packet needs to be created,
  so mutex locking of the pool can be maintained. malloc
  does it anyway. there is no serious overall time penalty involved.

  on the other hand, the reuse fifo is used a lot.
  most of the allocation/deallocation could be replaced with
  lock-free logic. similar logic for the atom alloc/free.

  the ref count management is used even more, so this should
  be handled with lock-free logic too.

  new invariants: while rc == 0 (packet in reuse fifo)
  packets cannot change type and cannot be deleted.



packets:
   pf_packet_create        create mallocs new packet
   pf_packet_destroy       frees it

fifo:
   pf_packet_save      save a packet
   pf_packet_reuse     reuse a packet     

refs:
   packet_register      inc refcount or new
   packet_unregister    dec refcount or free


the factory does:
* try to pf_packet_reuse
* else pf_packet_create

packet_unregister does:
* decref
* pf_packet_save if rc = 0

   in general, the public interface is:
   pf_packet_register()
   pf_packet_unregister()
   pf_factory_newpacket()

 */



/* mutex: protects the main packet pool
   which maps integer identifiers to pf_header_t*
*/

/* debug */
void
pf_packet_post_debug(pf_header_t* packet)
{
    pf_header_t *h = pf_packet_header(packet);
    pf_post("debug info for packet %d", packet);
    if (!h){
	pf_post("invalid packet");
    }
    else{
	pf_post ("\ttype: %d", h->type);
	pf_post ("\tdesc: %s", h->desc);
	pf_post ("\tsize: %d", h->data_size);
//	pf_post ("\tflags: %x", h->flags);
	pf_post ("\tusers: %d", h->rc);
	pf_post ("\tclass: %x", h->theclass);
    }
}



/* setup methods */

void pf_class_setup(void);
void 
pf_packet_setup(void)
{
    pf_class_setup();
}


/* reuse stack memory management */
static void symbol_packet_save(pf_symbol_t *type, pf_header_t *header){
    pf_list_t *s;
    PF_ASSERT(type);
    if (s = type->s_stack){
      got_stack:
	pf_list_push_packet(s, header);
	return;
    }
    s = type->s_stack = pf_list_new();
    goto got_stack;
}

static pf_header_t* symbol_packet_reuse(pf_symbol_t *type){
    pf_list_t *s;
    if (s = type->s_stack){
	if (s->elements) {
	    return pf_list_pop(s).w_packet;
	}
    }
    return 0;
}



/* private packet methods */

/* packets can only be created and destroyed using these 2 methods */
/* it updates the mem usage and total packet count */

static void
packet_dealloc(pf_header_t *p)
{
    /* free memory */
    D pf_post("packet: freeing packet %x", p);
    pf_dealloc (p);
}

/* create a new packet with properly initialized header. */

pf_header_t*
pf_packet_create(unsigned int data_type, unsigned int header_size, unsigned int data_size)
{
    pf_header_t *p = (pf_header_t *)pf_alloc(header_size);

    // catch sizeof(*)
    PF_ASSERT(header_size > sizeof(pf_header_t));

    D pf_post("packet: create type %d, size %d %d",
              data_type, header_size, data_size);

    if (p){
	//memset(p, 0xbd, datasize);
	memset(p, 0, header_size); 
	p->type = data_type;
	p->rc   = 1;
        
        if (data_size){
            p->data_size = data_size;
            if (!(p->data = pf_alloc(data_size))) {
                pf_dealloc(p);
                return 0;
            }
        }

    }
    return p;
}



/* internal method to add a packet to a packet type
   description symbol's unused packet fifo.
   packet has to be unused.
*/
static void
packet_save(pf_header_t *header)
{
    PF_ASSERT(header);
    PF_ASSERT(header->desc);

    D pf_post("saving %08x %s", header, header->desc->s_name);

    PF_ASSERT(0 == header->rc);  // assert RC == 0
    PF_ASSERT(header->theclass);

    if (header->theclass->sleep){
	D pf_post("executing sleep() for %08x %s", header, header->desc->s_name);
	header->theclass->sleep(header); // sleep if necessary
        PF_ASSERT(header->desc);         // check for possible memset in sleep
    }



    // push atom to reuse stack
    symbol_packet_save(header->desc, header);
}


/* this will revive a packet matching a certain type description
   no wildcards are allowed */
pf_header_t*
pf_packet_reuse(pf_symbol_t *type_description)
{
    PF_ASSERT(type_description);
    pf_header_t *h = symbol_packet_reuse(type_description);
    if (h){
        PF_ASSERT(h->theclass);

	if (h->theclass->wakeup)
	    h->theclass->wakeup(h); // revive if necessary

	h->rc++;                // inc refcount
	PF_ASSERT(h->rc == 1);  // need to be only owner

	D pf_post("reusing %08x %s", h, h->desc->s_name);

    }
    return h;
}

/* this returns a copy of a packet for read only access. 
   (increases refcount of the packet -> packet will become readonly if it was
   writable, i.e. had rc=1 */

pf_header_t*
pf_packet_register(pf_header_t *header)
{
    if (!header) return 0;
    header->rc++;
    return header;
}

/* clone a packet: create a new packet with the same
   type as the source packet */

pf_header_t*
pf_packet_clone(pf_header_t* header)
{
    if (!header) return 0;

    /* consistency checks */
    PF_ASSERT(header->desc);
    
    return pf_factory_newpacket(header->desc);
}

/* decrement refcount */
void 
pf_packet_unregister(pf_header_t* header){

    if (!header) return;
    PF_ASSERT(header->desc);
    int rc = --(header->rc);
 
    if (0 == rc) { packet_save(header); }

}



pf_header_t *
pf_packet_copydata(pf_header_t *header)
{
    PF_ASSERT(header);
    PF_ASSERT(header->theclass);
    if (!(header->theclass->copydata)){ return 0; }

    pf_header_t *new = pf_packet_clone(header);
    if (!new) return 0;
    header->theclass->copydata(new, header);
    return new;
}

/* replaces a packet with a writable copy */
pf_header_t *pf_packet_reserve(pf_header_t **ph)
{

    PF_ASSERT(*ph);
    if ((*ph)->rc == 1) {
        return *ph;
    }
    else {
        pf_header_t *new = pf_packet_copydata(*ph); // make a copy
        if (!new) return 0; // no copy method
        pf_packet_unregister(*ph); // unreg orig
        *ph = new; // replace
        return new;
    }
}




/* public data access methods */




pf_symbol_t
*pf_packet_type(pf_header_t* header)
{
    if (header){
	PF_ASSERT(header->desc);
	return header->desc;
    }
    return pf_symbol("invalid");
}



#ifdef __cplusplus
}
#endif
