nlm_advlock.c revision 214048
1/*-
2 * Copyright (c) 2008 Isilon Inc http://www.isilon.com/
3 * Authors: Doug Rabson <dfr@rabson.org>
4 * Developed with Red Inc: Alfred Perlstein <alfred@freebsd.org>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27
28#include <sys/cdefs.h>
29__FBSDID("$FreeBSD: head/sys/nlm/nlm_advlock.c 214048 2010-10-19 00:20:00Z rmacklem $");
30
31#include <sys/param.h>
32#include <sys/fcntl.h>
33#include <sys/jail.h>
34#include <sys/kernel.h>
35#include <sys/limits.h>
36#include <sys/lock.h>
37#include <sys/lockf.h>
38#include <sys/malloc.h>
39#include <sys/mbuf.h>
40#include <sys/mount.h>
41#include <sys/mutex.h>
42#include <sys/proc.h>
43#include <sys/socket.h>
44#include <sys/syslog.h>
45#include <sys/systm.h>
46#include <sys/unistd.h>
47#include <sys/vnode.h>
48
49#include <nfs/nfsproto.h>
50#include <nfsclient/nfs.h>
51#include <nfsclient/nfsmount.h>
52
53#include <nlm/nlm_prot.h>
54#include <nlm/nlm.h>
55
56/*
57 * We need to keep track of the svid values used for F_FLOCK locks.
58 */
59struct nlm_file_svid {
60	int		ns_refs;	/* thread count + 1 if active */
61	int		ns_svid;	/* on-the-wire SVID for this file */
62	struct ucred	*ns_ucred;	/* creds to use for lock recovery */
63	void		*ns_id;		/* local struct file pointer */
64	bool_t		ns_active;	/* TRUE if we own a lock */
65	LIST_ENTRY(nlm_file_svid) ns_link;
66};
67LIST_HEAD(nlm_file_svid_list, nlm_file_svid);
68
69#define NLM_SVID_HASH_SIZE	256
70struct nlm_file_svid_list nlm_file_svids[NLM_SVID_HASH_SIZE];
71
72struct mtx nlm_svid_lock;
73static struct unrhdr *nlm_svid_allocator;
74static volatile u_int nlm_xid = 1;
75
76static int nlm_setlock(struct nlm_host *host, struct rpc_callextra *ext,
77    rpcvers_t vers, struct timeval *timo, int retries,
78    struct vnode *vp, int op, struct flock *fl, int flags,
79    int svid, size_t fhlen, void *fh, off_t size, bool_t reclaim);
80static int nlm_clearlock(struct nlm_host *host,  struct rpc_callextra *ext,
81    rpcvers_t vers, struct timeval *timo, int retries,
82    struct vnode *vp, int op, struct flock *fl, int flags,
83    int svid, size_t fhlen, void *fh, off_t size);
84static int nlm_getlock(struct nlm_host *host, struct rpc_callextra *ext,
85    rpcvers_t vers, struct timeval *timo, int retries,
86    struct vnode *vp, int op, struct flock *fl, int flags,
87    int svid, size_t fhlen, void *fh, off_t size);
88static int nlm_map_status(nlm4_stats stat);
89static struct nlm_file_svid *nlm_find_svid(void *id);
90static void nlm_free_svid(struct nlm_file_svid *nf);
91static int nlm_init_lock(struct flock *fl, int flags, int svid,
92    rpcvers_t vers, size_t fhlen, void *fh, off_t size,
93    struct nlm4_lock *lock, char oh_space[32]);
94
95static void
96nlm_client_init(void *dummy)
97{
98	int i;
99
100	mtx_init(&nlm_svid_lock, "NLM svid lock", NULL, MTX_DEF);
101	nlm_svid_allocator = new_unrhdr(PID_MAX + 2, INT_MAX, &nlm_svid_lock);
102	for (i = 0; i < NLM_SVID_HASH_SIZE; i++)
103		LIST_INIT(&nlm_file_svids[i]);
104}
105SYSINIT(nlm_client_init, SI_SUB_LOCK, SI_ORDER_FIRST, nlm_client_init, NULL);
106
107static int
108nlm_msg(struct thread *td, const char *server, const char *msg, int error)
109{
110	struct proc *p;
111
112	p = td ? td->td_proc : NULL;
113	if (error) {
114		tprintf(p, LOG_INFO, "nfs server %s: %s, error %d\n", server,
115		    msg, error);
116	} else {
117		tprintf(p, LOG_INFO, "nfs server %s: %s\n", server, msg);
118	}
119	return (0);
120}
121
122struct nlm_feedback_arg {
123	bool_t	nf_printed;
124	struct nfsmount *nf_nmp;
125};
126
127static void
128nlm_down(struct nlm_feedback_arg *nf, struct thread *td,
129    const char *msg, int error)
130{
131	struct nfsmount *nmp = nf->nf_nmp;
132
133	if (nmp == NULL)
134		return;
135	mtx_lock(&nmp->nm_mtx);
136	if (!(nmp->nm_state & NFSSTA_LOCKTIMEO)) {
137		nmp->nm_state |= NFSSTA_LOCKTIMEO;
138		mtx_unlock(&nmp->nm_mtx);
139		vfs_event_signal(&nmp->nm_mountp->mnt_stat.f_fsid,
140		    VQ_NOTRESPLOCK, 0);
141	} else {
142		mtx_unlock(&nmp->nm_mtx);
143	}
144
145	nf->nf_printed = TRUE;
146	nlm_msg(td, nmp->nm_mountp->mnt_stat.f_mntfromname, msg, error);
147}
148
149static void
150nlm_up(struct nlm_feedback_arg *nf, struct thread *td,
151    const char *msg)
152{
153	struct nfsmount *nmp = nf->nf_nmp;
154
155	if (!nf->nf_printed)
156		return;
157
158	nlm_msg(td, nmp->nm_mountp->mnt_stat.f_mntfromname, msg, 0);
159
160	mtx_lock(&nmp->nm_mtx);
161	if (nmp->nm_state & NFSSTA_LOCKTIMEO) {
162		nmp->nm_state &= ~NFSSTA_LOCKTIMEO;
163		mtx_unlock(&nmp->nm_mtx);
164		vfs_event_signal(&nmp->nm_mountp->mnt_stat.f_fsid,
165		    VQ_NOTRESPLOCK, 1);
166	} else {
167		mtx_unlock(&nmp->nm_mtx);
168	}
169}
170
171static void
172nlm_feedback(int type, int proc, void *arg)
173{
174	struct thread *td = curthread;
175	struct nlm_feedback_arg *nf = (struct nlm_feedback_arg *) arg;
176
177	switch (type) {
178	case FEEDBACK_REXMIT2:
179	case FEEDBACK_RECONNECT:
180		nlm_down(nf, td, "lockd not responding", 0);
181		break;
182
183	case FEEDBACK_OK:
184		nlm_up(nf, td, "lockd is alive again");
185		break;
186	}
187}
188
189/*
190 * nlm_advlock --
191 *      NFS advisory byte-level locks.
192 */
193static int
194nlm_advlock_internal(struct vnode *vp, void *id, int op, struct flock *fl,
195    int flags, bool_t reclaim, bool_t unlock_vp)
196{
197	struct thread *td = curthread;
198	struct nfsmount *nmp;
199	off_t size;
200	size_t fhlen;
201	union nfsfh fh;
202	struct sockaddr *sa;
203	struct sockaddr_storage ss;
204	char servername[MNAMELEN];
205	struct timeval timo;
206	int retries;
207	rpcvers_t vers;
208	struct nlm_host *host;
209	struct rpc_callextra ext;
210	struct nlm_feedback_arg nf;
211	AUTH *auth;
212	struct ucred *cred;
213	struct nlm_file_svid *ns;
214	int svid;
215	int error;
216	int is_v3;
217
218	ASSERT_VOP_LOCKED(vp, "nlm_advlock_1");
219
220	/*
221	 * Push any pending writes to the server and flush our cache
222	 * so that if we are contending with another machine for a
223	 * file, we get whatever they wrote and vice-versa.
224	 */
225	if (op == F_SETLK || op == F_UNLCK)
226		nfs_vinvalbuf(vp, V_SAVE, td, 1);
227
228	nmp = VFSTONFS(vp->v_mount);
229	strcpy(servername, nmp->nm_hostname);
230	nmp->nm_getinfo(vp, fh.fh_bytes, &fhlen, &ss, &is_v3, &size);
231	sa = (struct sockaddr *) &ss;
232	timo.tv_sec = nmp->nm_timeo / NFS_HZ;
233	timo.tv_usec = (nmp->nm_timeo % NFS_HZ) * (1000000 / NFS_HZ);
234	if (is_v3 != 0)
235		vers = NLM_VERS4;
236	else
237		vers = NLM_VERS;
238
239	if (nmp->nm_flag & NFSMNT_SOFT)
240		retries = nmp->nm_retry;
241	else
242		retries = INT_MAX;
243
244	if (unlock_vp)
245		VOP_UNLOCK(vp, 0);
246
247	/*
248	 * We need to switch to mount-point creds so that we can send
249	 * packets from a privileged port.
250	 */
251	cred = td->td_ucred;
252	td->td_ucred = vp->v_mount->mnt_cred;
253
254	host = nlm_find_host_by_name(servername, sa, vers);
255	auth = authunix_create(cred);
256	memset(&ext, 0, sizeof(ext));
257
258	nf.nf_printed = FALSE;
259	nf.nf_nmp = nmp;
260	ext.rc_auth = auth;
261
262	ext.rc_feedback = nlm_feedback;
263	ext.rc_feedback_arg = &nf;
264	ext.rc_timers = NULL;
265
266	ns = NULL;
267	if (flags & F_FLOCK) {
268		ns = nlm_find_svid(id);
269		KASSERT(fl->l_start == 0 && fl->l_len == 0,
270		    ("F_FLOCK lock requests must be whole-file locks"));
271		if (!ns->ns_ucred) {
272			/*
273			 * Remember the creds used for locking in case
274			 * we need to recover the lock later.
275			 */
276			ns->ns_ucred = crdup(cred);
277		}
278		svid = ns->ns_svid;
279	} else if (flags & F_REMOTE) {
280		/*
281		 * If we are recovering after a server restart or
282		 * trashing locks on a force unmount, use the same
283		 * svid as last time.
284		 */
285		svid = fl->l_pid;
286	} else {
287		svid = ((struct proc *) id)->p_pid;
288	}
289
290	switch(op) {
291	case F_SETLK:
292		if ((flags & (F_FLOCK|F_WAIT)) == (F_FLOCK|F_WAIT)
293		    && fl->l_type == F_WRLCK) {
294			/*
295			 * The semantics for flock(2) require that any
296			 * shared lock on the file must be released
297			 * before an exclusive lock is granted. The
298			 * local locking code interprets this by
299			 * unlocking the file before sleeping on a
300			 * blocked exclusive lock request. We
301			 * approximate this by first attempting
302			 * non-blocking and if that fails, we unlock
303			 * the file and block.
304			 */
305			error = nlm_setlock(host, &ext, vers, &timo, retries,
306			    vp, F_SETLK, fl, flags & ~F_WAIT,
307			    svid, fhlen, &fh.fh_bytes, size, reclaim);
308			if (error == EAGAIN) {
309				fl->l_type = F_UNLCK;
310				error = nlm_clearlock(host, &ext, vers, &timo,
311				    retries, vp, F_UNLCK, fl, flags,
312				    svid, fhlen, &fh.fh_bytes, size);
313				fl->l_type = F_WRLCK;
314				if (!error) {
315					mtx_lock(&nlm_svid_lock);
316					if (ns->ns_active) {
317						ns->ns_refs--;
318						ns->ns_active = FALSE;
319					}
320					mtx_unlock(&nlm_svid_lock);
321					flags |= F_WAIT;
322					error = nlm_setlock(host, &ext, vers,
323					    &timo, retries, vp, F_SETLK, fl,
324					    flags, svid, fhlen, &fh.fh_bytes,
325					    size, reclaim);
326				}
327			}
328		} else {
329			error = nlm_setlock(host, &ext, vers, &timo, retries,
330			    vp, op, fl, flags, svid, fhlen, &fh.fh_bytes,
331			    size, reclaim);
332		}
333		if (!error && ns) {
334			mtx_lock(&nlm_svid_lock);
335			if (!ns->ns_active) {
336				/*
337				 * Add one to the reference count to
338				 * hold onto the SVID for the lifetime
339				 * of the lock. Note that since
340				 * F_FLOCK only supports whole-file
341				 * locks, there can only be one active
342				 * lock for this SVID.
343				 */
344				ns->ns_refs++;
345				ns->ns_active = TRUE;
346			}
347			mtx_unlock(&nlm_svid_lock);
348		}
349		break;
350
351	case F_UNLCK:
352		error = nlm_clearlock(host, &ext, vers, &timo, retries,
353		    vp, op, fl, flags, svid, fhlen, &fh.fh_bytes, size);
354		if (!error && ns) {
355			mtx_lock(&nlm_svid_lock);
356			if (ns->ns_active) {
357				ns->ns_refs--;
358				ns->ns_active = FALSE;
359			}
360			mtx_unlock(&nlm_svid_lock);
361		}
362		break;
363
364	case F_GETLK:
365		error = nlm_getlock(host, &ext, vers, &timo, retries,
366		    vp, op, fl, flags, svid, fhlen, &fh.fh_bytes, size);
367		break;
368
369	default:
370		error = EINVAL;
371		break;
372	}
373
374	if (ns)
375		nlm_free_svid(ns);
376
377	td->td_ucred = cred;
378	AUTH_DESTROY(auth);
379
380	nlm_host_release(host);
381
382	return (error);
383}
384
385int
386nlm_advlock(struct vop_advlock_args *ap)
387{
388
389	return (nlm_advlock_internal(ap->a_vp, ap->a_id, ap->a_op, ap->a_fl,
390		ap->a_flags, FALSE, TRUE));
391}
392
393/*
394 * Set the creds of td to the creds of the given lock's owner. The new
395 * creds reference count will be incremented via crhold. The caller is
396 * responsible for calling crfree and restoring td's original creds.
397 */
398static void
399nlm_set_creds_for_lock(struct thread *td, struct flock *fl)
400{
401	int i;
402	struct nlm_file_svid *ns;
403	struct proc *p;
404	struct ucred *cred;
405
406	cred = NULL;
407	if (fl->l_pid > PID_MAX) {
408		/*
409		 * If this was originally a F_FLOCK-style lock, we
410		 * recorded the creds used when it was originally
411		 * locked in the nlm_file_svid structure.
412		 */
413		mtx_lock(&nlm_svid_lock);
414		for (i = 0; i < NLM_SVID_HASH_SIZE; i++) {
415			for (ns = LIST_FIRST(&nlm_file_svids[i]); ns;
416			     ns = LIST_NEXT(ns, ns_link)) {
417				if (ns->ns_svid == fl->l_pid) {
418					cred = crhold(ns->ns_ucred);
419					break;
420				}
421			}
422		}
423		mtx_unlock(&nlm_svid_lock);
424	} else {
425		/*
426		 * This lock is owned by a process. Get a reference to
427		 * the process creds.
428		 */
429		p = pfind(fl->l_pid);
430		if (p) {
431			cred = crhold(p->p_ucred);
432			PROC_UNLOCK(p);
433		}
434	}
435
436	/*
437	 * If we can't find a cred, fall back on the recovery
438	 * thread's cred.
439	 */
440	if (!cred) {
441		cred = crhold(td->td_ucred);
442	}
443
444	td->td_ucred = cred;
445}
446
447static int
448nlm_reclaim_free_lock(struct vnode *vp, struct flock *fl, void *arg)
449{
450	struct flock newfl;
451	struct thread *td = curthread;
452	struct ucred *oldcred;
453	int error;
454
455	newfl = *fl;
456	newfl.l_type = F_UNLCK;
457
458	oldcred = td->td_ucred;
459	nlm_set_creds_for_lock(td, &newfl);
460
461	error = nlm_advlock_internal(vp, NULL, F_UNLCK, &newfl, F_REMOTE,
462	    FALSE, FALSE);
463
464	crfree(td->td_ucred);
465	td->td_ucred = oldcred;
466
467	return (error);
468}
469
470int
471nlm_reclaim(struct vop_reclaim_args *ap)
472{
473
474	nlm_cancel_wait(ap->a_vp);
475	lf_iteratelocks_vnode(ap->a_vp, nlm_reclaim_free_lock, NULL);
476	return (0);
477}
478
479struct nlm_recovery_context {
480	struct nlm_host	*nr_host;	/* host we are recovering */
481	int		nr_state;	/* remote NSM state for recovery */
482};
483
484static int
485nlm_client_recover_lock(struct vnode *vp, struct flock *fl, void *arg)
486{
487	struct nlm_recovery_context *nr = (struct nlm_recovery_context *) arg;
488	struct thread *td = curthread;
489	struct ucred *oldcred;
490	int state, error;
491
492	/*
493	 * If the remote NSM state changes during recovery, the host
494	 * must have rebooted a second time. In that case, we must
495	 * restart the recovery.
496	 */
497	state = nlm_host_get_state(nr->nr_host);
498	if (nr->nr_state != state)
499		return (ERESTART);
500
501	error = vn_lock(vp, LK_SHARED);
502	if (error)
503		return (error);
504
505	oldcred = td->td_ucred;
506	nlm_set_creds_for_lock(td, fl);
507
508	error = nlm_advlock_internal(vp, NULL, F_SETLK, fl, F_REMOTE,
509	    TRUE, TRUE);
510
511	crfree(td->td_ucred);
512	td->td_ucred = oldcred;
513
514	return (error);
515}
516
517void
518nlm_client_recovery(struct nlm_host *host)
519{
520	struct nlm_recovery_context nr;
521	int sysid, error;
522
523	sysid = NLM_SYSID_CLIENT | nlm_host_get_sysid(host);
524	do {
525		nr.nr_host = host;
526		nr.nr_state = nlm_host_get_state(host);
527		error = lf_iteratelocks_sysid(sysid,
528		    nlm_client_recover_lock, &nr);
529	} while (error == ERESTART);
530}
531
532static void
533nlm_convert_to_nlm_lock(struct nlm_lock *dst, struct nlm4_lock *src)
534{
535
536	dst->caller_name = src->caller_name;
537	dst->fh = src->fh;
538	dst->oh = src->oh;
539	dst->svid = src->svid;
540	dst->l_offset = src->l_offset;
541	dst->l_len = src->l_len;
542}
543
544static void
545nlm_convert_to_nlm4_holder(struct nlm4_holder *dst, struct nlm_holder *src)
546{
547
548	dst->exclusive = src->exclusive;
549	dst->svid = src->svid;
550	dst->oh = src->oh;
551	dst->l_offset = src->l_offset;
552	dst->l_len = src->l_len;
553}
554
555static void
556nlm_convert_to_nlm4_res(struct nlm4_res *dst, struct nlm_res *src)
557{
558	dst->cookie = src->cookie;
559	dst->stat.stat = (enum nlm4_stats) src->stat.stat;
560}
561
562static enum clnt_stat
563nlm_test_rpc(rpcvers_t vers, nlm4_testargs *args, nlm4_testres *res, CLIENT *client,
564    struct rpc_callextra *ext, struct timeval timo)
565{
566	if (vers == NLM_VERS4) {
567		return nlm4_test_4(args, res, client, ext, timo);
568	} else {
569		nlm_testargs args1;
570		nlm_testres res1;
571		enum clnt_stat stat;
572
573		args1.cookie = args->cookie;
574		args1.exclusive = args->exclusive;
575		nlm_convert_to_nlm_lock(&args1.alock, &args->alock);
576		memset(&res1, 0, sizeof(res1));
577
578		stat = nlm_test_1(&args1, &res1, client, ext, timo);
579
580		if (stat == RPC_SUCCESS) {
581			res->cookie = res1.cookie;
582			res->stat.stat = (enum nlm4_stats) res1.stat.stat;
583			if (res1.stat.stat == nlm_denied)
584				nlm_convert_to_nlm4_holder(
585					&res->stat.nlm4_testrply_u.holder,
586					&res1.stat.nlm_testrply_u.holder);
587		}
588
589		return (stat);
590	}
591}
592
593static enum clnt_stat
594nlm_lock_rpc(rpcvers_t vers, nlm4_lockargs *args, nlm4_res *res, CLIENT *client,
595    struct rpc_callextra *ext, struct timeval timo)
596{
597	if (vers == NLM_VERS4) {
598		return nlm4_lock_4(args, res, client, ext, timo);
599	} else {
600		nlm_lockargs args1;
601		nlm_res res1;
602		enum clnt_stat stat;
603
604		args1.cookie = args->cookie;
605		args1.block = args->block;
606		args1.exclusive = args->exclusive;
607		nlm_convert_to_nlm_lock(&args1.alock, &args->alock);
608		args1.reclaim = args->reclaim;
609		args1.state = args->state;
610		memset(&res1, 0, sizeof(res1));
611
612		stat = nlm_lock_1(&args1, &res1, client, ext, timo);
613
614		if (stat == RPC_SUCCESS) {
615			nlm_convert_to_nlm4_res(res, &res1);
616		}
617
618		return (stat);
619	}
620}
621
622static enum clnt_stat
623nlm_cancel_rpc(rpcvers_t vers, nlm4_cancargs *args, nlm4_res *res, CLIENT *client,
624    struct rpc_callextra *ext, struct timeval timo)
625{
626	if (vers == NLM_VERS4) {
627		return nlm4_cancel_4(args, res, client, ext, timo);
628	} else {
629		nlm_cancargs args1;
630		nlm_res res1;
631		enum clnt_stat stat;
632
633		args1.cookie = args->cookie;
634		args1.block = args->block;
635		args1.exclusive = args->exclusive;
636		nlm_convert_to_nlm_lock(&args1.alock, &args->alock);
637		memset(&res1, 0, sizeof(res1));
638
639		stat = nlm_cancel_1(&args1, &res1, client, ext, timo);
640
641		if (stat == RPC_SUCCESS) {
642			nlm_convert_to_nlm4_res(res, &res1);
643		}
644
645		return (stat);
646	}
647}
648
649static enum clnt_stat
650nlm_unlock_rpc(rpcvers_t vers, nlm4_unlockargs *args, nlm4_res *res, CLIENT *client,
651    struct rpc_callextra *ext, struct timeval timo)
652{
653	if (vers == NLM_VERS4) {
654		return nlm4_unlock_4(args, res, client, ext, timo);
655	} else {
656		nlm_unlockargs args1;
657		nlm_res res1;
658		enum clnt_stat stat;
659
660		args1.cookie = args->cookie;
661		nlm_convert_to_nlm_lock(&args1.alock, &args->alock);
662		memset(&res1, 0, sizeof(res1));
663
664		stat = nlm_unlock_1(&args1, &res1, client, ext, timo);
665
666		if (stat == RPC_SUCCESS) {
667			nlm_convert_to_nlm4_res(res, &res1);
668		}
669
670		return (stat);
671	}
672}
673
674/*
675 * Called after a lock request (set or clear) succeeded. We record the
676 * details in the local lock manager. Note that since the remote
677 * server has granted the lock, we can be sure that it doesn't
678 * conflict with any other locks we have in the local lock manager.
679 *
680 * Since it is possible that host may also make NLM client requests to
681 * our NLM server, we use a different sysid value to record our own
682 * client locks.
683 *
684 * Note that since it is possible for us to receive replies from the
685 * server in a different order than the locks were granted (e.g. if
686 * many local threads are contending for the same lock), we must use a
687 * blocking operation when registering with the local lock manager.
688 * We expect that any actual wait will be rare and short hence we
689 * ignore signals for this.
690 */
691static void
692nlm_record_lock(struct vnode *vp, int op, struct flock *fl,
693    int svid, int sysid, off_t size)
694{
695	struct vop_advlockasync_args a;
696	struct flock newfl;
697	int error;
698
699	a.a_vp = vp;
700	a.a_id = NULL;
701	a.a_op = op;
702	a.a_fl = &newfl;
703	a.a_flags = F_REMOTE|F_WAIT|F_NOINTR;
704	a.a_task = NULL;
705	a.a_cookiep = NULL;
706	newfl.l_start = fl->l_start;
707	newfl.l_len = fl->l_len;
708	newfl.l_type = fl->l_type;
709	newfl.l_whence = fl->l_whence;
710	newfl.l_pid = svid;
711	newfl.l_sysid = NLM_SYSID_CLIENT | sysid;
712
713	error = lf_advlockasync(&a, &vp->v_lockf, size);
714	KASSERT(error == 0 || error == ENOENT,
715	    ("Failed to register NFS lock locally - error=%d", error));
716}
717
718static int
719nlm_setlock(struct nlm_host *host, struct rpc_callextra *ext,
720    rpcvers_t vers, struct timeval *timo, int retries,
721    struct vnode *vp, int op, struct flock *fl, int flags,
722    int svid, size_t fhlen, void *fh, off_t size, bool_t reclaim)
723{
724	struct nlm4_lockargs args;
725	char oh_space[32];
726	struct nlm4_res res;
727	u_int xid;
728	CLIENT *client;
729	enum clnt_stat stat;
730	int retry, block, exclusive;
731	void *wait_handle = NULL;
732	int error;
733
734	memset(&args, 0, sizeof(args));
735	memset(&res, 0, sizeof(res));
736
737	block = (flags & F_WAIT) ? TRUE : FALSE;
738	exclusive = (fl->l_type == F_WRLCK);
739
740	error = nlm_init_lock(fl, flags, svid, vers, fhlen, fh, size,
741	    &args.alock, oh_space);
742	if (error)
743		return (error);
744	args.block = block;
745	args.exclusive = exclusive;
746	args.reclaim = reclaim;
747	args.state = nlm_nsm_state;
748
749	retry = 5*hz;
750	for (;;) {
751		client = nlm_host_get_rpc(host, FALSE);
752		if (!client)
753			return (ENOLCK); /* XXX retry? */
754
755		if (block)
756			wait_handle = nlm_register_wait_lock(&args.alock, vp);
757
758		xid = atomic_fetchadd_int(&nlm_xid, 1);
759		args.cookie.n_len = sizeof(xid);
760		args.cookie.n_bytes = (char*) &xid;
761
762		stat = nlm_lock_rpc(vers, &args, &res, client, ext, *timo);
763
764		CLNT_RELEASE(client);
765
766		if (stat != RPC_SUCCESS) {
767			if (block)
768				nlm_deregister_wait_lock(wait_handle);
769			if (retries) {
770				retries--;
771				continue;
772			}
773			return (EINVAL);
774		}
775
776		/*
777		 * Free res.cookie.
778		 */
779		xdr_free((xdrproc_t) xdr_nlm4_res, &res);
780
781		if (block && res.stat.stat != nlm4_blocked)
782			nlm_deregister_wait_lock(wait_handle);
783
784		if (res.stat.stat == nlm4_denied_grace_period) {
785			/*
786			 * The server has recently rebooted and is
787			 * giving old clients a change to reclaim
788			 * their locks. Wait for a few seconds and try
789			 * again.
790			 */
791			error = tsleep(&args, PCATCH, "nlmgrace", retry);
792			if (error && error != EWOULDBLOCK)
793				return (error);
794			retry = 2*retry;
795			if (retry > 30*hz)
796				retry = 30*hz;
797			continue;
798		}
799
800		if (block && res.stat.stat == nlm4_blocked) {
801			/*
802			 * The server should call us back with a
803			 * granted message when the lock succeeds. In
804			 * order to deal with broken servers, lost
805			 * granted messages and server reboots, we
806			 * will also re-try every few seconds.
807			 */
808			error = nlm_wait_lock(wait_handle, retry);
809			if (error == EWOULDBLOCK) {
810				retry = 2*retry;
811				if (retry > 30*hz)
812					retry = 30*hz;
813				continue;
814			}
815			if (error) {
816				/*
817				 * We need to call the server to
818				 * cancel our lock request.
819				 */
820				nlm4_cancargs cancel;
821
822				memset(&cancel, 0, sizeof(cancel));
823
824				xid = atomic_fetchadd_int(&nlm_xid, 1);
825				cancel.cookie.n_len = sizeof(xid);
826				cancel.cookie.n_bytes = (char*) &xid;
827				cancel.block = block;
828				cancel.exclusive = exclusive;
829				cancel.alock = args.alock;
830
831				do {
832					client = nlm_host_get_rpc(host, FALSE);
833					if (!client)
834						/* XXX retry? */
835						return (ENOLCK);
836
837					stat = nlm_cancel_rpc(vers, &cancel,
838					    &res, client, ext, *timo);
839
840					CLNT_RELEASE(client);
841
842					if (stat != RPC_SUCCESS) {
843						/*
844						 * We need to cope
845						 * with temporary
846						 * network partitions
847						 * as well as server
848						 * reboots. This means
849						 * we have to keep
850						 * trying to cancel
851						 * until the server
852						 * wakes up again.
853						 */
854						pause("nlmcancel", 10*hz);
855					}
856				} while (stat != RPC_SUCCESS);
857
858				/*
859				 * Free res.cookie.
860				 */
861				xdr_free((xdrproc_t) xdr_nlm4_res, &res);
862
863				switch (res.stat.stat) {
864				case nlm_denied:
865					/*
866					 * There was nothing
867					 * to cancel. We are
868					 * going to go ahead
869					 * and assume we got
870					 * the lock.
871					 */
872					error = 0;
873					break;
874
875				case nlm4_denied_grace_period:
876					/*
877					 * The server has
878					 * recently rebooted -
879					 * treat this as a
880					 * successful
881					 * cancellation.
882					 */
883					break;
884
885				case nlm4_granted:
886					/*
887					 * We managed to
888					 * cancel.
889					 */
890					break;
891
892				default:
893					/*
894					 * Broken server
895					 * implementation -
896					 * can't really do
897					 * anything here.
898					 */
899					break;
900				}
901
902			}
903		} else {
904			error = nlm_map_status(res.stat.stat);
905		}
906
907		if (!error && !reclaim) {
908			nlm_record_lock(vp, op, fl, args.alock.svid,
909			    nlm_host_get_sysid(host), size);
910			nlm_host_monitor(host, 0);
911		}
912
913		return (error);
914	}
915}
916
917static int
918nlm_clearlock(struct nlm_host *host, struct rpc_callextra *ext,
919    rpcvers_t vers, struct timeval *timo, int retries,
920    struct vnode *vp, int op, struct flock *fl, int flags,
921    int svid, size_t fhlen, void *fh, off_t size)
922{
923	struct nlm4_unlockargs args;
924	char oh_space[32];
925	struct nlm4_res res;
926	u_int xid;
927	CLIENT *client;
928	enum clnt_stat stat;
929	int error;
930
931	memset(&args, 0, sizeof(args));
932	memset(&res, 0, sizeof(res));
933
934	error = nlm_init_lock(fl, flags, svid, vers, fhlen, fh, size,
935	    &args.alock, oh_space);
936	if (error)
937		return (error);
938
939	for (;;) {
940		client = nlm_host_get_rpc(host, FALSE);
941		if (!client)
942			return (ENOLCK); /* XXX retry? */
943
944		xid = atomic_fetchadd_int(&nlm_xid, 1);
945		args.cookie.n_len = sizeof(xid);
946		args.cookie.n_bytes = (char*) &xid;
947
948		stat = nlm_unlock_rpc(vers, &args, &res, client, ext, *timo);
949
950		CLNT_RELEASE(client);
951
952		if (stat != RPC_SUCCESS) {
953			if (retries) {
954				retries--;
955				continue;
956			}
957			return (EINVAL);
958		}
959
960		/*
961		 * Free res.cookie.
962		 */
963		xdr_free((xdrproc_t) xdr_nlm4_res, &res);
964
965		if (res.stat.stat == nlm4_denied_grace_period) {
966			/*
967			 * The server has recently rebooted and is
968			 * giving old clients a change to reclaim
969			 * their locks. Wait for a few seconds and try
970			 * again.
971			 */
972			error = tsleep(&args, PCATCH, "nlmgrace", 5*hz);
973			if (error && error != EWOULDBLOCK)
974				return (error);
975			continue;
976		}
977
978		/*
979		 * If we are being called via nlm_reclaim (which will
980		 * use the F_REMOTE flag), don't record the lock
981		 * operation in the local lock manager since the vnode
982		 * is going away.
983		 */
984		if (!(flags & F_REMOTE))
985			nlm_record_lock(vp, op, fl, args.alock.svid,
986			    nlm_host_get_sysid(host), size);
987
988		return (0);
989	}
990}
991
992static int
993nlm_getlock(struct nlm_host *host, struct rpc_callextra *ext,
994    rpcvers_t vers, struct timeval *timo, int retries,
995    struct vnode *vp, int op, struct flock *fl, int flags,
996    int svid, size_t fhlen, void *fh, off_t size)
997{
998	struct nlm4_testargs args;
999	char oh_space[32];
1000	struct nlm4_testres res;
1001	u_int xid;
1002	CLIENT *client;
1003	enum clnt_stat stat;
1004	int exclusive;
1005	int error;
1006
1007	KASSERT(!(flags & F_FLOCK), ("unexpected F_FLOCK for F_GETLK"));
1008
1009	memset(&args, 0, sizeof(args));
1010	memset(&res, 0, sizeof(res));
1011
1012	exclusive = (fl->l_type == F_WRLCK);
1013
1014	error = nlm_init_lock(fl, flags, svid, vers, fhlen, fh, size,
1015	    &args.alock, oh_space);
1016	if (error)
1017		return (error);
1018	args.exclusive = exclusive;
1019
1020	for (;;) {
1021		client = nlm_host_get_rpc(host, FALSE);
1022		if (!client)
1023			return (ENOLCK); /* XXX retry? */
1024
1025		xid = atomic_fetchadd_int(&nlm_xid, 1);
1026		args.cookie.n_len = sizeof(xid);
1027		args.cookie.n_bytes = (char*) &xid;
1028
1029		stat = nlm_test_rpc(vers, &args, &res, client, ext, *timo);
1030
1031		CLNT_RELEASE(client);
1032
1033		if (stat != RPC_SUCCESS) {
1034			if (retries) {
1035				retries--;
1036				continue;
1037			}
1038			return (EINVAL);
1039		}
1040
1041		if (res.stat.stat == nlm4_denied_grace_period) {
1042			/*
1043			 * The server has recently rebooted and is
1044			 * giving old clients a change to reclaim
1045			 * their locks. Wait for a few seconds and try
1046			 * again.
1047			 */
1048			xdr_free((xdrproc_t) xdr_nlm4_testres, &res);
1049			error = tsleep(&args, PCATCH, "nlmgrace", 5*hz);
1050			if (error && error != EWOULDBLOCK)
1051				return (error);
1052			continue;
1053		}
1054
1055		if (res.stat.stat == nlm4_denied) {
1056			struct nlm4_holder *h =
1057				&res.stat.nlm4_testrply_u.holder;
1058			fl->l_start = h->l_offset;
1059			fl->l_len = h->l_len;
1060			fl->l_pid = h->svid;
1061			if (h->exclusive)
1062				fl->l_type = F_WRLCK;
1063			else
1064				fl->l_type = F_RDLCK;
1065			fl->l_whence = SEEK_SET;
1066			fl->l_sysid = 0;
1067		} else {
1068			fl->l_type = F_UNLCK;
1069		}
1070
1071		xdr_free((xdrproc_t) xdr_nlm4_testres, &res);
1072
1073		return (0);
1074	}
1075}
1076
1077static int
1078nlm_map_status(nlm4_stats stat)
1079{
1080	switch (stat) {
1081	case nlm4_granted:
1082		return (0);
1083
1084	case nlm4_denied:
1085		return (EAGAIN);
1086
1087	case nlm4_denied_nolocks:
1088		return (ENOLCK);
1089
1090	case nlm4_deadlck:
1091		return (EDEADLK);
1092
1093	case nlm4_rofs:
1094		return (EROFS);
1095
1096	case nlm4_stale_fh:
1097		return (ESTALE);
1098
1099	case nlm4_fbig:
1100		return (EFBIG);
1101
1102	case nlm4_failed:
1103		return (EACCES);
1104
1105	default:
1106		return (EINVAL);
1107	}
1108}
1109
1110static struct nlm_file_svid *
1111nlm_find_svid(void *id)
1112{
1113	struct nlm_file_svid *ns, *newns;
1114	int h;
1115
1116	h = (((uintptr_t) id) >> 7) % NLM_SVID_HASH_SIZE;
1117
1118	mtx_lock(&nlm_svid_lock);
1119	LIST_FOREACH(ns, &nlm_file_svids[h], ns_link) {
1120		if (ns->ns_id == id) {
1121			ns->ns_refs++;
1122			break;
1123		}
1124	}
1125	mtx_unlock(&nlm_svid_lock);
1126	if (!ns) {
1127		int svid = alloc_unr(nlm_svid_allocator);
1128		newns = malloc(sizeof(struct nlm_file_svid), M_NLM,
1129		    M_WAITOK);
1130		newns->ns_refs = 1;
1131		newns->ns_id = id;
1132		newns->ns_svid = svid;
1133		newns->ns_ucred = NULL;
1134		newns->ns_active = FALSE;
1135
1136		/*
1137		 * We need to check for a race with some other
1138		 * thread allocating a svid for this file.
1139		 */
1140		mtx_lock(&nlm_svid_lock);
1141		LIST_FOREACH(ns, &nlm_file_svids[h], ns_link) {
1142			if (ns->ns_id == id) {
1143				ns->ns_refs++;
1144				break;
1145			}
1146		}
1147		if (ns) {
1148			mtx_unlock(&nlm_svid_lock);
1149			free_unr(nlm_svid_allocator, newns->ns_svid);
1150			free(newns, M_NLM);
1151		} else {
1152			LIST_INSERT_HEAD(&nlm_file_svids[h], newns,
1153			    ns_link);
1154			ns = newns;
1155			mtx_unlock(&nlm_svid_lock);
1156		}
1157	}
1158
1159	return (ns);
1160}
1161
1162static void
1163nlm_free_svid(struct nlm_file_svid *ns)
1164{
1165
1166	mtx_lock(&nlm_svid_lock);
1167	ns->ns_refs--;
1168	if (!ns->ns_refs) {
1169		KASSERT(!ns->ns_active, ("Freeing active SVID"));
1170		LIST_REMOVE(ns, ns_link);
1171		mtx_unlock(&nlm_svid_lock);
1172		free_unr(nlm_svid_allocator, ns->ns_svid);
1173		if (ns->ns_ucred)
1174			crfree(ns->ns_ucred);
1175		free(ns, M_NLM);
1176	} else {
1177		mtx_unlock(&nlm_svid_lock);
1178	}
1179}
1180
1181static int
1182nlm_init_lock(struct flock *fl, int flags, int svid,
1183    rpcvers_t vers, size_t fhlen, void *fh, off_t size,
1184    struct nlm4_lock *lock, char oh_space[32])
1185{
1186	size_t oh_len;
1187	off_t start, len;
1188
1189	if (fl->l_whence == SEEK_END) {
1190		if (size > OFF_MAX
1191		    || (fl->l_start > 0 && size > OFF_MAX - fl->l_start))
1192			return (EOVERFLOW);
1193		start = size + fl->l_start;
1194	} else if (fl->l_whence == SEEK_SET || fl->l_whence == SEEK_CUR) {
1195		start = fl->l_start;
1196	} else {
1197		return (EINVAL);
1198	}
1199	if (start < 0)
1200		return (EINVAL);
1201	if (fl->l_len < 0) {
1202		len = -fl->l_len;
1203		start -= len;
1204		if (start < 0)
1205			return (EINVAL);
1206	} else {
1207		len = fl->l_len;
1208	}
1209
1210	if (vers == NLM_VERS) {
1211		/*
1212		 * Enforce range limits on V1 locks
1213		 */
1214		if (start > 0xffffffffLL || len > 0xffffffffLL)
1215			return (EOVERFLOW);
1216	}
1217
1218	snprintf(oh_space, 32, "%d@", svid);
1219	oh_len = strlen(oh_space);
1220	getcredhostname(NULL, oh_space + oh_len, 32 - oh_len);
1221	oh_len = strlen(oh_space);
1222
1223	memset(lock, 0, sizeof(*lock));
1224	lock->caller_name = prison0.pr_hostname;
1225	lock->fh.n_len = fhlen;
1226	lock->fh.n_bytes = fh;
1227	lock->oh.n_len = oh_len;
1228	lock->oh.n_bytes = oh_space;
1229	lock->svid = svid;
1230	lock->l_offset = start;
1231	lock->l_len = len;
1232
1233	return (0);
1234}
1235