/*
 * tools/lib/pv_read_pe.c
 *
 * Copyright (C) 1997 - 2001  Heinz Mauelshagen, Sistina Software
 *
 * March-May,October-November 1997
 * May,August,November 1998
 * January 2000
 * April,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_read_pe() by using
 *                 new function pe_copy_from_disk()
 *    08/02/2000 - use debug_enter()/debug_leave()
 *    09/04/2001 - cleaned up debug output (Andreas Dilger)
 *    22/06/2001 - added Andreas Dilger's PE on 4k boundary alignment enhancements
 *
 */

#include <liblvm.h>


int pv_read_pe ( pv_t *pv, pe_disk_t **pe) {
   int pv_handle = -1;
   int ret = 0;
   uint size = 0;
   pe_disk_t *pe_this = NULL;

   debug_enter ( "pv_read_pe -- CALLED with %s and %lu\n",
                 pv != NULL ? pv->pv_name : "NULL",
                 pv != NULL ? pv->pe_total : 0);

   if ( pv == NULL || pe == NULL) {
      ret = -LVM_EPARAM;
      goto pv_read_pe_end;
   }

   *pe = NULL;

   size = pv->pe_total * sizeof ( pe_disk_t);
   if ( size + pv->pe_on_disk.base > LVM_VGDA_SIZE ( pv)) {
      ret = -LVM_EPV_READ_PE_SIZE;
      goto pv_read_pe_end;
   }
   if ( ( pv_handle = open ( pv->pv_name, O_RDONLY)) == -1)
      ret = -LVM_EPV_READ_PE_OPEN;
   else if ( lseek ( pv_handle, pv->pe_on_disk.base, SEEK_SET) !=
             pv->pe_on_disk.base) ret = -LVM_EPV_READ_PE_LSEEK;
   else if ( ( pe_this = malloc ( size)) == NULL) {
      fprintf ( stderr, "malloc error in %s [line %d]\n",
                        __FILE__, __LINE__);
      ret = -LVM_EPV_READ_PE_MALLOC;
   } else {
      memset ( pe_this, 0, size);
      if ( read ( pv_handle, pe_this, size) != size)
         ret = -LVM_EPV_READ_PE_READ;
      else {
         *pe = pe_copy_from_disk ( pe_this, pv->pe_total);
      }
   }
   debug ( "pv_read_pe -- ret: %d\n", ret);
   if ( pv_handle != -1) close ( pv_handle);
   if ( pe_this != NULL) free ( pe_this);

pv_read_pe_end:

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