/*
 * tools/lib/lv_init_COW_table.c
 *
 * Copyright (C) 2000  Heinz Mauelshagen, Sistina Software
 *
 * July 2000
 *
 *
 * 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
 *
 */

#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;
   loff_t offset = 0;

#ifdef DEBUG
   debug_enter ( "lv_init_COW_table -- CALLED for \%s\"\n", lv->lv_name);
#endif

   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);


         if ( ( pv_handle = open ( pv_create_name_from_kdev_t ( lv->lv_current_pe[le].dev), 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 ( ( ret = llseek ( pv_handle, offset, SEEK_SET)) == -1) {
            ret = -LVM_ELV_INIT_COW_TABLE_LLSEEK;
            goto lv_init_COW_table_end;
         }                 

         if ( ( ret = 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 = -LVM_ELV_INIT_COW_TABLE_CLOSE;
   }
   if ( buffer != NULL) free ( buffer);

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