/*= -*- c-file-style: "linux"; indent-tabs-mode: t; -*-
 *
 * n4: A fast userspace NFSv4 server.
 * $Id: outbuf.c,v 1.9 2001/07/20 07:42:19 mbp Exp $
 * 
 * Copyright (C) 2001 by Martin Pool <mbp@samba.org>
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 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
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <includes.h>

/*
 * TODO: For debugging, add an option to always realloc the buffer.
 * Is there anything we can do to make sure the previous buffer is
 * made invalid?  What about marking it for mprotect()?  No, there's
 * no need -- we can rely on mcheck or ElectricFence to do that.
 *
 * TODO: We also possibly want a way to truncate a buffer.  For
 * example, if READDIR discovers an error halfway through reading a
 * directory, then it has to throw out all the results generated so
 * far and send only the error code.  We can remember the point at
 * which we need to emit the overall result, so we just need to
 * truncate at that point.  Perhaps there is a more structured way
 * than coding every instance like this?  */

/**
 * Allocate a new packet buffer for output.
 *
 * The first word of the buffer is reserved for later use to hold the
 * size of the packet.  
 *
 * TODO: Perhaps we need to be smarter about working out the size to
 * allocate.  It might be best to pre-allocate a 64kB buffer, so that
 * we're unlikely to have to resize.
 **/
n4err n4buf_init_outbuf(n4outbuf *b, TALLOC_CTX *pool)
{
    b->pool = pool;
    b->alloc_len = 16;
    b->start = b->p = (guint32 *) talloc(pool, b->alloc_len);
    n4trace("init outbuf %p on pool %p", b, pool);
    if (!b->p) {
        n4log_error("failed to allocate initial output buffer");
        return N4ERR_MEM;
    }

    /* make uninitialized data obvious */
    memset(b->start, '$', b->alloc_len);

    *(b->p)++ = 0;
    
    return N4OK;
}


/**
 * Make sure there is at least \p reqd more \b bytes of output space
 * in \p buf.  If not, reallocate the buffer, updating both the \p
 * start and \p p pointers.
 **/
n4err n4outbuf_expand(n4outbuf *buf, int words_reqd)
{
    size_t new_len;

    new_len = (sizeof *buf->p) * (buf->p - buf->start + words_reqd);
    if (new_len > buf->alloc_len) {
        guint32  *new_start;
        size_t   empty_bytes;
        
/*          n4trace("realloc buf %p on pool %p to %ld", buf, buf->pool, */
/*                  (long) new_len); */
        new_start = talloc_realloc(buf->pool, buf->start, new_len);
        if (!new_start) {
            n4log_error("failed to allocate new output buffer of %ld bytes",
                         (long) new_len);
            return N4ERR_MEM;
        }

        /* keep the same relative position for p */
        if (new_start != buf->start)
            buf->p = new_start + (buf->p - buf->start);
        buf->start = new_start;
        buf->alloc_len = new_len;
        
        /* Make uninitialized data obvious: fill from the next empty
         * space on to the end of the buffer.  This may be larger than
         * the growth if there was already some free space. */
        empty_bytes = new_len - (sizeof *buf->p) * (buf->p - buf->start);
        memset(buf->p, '$', empty_bytes);
    }

    return N4OK; 
}


/**
 * Return the length of bytes actually written into the buffer.  Use
 * this when construction is complete to find out how much must be
 * transmitted.
 */
n4err n4buf_calc_outbuf_len_bytes(n4outbuf const *buf, size_t *len)
{
    *len = (sizeof *buf->p) * (buf->p - buf->start);
    if (*len > buf->alloc_len) {
        n4fatal("buffer %p overfilled; alloc len=%ld, actual len=%ld",
                 buf, (long) buf->alloc_len, (long) *len);
    }
    
    return N4OK;
}


n4err n4buf_check_outbuf(n4outbuf const *buf)
{
    size_t len;

    n4buf_calc_outbuf_len_bytes(buf, &len);
    return N4OK;
}


n4err n4outbuf_pad_after(struct n4outbuf *outb,
			 int result)
{
    int				padding_bytes;
    int				i;

    padding_bytes = ((result + 3) & ~3) - result;
    i = 0;
    while (padding_bytes--) {
	((char *) outb->p)[result + i++] = 0;
    }

    return N4OK;
}


/**
 * Return the position (words from start) of the cursor in an output
 * buffer, and advance the pointer.  Use this when you need to leave
 * space for a field whose value won't be known until later.
 *
 * This must be stored as an offset, since the buffer might move in
 * memory later on.
 **/
int n4outbuf_skip(n4outbuf *b)
{
    return b->p++ - b->start;
}


/**
 * Returns position of output cursor, in words.
 **/
int n4outbuf_tell(struct n4outbuf *b)
{
    return b->p - b->start;
}


void n4outbuf_seek(struct n4outbuf *b,
                                 int pos)
{
    b->p = &b->start[pos];
}


void n4outbuf_pack_at(struct n4outbuf *b,
                                    int pos,
                                    uint32_t val)
{
    n4_assert(pos > 0);
    n4_assert(pos < (b->p - b->start));
    b->start[pos] = val;
}


void n4outbuf_advance(struct n4outbuf *outb,
                                    int words)
{
    outb->p += words;
}


void PACK (struct n4outbuf *b,
	   int32_t d)
{
    n4pack_nocheck (b, d);
}


void n4pack_nocheck (struct n4outbuf *b,
		     int32_t d)
{
    *(b->p)++ = d;
}


n4err n4pack_checked(struct n4outbuf *outb,
				   uint32_t v)
{
    CHECK_ERR(n4outbuf_expand(outb, 1));
    PACK(outb, TO_NET(v));
    return N4OK;
}


/**
 * Signed int64 fields are rare, but they do occur, e.g. in nfstime4.
 **/
void n4pack_signed64_nocheck (struct n4outbuf *outb,
			      int64_t d)
{
    PACK_HYPER (outb, GINT64_TO_BE (d));
}


n4err n4pack64_checked (struct n4outbuf *outb,
			uint64_t v)
{
    CHECK_ERR(n4outbuf_expand(outb, 2));
    PACK_HYPER(outb, GUINT64_TO_BE(v));
    return N4OK;
}


void n4pack64_nocheck (struct n4outbuf *outb,
		       uint64_t v)
{
    PACK_HYPER(outb, TO_NET(v));
}


void PACK_HYPER(n4outbuf *b, guint64 d)
{
    guint64 *hyp = (guint64 *) b->p;
    *hyp++ = d;
    b->p = (guint32 *) hyp;
}


