/*
 * tools/lib/lv_setup_for_reduce.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * March-May,November 1997
 * September 1999
 * January 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
 *
 */

/*
 * Changelog
 *
 *    29/10/1999 - fixed possible free() bug
 *    31/01/2000 - use debug_enter()/debug_leave()
 *
 */

#include <liblvm.h>

/*
 * setup structure for a logical volume size reduce
 */
int lv_setup_for_reduce ( char *vg_name, vg_t *vg, char *lv_name, uint size) {
   int l = 0;
   int ret = 0;
   uint pe = 0;
   pe_t *lv_current_pe_sav = NULL;
   pe_disk_t lv_pe = { 0, 0};

   debug_enter ( "lv_setup_for_reduce -- CALLED\n");

   if ( vg_name == NULL || vg == NULL || lv_name == NULL ||
        vg_check_name ( vg_name) < 0 || size == 0 ||
        lv_check_name ( lv_name) < 0) {
      ret = -LVM_EPARAM;
      goto lv_setup_for_reduce_end;
   }

   if ( ( l = lv_get_index_by_name ( vg, lv_name)) < 0) {
      ret = -LVM_ELV_SETUP_FOR_REDUCE_LV_INDEX;
      goto lv_setup_for_reduce_end;
   }
   debug ( "lv_setup_for_reduce -- size: %d  lv_current_le: %lu\n",
            size, vg->lv[l]->lv_current_le);
   pe = vg->lv[l]->lv_allocated_le - size / vg->pe_size;
   vg->pe_allocated -= pe;
   debug ( "lv_setup_for_reduce -- pe: %d\n", pe);
   lv_pe.lv_num = l + 1;
   if ( ( ret = pv_release_pe ( vg, &lv_pe, &pe, vg->lv[l]->lv_stripes)) < 0 ||
        pe != 0) {
      ret = -LVM_ESIZE;
      goto lv_setup_for_reduce_end;
   }
   debug ( "lv_setup_for_reduce -- AFTER pv_release_pe\n");
   vg->lv[l]->lv_allocated_le = vg->lv[l]->lv_current_le = size / vg->pe_size;
   vg->lv[l]->lv_size = size;

   lv_current_pe_sav = vg->lv[l]->lv_current_pe;
   if ( ( vg->lv[l]->lv_current_pe =
          realloc ( vg->lv[l]->lv_current_pe,
                    vg->lv[l]->lv_allocated_le *
                    sizeof ( pe_t))) == NULL) {
      free ( lv_current_pe_sav);
      fprintf ( stderr, "realloc error in %s [line %d]\n",
                        __FILE__, __LINE__);
      ret = -LVM_ELV_SETUP_FOR_REDUCE_MALLOC;
      goto lv_setup_for_reduce_end;
   }

lv_setup_for_reduce_end:

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