1  /* pthread_mutex_transfer_np.  Transfer mutex ownership to another thread.
       2     Hurd version.
       3     Copyright (C) 2016-2023 Free Software Foundation, Inc.
       4     This file is part of the GNU C Library.
       5  
       6     The GNU C Library is free software; you can redistribute it and/or
       7     modify it under the terms of the GNU Lesser General Public
       8     License as published by the Free Software Foundation; either
       9     version 2.1 of the License, or (at your option) any later version.
      10  
      11     The GNU C Library is distributed in the hope that it will be useful,
      12     but WITHOUT ANY WARRANTY; without even the implied warranty of
      13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      14     Lesser General Public License for more details.
      15  
      16     You should have received a copy of the GNU Lesser General Public
      17     License along with the GNU C Library;  if not, see
      18     <https://www.gnu.org/licenses/>.  */
      19  
      20  #include <pthread.h>
      21  #include <stdlib.h>
      22  #include <assert.h>
      23  #include <pt-internal.h>
      24  #include "pt-mutex.h"
      25  #include <hurdlock.h>
      26  
      27  int
      28  __pthread_mutex_transfer_np (pthread_mutex_t *mtxp, pthread_t th)
      29  {
      30    struct __pthread *self = _pthread_self ();
      31    struct __pthread *pt = __pthread_getid (th);
      32  
      33    if (pt == NULL)
      34      return ESRCH;
      35    else if (pt == self)
      36      return 0;
      37  
      38    int ret = 0;
      39    int flags = mtxp->__flags & GSYNC_SHARED;
      40  
      41    switch (MTX_TYPE (mtxp))
      42      {
      43      case PT_MTX_NORMAL:
      44        break;
      45  
      46      case PT_MTX_RECURSIVE:
      47      case PT_MTX_ERRORCHECK:
      48        if (!mtx_owned_p (mtxp, self, flags))
      49  	ret = EPERM;
      50        else
      51  	mtx_set_owner (mtxp, pt, flags);
      52  
      53        break;
      54  
      55      case PT_MTX_NORMAL | PTHREAD_MUTEX_ROBUST:
      56      case PT_MTX_RECURSIVE | PTHREAD_MUTEX_ROBUST:
      57      case PT_MTX_ERRORCHECK | PTHREAD_MUTEX_ROBUST:
      58        /* Note that this can be used to transfer an inconsistent
      59         * mutex as well. The new owner will still have the same
      60         * flags as the original. */
      61        if (mtxp->__owner_id != self->thread
      62  	  || (int) (mtxp->__lock & LLL_OWNER_MASK) != __getpid ())
      63  	ret = EPERM;
      64        else
      65  	mtxp->__owner_id = pt->thread;
      66  
      67        break;
      68  
      69      default:
      70        ret = EINVAL;
      71      }
      72  
      73    return ret;
      74  }
      75  
      76  weak_alias (__pthread_mutex_transfer_np, pthread_mutex_transfer_np)