/*
 * tools/lib/pv_setup_for_create.c
 *
 * Copyright (C) 1997 - 2002  Heinz Mauelshagen, Sistina Software
 *
 * March 1997
 * January 1999
 * January,March,September 2000
 * January 2002
 *
 *
 * This LVM library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This LVM library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this LVM library; if not, write to the Free
 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
 * MA 02111-1307, USA
 *
 */

/*
 * Changelog
 *
 *    13/01/1999 - added memset pv_name and vg_name
 *               - added zeroing of rest of pv_name
 *    08/02/2000 - use debug_enter()/debug_leave()
 *    17/03/2000 - changed namelist to uuidlist
 *    24/04/2000 - used lvm_create_uuid() to initialize physical volume UUID
 *    28/09/2000 - fixed bug if called with vg->pv->pv_name as dev_name
 *    29/01/2002 - added setup for vg_on_disk.base+size for pv_write()
 *                 to zero gap between PV and VG struct [AED]
 *
 */

#include <liblvm.h>


int pv_setup_for_create(char *dev_name, pv_t *pv, uint size)
{
	int ret = 0;
	char tmp[512];

	debug_enter("pv_setup_for_create -- CALLED for DEV %s, size %u\n",
		    dev_name, size);

	if (!dev_name || !pv || !size || (pv_check_name(dev_name) < 0)) {
		ret = -LVM_EPARAM;
		goto out;
	}

	/*
	 * sometimes dev_name is already pointing to pv->pv_name !  so
	 * copy the name to a temporary place before zeroing the
	 * structure.
	 */
	strncpy(tmp, dev_name, sizeof(tmp) - 1);
	tmp[sizeof(tmp) - 1] = '\0';

	/* zero it */
	memset(pv, 0, sizeof(*pv));

	strncpy(pv->id, LVM_ID, sizeof(pv->id));
	pv->version = LVM_STRUCT_VERSION;
	pv->pv_on_disk.base = LVM_PV_DISK_BASE;
	pv->pv_on_disk.size = LVM_PV_DISK_SIZE;

        /* We need these set so that pv_write() can properly zero out the
         * rest of the PV header.  We don't want to hard-code this into
         * pv_write() because the vg_on_disk.base can be different.
         */
        pv->vg_on_disk.base = LVM_VG_DISK_BASE;
        pv->vg_on_disk.size = LVM_VG_DISK_SIZE;

	/* copy the name back in from the temporary var */
	strncpy(pv->pv_name, tmp, sizeof(pv->pv_name) - 1);

	system_id_set(pv->system_id);
	pv->pv_dev = pv_create_kdev_t(pv->pv_name);
	pv->pv_allocatable = PV_ALLOCATABLE; /* bitfield */
	pv->pv_size = size;
	memcpy(pv->pv_uuid, lvm_create_uuid(UUID_LEN), UUID_LEN);

 out:
	debug_leave("pv_setup_for_create -- LEAVING with ret: %d\n", ret);
	return ret;
}
