/*
 * tools/lib/pv_write_pe.c
 *
 * Copyright (C) 1997 - 2001  Heinz Mauelshagen, Sistina Software
 *
 * March 1997
 * August-September 1998
 * January 2000
 * June 2001
 *
 *
 * 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
 *
 *    06/09/1998 - implemented data layer in pv_write_pe() by using
 *                 new function pe_copy_to_disk()
 *    08/02/2000 - use debug_enter()/debug_leave()
 *    22/06/2001 - added Andreas Dilger's PE on 4k boundary alignment enhancements
 *
 */

#include <liblvm.h>


int pv_write_pe ( char *pv_name, pv_t *pv) {
   int pv_handle = -1;
   int ret  = 0;
   uint size = 0;
   pe_disk_t *pe_disk = NULL;

   debug_enter ( "pv_write_pe -- CALLED  pv->pe_total: %lu\n", pv->pe_total);

   if ( pv_name == NULL ||
        pv_check_name ( pv_name) < 0 ||
        pv == NULL) ret = -LVM_EPARAM;
   else {
      size = pv->pe_total * sizeof ( pe_disk_t);
      if ( size + pv->pe_on_disk.base > LVM_VGDA_SIZE ( pv))
         ret = -LVM_EPV_WRITE_PE_SIZE;;
      if ( ( pv_handle = open ( pv_name, O_WRONLY)) == -1)
         ret = -LVM_EPV_WRITE_PE_OPEN;
      else if ( lseek ( pv_handle,  pv->pe_on_disk.base, SEEK_SET) !=
                 pv->pe_on_disk.base)
         ret = -LVM_EPV_WRITE_PE_LSEEK;
      else {
         pe_disk = pe_copy_to_disk ( pv->pe, pv->pe_total);
         if ( write ( pv_handle, pe_disk, size) != size)
            ret = -LVM_EPV_WRITE_PE_WRITE;
         free ( pe_disk);
      }
   
      if ( pv_handle != -1) {
         fsync ( pv_handle);
         close ( pv_handle);
      }
   }

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