/*
 * tools/lib/lv_init_COW_table.c
 *
 * Copyright (C) 2000 - 2001 Heinz Mauelshagen, Sistina Software
 *
 * July 2000
 * March,April 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
 *
 *    09/04/2001 - cleaned up debug output (Andreas Dilger)
 * 
 */

#include <liblvm.h>


int lv_init_COW_table ( vg_t *vg, lv_t *lv) {
   int le = 0;
   int pv_handle = -1;
   int ret = 0;
   ulong size = 0;
   char *buffer = NULL;
   char *pv_name = NULL;
   loff_t offset = 0;

   debug_enter ( "lv_init_COW_table -- CALLED for \%s\"\n",
                 lv != NULL ? lv->lv_name : "NULL");

   if ( vg == NULL ||
        lv == NULL ||
        vg_check_name ( vg->vg_name) < 0 ||
        lv_check_name ( lv->lv_name) < 0) ret = -LVM_EPARAM;
   else {
      size = SECTOR_SIZE;
      if ( ( buffer = malloc ( size)) == NULL) {
         fprintf ( stderr, "%s -- ERROR: malloc at line %d\n\n", cmd, __LINE__);
         ret = LVM_ELV_INIT_COW_TABLE_MALLOC;
      } else {
         memset ( buffer, 0, size);

         pv_name = pv_create_name_from_kdev_t ( lv->lv_current_pe[le].dev);
         if ( pv_name == NULL) {
            ret = -LVM_ELV_PV_CREATE_NAME_FROM_KDEV_T;
            goto lv_init_COW_table_end;
         }
         if ( ( pv_handle = open ( pv_name, O_WRONLY)) == -1) {
            ret = -LVM_ELV_INIT_COW_TABLE_OPEN;
            goto lv_init_COW_table_end;
         }                 

         offset = ( loff_t) lv->lv_current_pe[le].pe * SECTOR_SIZE;
         if ( llseek ( pv_handle, offset, SEEK_SET) == -1) {
            ret = -LVM_ELV_INIT_COW_TABLE_LLSEEK;
            goto lv_init_COW_table_end;
         }                 

         if ( write ( pv_handle, buffer, size) != size) {
            ret = -LVM_ELV_INIT_COW_TABLE_WRITE;
            goto lv_init_COW_table_end;
         }
      }
   }

lv_init_COW_table_end:
   if ( pv_handle != -1) {
      fsync ( pv_handle);
      if ( close ( pv_handle) < 0 && !ret) ret = -LVM_ELV_INIT_COW_TABLE_CLOSE;
      pv_flush ( pv_name);
   }
   if ( buffer != NULL) free ( buffer);

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