/*
 * tools/lib/pe_lock.c
 *
 * Copyright (C) 1997 - 2000  Heinz Mauelshagen, Germany
 *
 * June 1997
 * January,February 1999
 *
 *
 * 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()
 *
 */

#include <liblvm.h>

int pe_lock_internal ( char *, kdev_t, ulong, ushort, ushort, kdev_t, int);

int pe_lock ( char *vg_name, kdev_t dev, ulong pe,
              ushort vg_num, ushort lv_num, kdev_t lv_dev) {
   return pe_lock_internal ( vg_name, dev, pe, vg_num, lv_num, lv_dev, LOCK_PE);
}

int pe_unlock ( char *vg_name) {
   return pe_lock_internal ( vg_name, 0, 0, 0, 0, 0, UNLOCK_PE);
}

int pe_lock_internal ( char *vg_name, kdev_t dev, ulong pe,
                       ushort vg_num, ushort lv_num, kdev_t lv_dev, int lock) {
   int group = -1;
   int ret = 0;
   char group_file[NAME_LEN] = { 0, };
   pe_lock_req_t pe_lock_req;

#ifdef DEBUG
   debug ( "pe_lock_internal -- CALLED for %s\n", vg_name);
#endif

   if ( lock != LOCK_PE && lock != UNLOCK_PE) return -LVM_EPARAM;
   if ( vg_name == NULL || vg_check_name ( vg_name) < 0) return -LVM_EPARAM;
   if ( lock == LOCK_PE) {
      if ( dev == 0 || pe == 0 || lv_num == 0 || lv_dev == 0)
         return -LVM_EPARAM;
   }

   sprintf ( group_file, LVM_DIR_PREFIX "%s/group%c", vg_name, 0);
   if ( ( group = open ( group_file, O_RDONLY)) == -1) return -LVM_EPE_LOCK;

   pe_lock_req.lock = lock;
   if ( lock == LOCK_PE) {
      pe_lock_req.data.pv_dev = LOCK_PE;
      pe_lock_req.data.pv_dev = dev;
      pe_lock_req.data.lv_dev = lv_dev;
      pe_lock_req.data.pv_offset = pe;
   } else pe_lock_req.data.pv_dev = UNLOCK_PE;

   if ( ( ret = ioctl ( group,
                        PE_LOCK_UNLOCK,
                        &pe_lock_req)) == -1) ret = -errno;

   if ( group != -1) close ( group);

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