/*
 * tools/lib/pv_check_free.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * October 1997
 * May 1998
 * February 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
 *
 *    16/05/1998 - fixed bug for pe_count = FREE PE on PV in pv_check_free()
 *    31/01/2000 - use debug_enter()/debug_leave()
 *
 */

#include <liblvm.h>

int pv_check_free ( pv_t *pv, ulong pe_count, ulong *pe_start) {
   int ret = FALSE;
   ulong pe = 0;

#ifdef DEBUG
   debug_enter ( "pv_check_free -- CALLED\n");
#endif

   if ( pv == NULL || pe_count < 1)
      ret = -LVM_EPARAM;
   else if ( pv->pe_total - pv->pe_allocated >= pe_count) ret = TRUE;
   else                                                   ret = FALSE;

   if ( ret == TRUE && pe_start != NULL) {
      for ( pe = 0; pe < pv->pe_total; pe++) {
         if ( pv->pe[pe].lv_num == 0) {
            *pe_start = pe;
            break;
         }
      }
   }

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


int pv_check_free_contiguous ( pv_t *pv, ulong pe_count, ulong *pe_start) {
   int ret = FALSE;
   ulong pe = 0;
   ulong this_pe_count = 0;
   ulong this_pe_start = 0;

#ifdef DEBUG
   debug_enter ( "pv_check_free_contiguous -- CALLED\n");
#endif

   if ( pv == NULL || pe_count < 1) ret = -LVM_EPARAM;
   else {
      ret = pv_check_free ( pv, pe_count, &this_pe_start);
   
      if ( ret == TRUE && pe_start != NULL) {
         for ( pe = this_pe_start; pe < pv->pe_total; pe++) {
            if ( pv->pe[pe].lv_num == 0) this_pe_count++;
            else {
               this_pe_count = 0;
               this_pe_start = pe;
            }
            if ( this_pe_count == pe_count) break;
         }
         if ( this_pe_count == pe_count) *pe_start = this_pe_start;
         else                            ret = FALSE;
      }
   }

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