/*
 * tools/lib/pe_lock.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Sistina Software
 *
 * June 1997
 * January,February 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
 *
 *    18/10/1997 - fixed open of group file (always opened LVM_DEV before)
 *    04/29/1998 - changed to new lv_create_kdev_t()
 *    26/01/1999 - made volume group directory prefix a preprocessor option
 *    16/02/1999 - avoided lv_create_kdev_t()
 *    31/01/2000 - use debug_enter()/debug_leave()
 *    08/06/2001 - clean up pe_lock/pe_unlock to hold LOCK/UNLOCK specifics
 *
 */

#include <liblvm.h>

static int pe_lock_internal ( char *vg_name, pe_lock_req_t *pe_lock_req)
{
   int ret;

   debug_enter ( "pe_lock_internal -- CALLED for %s\n", vg_name);

   if ( (ret = vg_check_name ( vg_name)) == 0) {
      char group_file[NAME_LEN];
      int group;

      memset ( group_file, 0, sizeof ( group_file));
      snprintf ( group_file, sizeof ( group_file) - 1,
                             LVM_DIR_PREFIX "%s/group", vg_name);

      if ( ( group = open ( group_file, O_RDONLY)) == -1)
         ret = -LVM_EPE_LOCK;
      else {
         if ( ( ret = ioctl ( group, PE_LOCK_UNLOCK, pe_lock_req)) == -1)
            ret = -errno;
         close(group);
      }
   }

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

int pe_lock ( char *vg_name, kdev_t dev, ulong pe,
              ushort vg_num, ushort lv_num, kdev_t lv_dev)
{
   pe_lock_req_t pe_lock_req;

   if (dev == 0 || pe == 0 || lv_num == 0 || lv_dev == 0)
      return -LVM_EPARAM;

   pe_lock_req.lock = LOCK_PE;
   pe_lock_req.data.pv_dev = dev;
   pe_lock_req.data.lv_dev = lv_dev;
   pe_lock_req.data.pv_offset = pe;

   return pe_lock_internal ( vg_name, &pe_lock_req);
}

int pe_unlock ( char *vg_name)
{
   pe_lock_req_t pe_lock_req;

   pe_lock_req.lock = UNLOCK_PE;
   return pe_lock_internal ( vg_name, &pe_lock_req);
}

