]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/fs/nfsserver/nfs_nfsdstate.c
MFS: r366050, r366117
[FreeBSD/FreeBSD.git] / sys / fs / nfsserver / nfs_nfsdstate.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2009 Rick Macklem, University of Guelph
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include "opt_inet.h"
34 #include "opt_inet6.h"
35 #include <sys/extattr.h>
36 #include <fs/nfs/nfsport.h>
37
38 struct nfsrv_stablefirst nfsrv_stablefirst;
39 int nfsrv_issuedelegs = 0;
40 int nfsrv_dolocallocks = 0;
41 struct nfsv4lock nfsv4rootfs_lock;
42 time_t nfsdev_time = 0;
43 int nfsrv_layouthashsize;
44 volatile int nfsrv_layoutcnt = 0;
45
46 extern int newnfs_numnfsd;
47 extern struct nfsstatsv1 nfsstatsv1;
48 extern int nfsrv_lease;
49 extern struct timeval nfsboottime;
50 extern u_int32_t newnfs_true, newnfs_false;
51 extern struct mtx nfsrv_dslock_mtx;
52 extern struct mtx nfsrv_recalllock_mtx;
53 extern struct mtx nfsrv_dontlistlock_mtx;
54 extern int nfsd_debuglevel;
55 extern u_int nfsrv_dsdirsize;
56 extern struct nfsdevicehead nfsrv_devidhead;
57 extern int nfsrv_doflexfile;
58 extern int nfsrv_maxpnfsmirror;
59 NFSV4ROOTLOCKMUTEX;
60 NFSSTATESPINLOCK;
61 extern struct nfsdontlisthead nfsrv_dontlisthead;
62 extern volatile int nfsrv_devidcnt;
63 extern struct nfslayouthead nfsrv_recalllisthead;
64 extern char *nfsrv_zeropnfsdat;
65
66 SYSCTL_DECL(_vfs_nfsd);
67 int     nfsrv_statehashsize = NFSSTATEHASHSIZE;
68 SYSCTL_INT(_vfs_nfsd, OID_AUTO, statehashsize, CTLFLAG_RDTUN,
69     &nfsrv_statehashsize, 0,
70     "Size of state hash table set via loader.conf");
71
72 int     nfsrv_clienthashsize = NFSCLIENTHASHSIZE;
73 SYSCTL_INT(_vfs_nfsd, OID_AUTO, clienthashsize, CTLFLAG_RDTUN,
74     &nfsrv_clienthashsize, 0,
75     "Size of client hash table set via loader.conf");
76
77 int     nfsrv_lockhashsize = NFSLOCKHASHSIZE;
78 SYSCTL_INT(_vfs_nfsd, OID_AUTO, fhhashsize, CTLFLAG_RDTUN,
79     &nfsrv_lockhashsize, 0,
80     "Size of file handle hash table set via loader.conf");
81
82 int     nfsrv_sessionhashsize = NFSSESSIONHASHSIZE;
83 SYSCTL_INT(_vfs_nfsd, OID_AUTO, sessionhashsize, CTLFLAG_RDTUN,
84     &nfsrv_sessionhashsize, 0,
85     "Size of session hash table set via loader.conf");
86
87 int     nfsrv_layouthighwater = NFSLAYOUTHIGHWATER;
88 SYSCTL_INT(_vfs_nfsd, OID_AUTO, layouthighwater, CTLFLAG_RDTUN,
89     &nfsrv_layouthighwater, 0,
90     "High water mark for number of layouts set via loader.conf");
91
92 static int      nfsrv_v4statelimit = NFSRV_V4STATELIMIT;
93 SYSCTL_INT(_vfs_nfsd, OID_AUTO, v4statelimit, CTLFLAG_RWTUN,
94     &nfsrv_v4statelimit, 0,
95     "High water limit for NFSv4 opens+locks+delegations");
96
97 static int      nfsrv_writedelegifpos = 0;
98 SYSCTL_INT(_vfs_nfsd, OID_AUTO, writedelegifpos, CTLFLAG_RW,
99     &nfsrv_writedelegifpos, 0,
100     "Issue a write delegation for read opens if possible");
101
102 static int      nfsrv_allowreadforwriteopen = 1;
103 SYSCTL_INT(_vfs_nfsd, OID_AUTO, allowreadforwriteopen, CTLFLAG_RW,
104     &nfsrv_allowreadforwriteopen, 0,
105     "Allow Reads to be done with Write Access StateIDs");
106
107 int     nfsrv_pnfsatime = 0;
108 SYSCTL_INT(_vfs_nfsd, OID_AUTO, pnfsstrictatime, CTLFLAG_RW,
109     &nfsrv_pnfsatime, 0,
110     "For pNFS service, do Getattr ops to keep atime up-to-date");
111
112 int     nfsrv_flexlinuxhack = 0;
113 SYSCTL_INT(_vfs_nfsd, OID_AUTO, flexlinuxhack, CTLFLAG_RW,
114     &nfsrv_flexlinuxhack, 0,
115     "For Linux clients, hack around Flex File Layout bug");
116
117 /*
118  * Hash lists for nfs V4.
119  */
120 struct nfsclienthashhead        *nfsclienthash;
121 struct nfslockhashhead          *nfslockhash;
122 struct nfssessionhash           *nfssessionhash;
123 struct nfslayouthash            *nfslayouthash;
124 volatile int nfsrv_dontlistlen = 0;
125
126 static u_int32_t nfsrv_openpluslock = 0, nfsrv_delegatecnt = 0;
127 static time_t nfsrvboottime;
128 static int nfsrv_returnoldstateid = 0, nfsrv_clients = 0;
129 static int nfsrv_clienthighwater = NFSRV_CLIENTHIGHWATER;
130 static int nfsrv_nogsscallback = 0;
131 static volatile int nfsrv_writedelegcnt = 0;
132 static int nfsrv_faildscnt;
133
134 /* local functions */
135 static void nfsrv_dumpaclient(struct nfsclient *clp,
136     struct nfsd_dumpclients *dumpp);
137 static void nfsrv_freeopenowner(struct nfsstate *stp, int cansleep,
138     NFSPROC_T *p);
139 static int nfsrv_freeopen(struct nfsstate *stp, vnode_t vp, int cansleep,
140     NFSPROC_T *p);
141 static void nfsrv_freelockowner(struct nfsstate *stp, vnode_t vp, int cansleep,
142     NFSPROC_T *p);
143 static void nfsrv_freeallnfslocks(struct nfsstate *stp, vnode_t vp,
144     int cansleep, NFSPROC_T *p);
145 static void nfsrv_freenfslock(struct nfslock *lop);
146 static void nfsrv_freenfslockfile(struct nfslockfile *lfp);
147 static void nfsrv_freedeleg(struct nfsstate *);
148 static int nfsrv_getstate(struct nfsclient *clp, nfsv4stateid_t *stateidp, 
149     u_int32_t flags, struct nfsstate **stpp);
150 static void nfsrv_getowner(struct nfsstatehead *hp, struct nfsstate *new_stp,
151     struct nfsstate **stpp);
152 static int nfsrv_getlockfh(vnode_t vp, u_short flags,
153     struct nfslockfile *new_lfp, fhandle_t *nfhp, NFSPROC_T *p);
154 static int nfsrv_getlockfile(u_short flags, struct nfslockfile **new_lfpp,
155     struct nfslockfile **lfpp, fhandle_t *nfhp, int lockit);
156 static void nfsrv_insertlock(struct nfslock *new_lop,
157     struct nfslock *insert_lop, struct nfsstate *stp, struct nfslockfile *lfp);
158 static void nfsrv_updatelock(struct nfsstate *stp, struct nfslock **new_lopp,
159     struct nfslock **other_lopp, struct nfslockfile *lfp);
160 static int nfsrv_getipnumber(u_char *cp);
161 static int nfsrv_checkrestart(nfsquad_t clientid, u_int32_t flags,
162     nfsv4stateid_t *stateidp, int specialid);
163 static int nfsrv_checkgrace(struct nfsrv_descript *nd, struct nfsclient *clp,
164     u_int32_t flags);
165 static int nfsrv_docallback(struct nfsclient *clp, int procnum,
166     nfsv4stateid_t *stateidp, int trunc, fhandle_t *fhp,
167     struct nfsvattr *nap, nfsattrbit_t *attrbitp, int laytype, NFSPROC_T *p);
168 static int nfsrv_cbcallargs(struct nfsrv_descript *nd, struct nfsclient *clp,
169     uint32_t callback, int op, const char *optag, struct nfsdsession **sepp);
170 static u_int32_t nfsrv_nextclientindex(void);
171 static u_int32_t nfsrv_nextstateindex(struct nfsclient *clp);
172 static void nfsrv_markstable(struct nfsclient *clp);
173 static void nfsrv_markreclaim(struct nfsclient *clp);
174 static int nfsrv_checkstable(struct nfsclient *clp);
175 static int nfsrv_clientconflict(struct nfsclient *clp, int *haslockp, struct 
176     vnode *vp, NFSPROC_T *p);
177 static int nfsrv_delegconflict(struct nfsstate *stp, int *haslockp,
178     NFSPROC_T *p, vnode_t vp);
179 static int nfsrv_cleandeleg(vnode_t vp, struct nfslockfile *lfp,
180     struct nfsclient *clp, int *haslockp, NFSPROC_T *p);
181 static int nfsrv_notsamecredname(struct nfsrv_descript *nd,
182     struct nfsclient *clp);
183 static time_t nfsrv_leaseexpiry(void);
184 static void nfsrv_delaydelegtimeout(struct nfsstate *stp);
185 static int nfsrv_checkseqid(struct nfsrv_descript *nd, u_int32_t seqid,
186     struct nfsstate *stp, struct nfsrvcache *op);
187 static int nfsrv_nootherstate(struct nfsstate *stp);
188 static int nfsrv_locallock(vnode_t vp, struct nfslockfile *lfp, int flags,
189     uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p);
190 static void nfsrv_localunlock(vnode_t vp, struct nfslockfile *lfp,
191     uint64_t init_first, uint64_t init_end, NFSPROC_T *p);
192 static int nfsrv_dolocal(vnode_t vp, struct nfslockfile *lfp, int flags,
193     int oldflags, uint64_t first, uint64_t end, struct nfslockconflict *cfp,
194     NFSPROC_T *p);
195 static void nfsrv_locallock_rollback(vnode_t vp, struct nfslockfile *lfp,
196     NFSPROC_T *p);
197 static void nfsrv_locallock_commit(struct nfslockfile *lfp, int flags,
198     uint64_t first, uint64_t end);
199 static void nfsrv_locklf(struct nfslockfile *lfp);
200 static void nfsrv_unlocklf(struct nfslockfile *lfp);
201 static struct nfsdsession *nfsrv_findsession(uint8_t *sessionid);
202 static int nfsrv_freesession(struct nfsdsession *sep, uint8_t *sessionid);
203 static int nfsv4_setcbsequence(struct nfsrv_descript *nd, struct nfsclient *clp,
204     int dont_replycache, struct nfsdsession **sepp);
205 static int nfsv4_getcbsession(struct nfsclient *clp, struct nfsdsession **sepp);
206 static int nfsrv_addlayout(struct nfsrv_descript *nd, struct nfslayout **lypp,
207     nfsv4stateid_t *stateidp, char *layp, int *layoutlenp, NFSPROC_T *p);
208 static void nfsrv_freelayout(struct nfslayouthead *lhp, struct nfslayout *lyp);
209 static void nfsrv_freelayoutlist(nfsquad_t clientid);
210 static void nfsrv_freelayouts(nfsquad_t *clid, fsid_t *fs, int laytype,
211     int iomode);
212 static void nfsrv_freealllayouts(void);
213 static void nfsrv_freedevid(struct nfsdevice *ds);
214 static int nfsrv_setdsserver(char *dspathp, char *mdspathp, NFSPROC_T *p,
215     struct nfsdevice **dsp);
216 static int nfsrv_delds(char *devid, NFSPROC_T *p);
217 static void nfsrv_deleteds(struct nfsdevice *fndds);
218 static void nfsrv_allocdevid(struct nfsdevice *ds, char *addr, char *dnshost);
219 static void nfsrv_freealldevids(void);
220 static void nfsrv_flexlayouterr(struct nfsrv_descript *nd, uint32_t *layp,
221     int maxcnt, NFSPROC_T *p);
222 static int nfsrv_recalllayout(nfsquad_t clid, nfsv4stateid_t *stateidp,
223     fhandle_t *fhp, struct nfslayout *lyp, int changed, int laytype,
224     NFSPROC_T *p);
225 static int nfsrv_findlayout(nfsquad_t *clientidp, fhandle_t *fhp, int laytype,
226     NFSPROC_T *, struct nfslayout **lypp);
227 static int nfsrv_fndclid(nfsquad_t *clidvec, nfsquad_t clid, int clidcnt);
228 static struct nfslayout *nfsrv_filelayout(struct nfsrv_descript *nd, int iomode,
229     fhandle_t *fhp, fhandle_t *dsfhp, char *devid, fsid_t fs);
230 static struct nfslayout *nfsrv_flexlayout(struct nfsrv_descript *nd, int iomode,
231     int mirrorcnt, fhandle_t *fhp, fhandle_t *dsfhp, char *devid, fsid_t fs);
232 static int nfsrv_dontlayout(fhandle_t *fhp);
233 static int nfsrv_createdsfile(vnode_t vp, fhandle_t *fhp, struct pnfsdsfile *pf,
234     vnode_t dvp, struct nfsdevice *ds, struct ucred *cred, NFSPROC_T *p,
235     vnode_t *tvpp);
236 static struct nfsdevice *nfsrv_findmirroredds(struct nfsmount *nmp);
237
238 /*
239  * Scan the client list for a match and either return the current one,
240  * create a new entry or return an error.
241  * If returning a non-error, the clp structure must either be linked into
242  * the client list or free'd.
243  */
244 int
245 nfsrv_setclient(struct nfsrv_descript *nd, struct nfsclient **new_clpp,
246     nfsquad_t *clientidp, nfsquad_t *confirmp, NFSPROC_T *p)
247 {
248         struct nfsclient *clp = NULL, *new_clp = *new_clpp;
249         int i, error = 0, ret;
250         struct nfsstate *stp, *tstp;
251 #ifdef INET
252         struct sockaddr_in *sin, *rin;
253 #endif
254 #ifdef INET6
255         struct sockaddr_in6 *sin6, *rin6;
256 #endif
257         struct nfsdsession *sep, *nsep;
258         int zapit = 0, gotit, hasstate = 0, igotlock;
259         static u_int64_t confirm_index = 0;
260
261         /*
262          * Check for state resource limit exceeded.
263          */
264         if (nfsrv_openpluslock > nfsrv_v4statelimit) {
265                 error = NFSERR_RESOURCE;
266                 goto out;
267         }
268
269         if (nfsrv_issuedelegs == 0 ||
270             ((nd->nd_flag & ND_GSS) != 0 && nfsrv_nogsscallback != 0))
271                 /*
272                  * Don't do callbacks when delegations are disabled or
273                  * for AUTH_GSS unless enabled via nfsrv_nogsscallback.
274                  * If establishing a callback connection is attempted
275                  * when a firewall is blocking the callback path, the
276                  * server may wait too long for the connect attempt to
277                  * succeed during the Open. Some clients, such as Linux,
278                  * may timeout and give up on the Open before the server
279                  * replies. Also, since AUTH_GSS callbacks are not
280                  * yet interoperability tested, they might cause the
281                  * server to crap out, if they get past the Init call to
282                  * the client.
283                  */
284                 new_clp->lc_program = 0;
285
286         /* Lock out other nfsd threads */
287         NFSLOCKV4ROOTMUTEX();
288         nfsv4_relref(&nfsv4rootfs_lock);
289         do {
290                 igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
291                     NFSV4ROOTLOCKMUTEXPTR, NULL);
292         } while (!igotlock);
293         NFSUNLOCKV4ROOTMUTEX();
294
295         /*
296          * Search for a match in the client list.
297          */
298         gotit = i = 0;
299         while (i < nfsrv_clienthashsize && !gotit) {
300             LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
301                 if (new_clp->lc_idlen == clp->lc_idlen &&
302                     !NFSBCMP(new_clp->lc_id, clp->lc_id, clp->lc_idlen)) {
303                         gotit = 1;
304                         break;
305                 }
306             }
307             if (gotit == 0)
308                 i++;
309         }
310         if (!gotit ||
311             (clp->lc_flags & (LCL_NEEDSCONFIRM | LCL_ADMINREVOKED))) {
312                 if ((nd->nd_flag & ND_NFSV41) != 0 && confirmp->lval[1] != 0) {
313                         /*
314                          * For NFSv4.1, if confirmp->lval[1] is non-zero, the
315                          * client is trying to update a confirmed clientid.
316                          */
317                         NFSLOCKV4ROOTMUTEX();
318                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
319                         NFSUNLOCKV4ROOTMUTEX();
320                         confirmp->lval[1] = 0;
321                         error = NFSERR_NOENT;
322                         goto out;
323                 }
324                 /*
325                  * Get rid of the old one.
326                  */
327                 if (i != nfsrv_clienthashsize) {
328                         LIST_REMOVE(clp, lc_hash);
329                         nfsrv_cleanclient(clp, p);
330                         nfsrv_freedeleglist(&clp->lc_deleg);
331                         nfsrv_freedeleglist(&clp->lc_olddeleg);
332                         zapit = 1;
333                 }
334                 /*
335                  * Add it after assigning a client id to it.
336                  */
337                 new_clp->lc_flags |= LCL_NEEDSCONFIRM;
338                 if ((nd->nd_flag & ND_NFSV41) != 0)
339                         new_clp->lc_confirm.lval[0] = confirmp->lval[0] =
340                             ++confirm_index;
341                 else
342                         confirmp->qval = new_clp->lc_confirm.qval =
343                             ++confirm_index;
344                 clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
345                     (u_int32_t)nfsrvboottime;
346                 clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
347                     nfsrv_nextclientindex();
348                 new_clp->lc_stateindex = 0;
349                 new_clp->lc_statemaxindex = 0;
350                 new_clp->lc_cbref = 0;
351                 new_clp->lc_expiry = nfsrv_leaseexpiry();
352                 LIST_INIT(&new_clp->lc_open);
353                 LIST_INIT(&new_clp->lc_deleg);
354                 LIST_INIT(&new_clp->lc_olddeleg);
355                 LIST_INIT(&new_clp->lc_session);
356                 for (i = 0; i < nfsrv_statehashsize; i++)
357                         LIST_INIT(&new_clp->lc_stateid[i]);
358                 LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
359                     lc_hash);
360                 nfsstatsv1.srvclients++;
361                 nfsrv_openpluslock++;
362                 nfsrv_clients++;
363                 NFSLOCKV4ROOTMUTEX();
364                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
365                 NFSUNLOCKV4ROOTMUTEX();
366                 if (zapit)
367                         nfsrv_zapclient(clp, p);
368                 *new_clpp = NULL;
369                 goto out;
370         }
371
372         /*
373          * Now, handle the cases where the id is already issued.
374          */
375         if (nfsrv_notsamecredname(nd, clp)) {
376             /*
377              * Check to see if there is expired state that should go away.
378              */
379             if (clp->lc_expiry < NFSD_MONOSEC &&
380                 (!LIST_EMPTY(&clp->lc_open) || !LIST_EMPTY(&clp->lc_deleg))) {
381                 nfsrv_cleanclient(clp, p);
382                 nfsrv_freedeleglist(&clp->lc_deleg);
383             }
384
385             /*
386              * If there is outstanding state, then reply NFSERR_CLIDINUSE per
387              * RFC3530 Sec. 8.1.2 last para.
388              */
389             if (!LIST_EMPTY(&clp->lc_deleg)) {
390                 hasstate = 1;
391             } else if (LIST_EMPTY(&clp->lc_open)) {
392                 hasstate = 0;
393             } else {
394                 hasstate = 0;
395                 /* Look for an Open on the OpenOwner */
396                 LIST_FOREACH(stp, &clp->lc_open, ls_list) {
397                     if (!LIST_EMPTY(&stp->ls_open)) {
398                         hasstate = 1;
399                         break;
400                     }
401                 }
402             }
403             if (hasstate) {
404                 /*
405                  * If the uid doesn't match, return NFSERR_CLIDINUSE after
406                  * filling out the correct ipaddr and portnum.
407                  */
408                 switch (clp->lc_req.nr_nam->sa_family) {
409 #ifdef INET
410                 case AF_INET:
411                         sin = (struct sockaddr_in *)new_clp->lc_req.nr_nam;
412                         rin = (struct sockaddr_in *)clp->lc_req.nr_nam;
413                         sin->sin_addr.s_addr = rin->sin_addr.s_addr;
414                         sin->sin_port = rin->sin_port;
415                         break;
416 #endif
417 #ifdef INET6
418                 case AF_INET6:
419                         sin6 = (struct sockaddr_in6 *)new_clp->lc_req.nr_nam;
420                         rin6 = (struct sockaddr_in6 *)clp->lc_req.nr_nam;
421                         sin6->sin6_addr = rin6->sin6_addr;
422                         sin6->sin6_port = rin6->sin6_port;
423                         break;
424 #endif
425                 }
426                 NFSLOCKV4ROOTMUTEX();
427                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
428                 NFSUNLOCKV4ROOTMUTEX();
429                 error = NFSERR_CLIDINUSE;
430                 goto out;
431             }
432         }
433
434         if (NFSBCMP(new_clp->lc_verf, clp->lc_verf, NFSX_VERF)) {
435                 /*
436                  * If the verifier has changed, the client has rebooted
437                  * and a new client id is issued. The old state info
438                  * can be thrown away once the SETCLIENTID_CONFIRM occurs.
439                  */
440                 LIST_REMOVE(clp, lc_hash);
441
442                 /* Get rid of all sessions on this clientid. */
443                 LIST_FOREACH_SAFE(sep, &clp->lc_session, sess_list, nsep) {
444                         ret = nfsrv_freesession(sep, NULL);
445                         if (ret != 0)
446                                 printf("nfsrv_setclient: verifier changed free"
447                                     " session failed=%d\n", ret);
448                 }
449
450                 new_clp->lc_flags |= LCL_NEEDSCONFIRM;
451                 if ((nd->nd_flag & ND_NFSV41) != 0)
452                         new_clp->lc_confirm.lval[0] = confirmp->lval[0] =
453                             ++confirm_index;
454                 else
455                         confirmp->qval = new_clp->lc_confirm.qval =
456                             ++confirm_index;
457                 clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
458                     nfsrvboottime;
459                 clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
460                     nfsrv_nextclientindex();
461                 new_clp->lc_stateindex = 0;
462                 new_clp->lc_statemaxindex = 0;
463                 new_clp->lc_cbref = 0;
464                 new_clp->lc_expiry = nfsrv_leaseexpiry();
465
466                 /*
467                  * Save the state until confirmed.
468                  */
469                 LIST_NEWHEAD(&new_clp->lc_open, &clp->lc_open, ls_list);
470                 LIST_FOREACH(tstp, &new_clp->lc_open, ls_list)
471                         tstp->ls_clp = new_clp;
472                 LIST_NEWHEAD(&new_clp->lc_deleg, &clp->lc_deleg, ls_list);
473                 LIST_FOREACH(tstp, &new_clp->lc_deleg, ls_list)
474                         tstp->ls_clp = new_clp;
475                 LIST_NEWHEAD(&new_clp->lc_olddeleg, &clp->lc_olddeleg,
476                     ls_list);
477                 LIST_FOREACH(tstp, &new_clp->lc_olddeleg, ls_list)
478                         tstp->ls_clp = new_clp;
479                 for (i = 0; i < nfsrv_statehashsize; i++) {
480                         LIST_NEWHEAD(&new_clp->lc_stateid[i],
481                             &clp->lc_stateid[i], ls_hash);
482                         LIST_FOREACH(tstp, &new_clp->lc_stateid[i], ls_hash)
483                                 tstp->ls_clp = new_clp;
484                 }
485                 LIST_INIT(&new_clp->lc_session);
486                 LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
487                     lc_hash);
488                 nfsstatsv1.srvclients++;
489                 nfsrv_openpluslock++;
490                 nfsrv_clients++;
491                 NFSLOCKV4ROOTMUTEX();
492                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
493                 NFSUNLOCKV4ROOTMUTEX();
494
495                 /*
496                  * Must wait until any outstanding callback on the old clp
497                  * completes.
498                  */
499                 NFSLOCKSTATE();
500                 while (clp->lc_cbref) {
501                         clp->lc_flags |= LCL_WAKEUPWANTED;
502                         (void)mtx_sleep(clp, NFSSTATEMUTEXPTR, PZERO - 1,
503                             "nfsd clp", 10 * hz);
504                 }
505                 NFSUNLOCKSTATE();
506                 nfsrv_zapclient(clp, p);
507                 *new_clpp = NULL;
508                 goto out;
509         }
510
511         /* For NFSv4.1, mark that we found a confirmed clientid. */
512         if ((nd->nd_flag & ND_NFSV41) != 0) {
513                 clientidp->lval[0] = clp->lc_clientid.lval[0];
514                 clientidp->lval[1] = clp->lc_clientid.lval[1];
515                 confirmp->lval[0] = 0;  /* Ignored by client */
516                 confirmp->lval[1] = 1;
517         } else {
518                 /*
519                  * id and verifier match, so update the net address info
520                  * and get rid of any existing callback authentication
521                  * handle, so a new one will be acquired.
522                  */
523                 LIST_REMOVE(clp, lc_hash);
524                 new_clp->lc_flags |= (LCL_NEEDSCONFIRM | LCL_DONTCLEAN);
525                 new_clp->lc_expiry = nfsrv_leaseexpiry();
526                 confirmp->qval = new_clp->lc_confirm.qval = ++confirm_index;
527                 clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
528                     clp->lc_clientid.lval[0];
529                 clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
530                     clp->lc_clientid.lval[1];
531                 new_clp->lc_delegtime = clp->lc_delegtime;
532                 new_clp->lc_stateindex = clp->lc_stateindex;
533                 new_clp->lc_statemaxindex = clp->lc_statemaxindex;
534                 new_clp->lc_cbref = 0;
535                 LIST_NEWHEAD(&new_clp->lc_open, &clp->lc_open, ls_list);
536                 LIST_FOREACH(tstp, &new_clp->lc_open, ls_list)
537                         tstp->ls_clp = new_clp;
538                 LIST_NEWHEAD(&new_clp->lc_deleg, &clp->lc_deleg, ls_list);
539                 LIST_FOREACH(tstp, &new_clp->lc_deleg, ls_list)
540                         tstp->ls_clp = new_clp;
541                 LIST_NEWHEAD(&new_clp->lc_olddeleg, &clp->lc_olddeleg, ls_list);
542                 LIST_FOREACH(tstp, &new_clp->lc_olddeleg, ls_list)
543                         tstp->ls_clp = new_clp;
544                 for (i = 0; i < nfsrv_statehashsize; i++) {
545                         LIST_NEWHEAD(&new_clp->lc_stateid[i],
546                             &clp->lc_stateid[i], ls_hash);
547                         LIST_FOREACH(tstp, &new_clp->lc_stateid[i], ls_hash)
548                                 tstp->ls_clp = new_clp;
549                 }
550                 LIST_INIT(&new_clp->lc_session);
551                 LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
552                     lc_hash);
553                 nfsstatsv1.srvclients++;
554                 nfsrv_openpluslock++;
555                 nfsrv_clients++;
556         }
557         NFSLOCKV4ROOTMUTEX();
558         nfsv4_unlock(&nfsv4rootfs_lock, 1);
559         NFSUNLOCKV4ROOTMUTEX();
560
561         if ((nd->nd_flag & ND_NFSV41) == 0) {
562                 /*
563                  * Must wait until any outstanding callback on the old clp
564                  * completes.
565                  */
566                 NFSLOCKSTATE();
567                 while (clp->lc_cbref) {
568                         clp->lc_flags |= LCL_WAKEUPWANTED;
569                         (void)mtx_sleep(clp, NFSSTATEMUTEXPTR, PZERO - 1,
570                             "nfsdclp", 10 * hz);
571                 }
572                 NFSUNLOCKSTATE();
573                 nfsrv_zapclient(clp, p);
574                 *new_clpp = NULL;
575         }
576
577 out:
578         NFSEXITCODE2(error, nd);
579         return (error);
580 }
581
582 /*
583  * Check to see if the client id exists and optionally confirm it.
584  */
585 int
586 nfsrv_getclient(nfsquad_t clientid, int opflags, struct nfsclient **clpp,
587     struct nfsdsession *nsep, nfsquad_t confirm, uint32_t cbprogram,
588     struct nfsrv_descript *nd, NFSPROC_T *p)
589 {
590         struct nfsclient *clp;
591         struct nfsstate *stp;
592         int i;
593         struct nfsclienthashhead *hp;
594         int error = 0, igotlock, doneok;
595         struct nfssessionhash *shp;
596         struct nfsdsession *sep;
597         uint64_t sessid[2];
598         static uint64_t next_sess = 0;
599
600         if (clpp)
601                 *clpp = NULL;
602         if ((nd == NULL || (nd->nd_flag & ND_NFSV41) == 0 ||
603             opflags != CLOPS_RENEW) && nfsrvboottime != clientid.lval[0]) {
604                 error = NFSERR_STALECLIENTID;
605                 goto out;
606         }
607
608         /*
609          * If called with opflags == CLOPS_RENEW, the State Lock is
610          * already held. Otherwise, we need to get either that or,
611          * for the case of Confirm, lock out the nfsd threads.
612          */
613         if (opflags & CLOPS_CONFIRM) {
614                 NFSLOCKV4ROOTMUTEX();
615                 nfsv4_relref(&nfsv4rootfs_lock);
616                 do {
617                         igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
618                             NFSV4ROOTLOCKMUTEXPTR, NULL);
619                 } while (!igotlock);
620                 /*
621                  * Create a new sessionid here, since we need to do it where
622                  * there is a mutex held to serialize update of next_sess.
623                  */
624                 if ((nd->nd_flag & ND_NFSV41) != 0) {
625                         sessid[0] = ++next_sess;
626                         sessid[1] = clientid.qval;
627                 }
628                 NFSUNLOCKV4ROOTMUTEX();
629         } else if (opflags != CLOPS_RENEW) {
630                 NFSLOCKSTATE();
631         }
632
633         /* For NFSv4.1, the clp is acquired from the associated session. */
634         if (nd != NULL && (nd->nd_flag & ND_NFSV41) != 0 &&
635             opflags == CLOPS_RENEW) {
636                 clp = NULL;
637                 if ((nd->nd_flag & ND_HASSEQUENCE) != 0) {
638                         shp = NFSSESSIONHASH(nd->nd_sessionid);
639                         NFSLOCKSESSION(shp);
640                         sep = nfsrv_findsession(nd->nd_sessionid);
641                         if (sep != NULL)
642                                 clp = sep->sess_clp;
643                         NFSUNLOCKSESSION(shp);
644                 }
645         } else {
646                 hp = NFSCLIENTHASH(clientid);
647                 LIST_FOREACH(clp, hp, lc_hash) {
648                         if (clp->lc_clientid.lval[1] == clientid.lval[1])
649                                 break;
650                 }
651         }
652         if (clp == NULL) {
653                 if (opflags & CLOPS_CONFIRM)
654                         error = NFSERR_STALECLIENTID;
655                 else
656                         error = NFSERR_EXPIRED;
657         } else if (clp->lc_flags & LCL_ADMINREVOKED) {
658                 /*
659                  * If marked admin revoked, just return the error.
660                  */
661                 error = NFSERR_ADMINREVOKED;
662         }
663         if (error) {
664                 if (opflags & CLOPS_CONFIRM) {
665                         NFSLOCKV4ROOTMUTEX();
666                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
667                         NFSUNLOCKV4ROOTMUTEX();
668                 } else if (opflags != CLOPS_RENEW) {
669                         NFSUNLOCKSTATE();
670                 }
671                 goto out;
672         }
673
674         /*
675          * Perform any operations specified by the opflags.
676          */
677         if (opflags & CLOPS_CONFIRM) {
678                 if (((nd->nd_flag & ND_NFSV41) != 0 &&
679                      clp->lc_confirm.lval[0] != confirm.lval[0]) ||
680                     ((nd->nd_flag & ND_NFSV41) == 0 &&
681                      clp->lc_confirm.qval != confirm.qval))
682                         error = NFSERR_STALECLIENTID;
683                 else if (nfsrv_notsamecredname(nd, clp))
684                         error = NFSERR_CLIDINUSE;
685
686                 if (!error) {
687                     if ((clp->lc_flags & (LCL_NEEDSCONFIRM | LCL_DONTCLEAN)) ==
688                         LCL_NEEDSCONFIRM) {
689                         /*
690                          * Hang onto the delegations (as old delegations)
691                          * for an Open with CLAIM_DELEGATE_PREV unless in
692                          * grace, but get rid of the rest of the state.
693                          */
694                         nfsrv_cleanclient(clp, p);
695                         nfsrv_freedeleglist(&clp->lc_olddeleg);
696                         if (nfsrv_checkgrace(nd, clp, 0)) {
697                             /* In grace, so just delete delegations */
698                             nfsrv_freedeleglist(&clp->lc_deleg);
699                         } else {
700                             LIST_FOREACH(stp, &clp->lc_deleg, ls_list)
701                                 stp->ls_flags |= NFSLCK_OLDDELEG;
702                             clp->lc_delegtime = NFSD_MONOSEC +
703                                 nfsrv_lease + NFSRV_LEASEDELTA;
704                             LIST_NEWHEAD(&clp->lc_olddeleg, &clp->lc_deleg,
705                                 ls_list);
706                         }
707                         if ((nd->nd_flag & ND_NFSV41) != 0)
708                             clp->lc_program = cbprogram;
709                     }
710                     clp->lc_flags &= ~(LCL_NEEDSCONFIRM | LCL_DONTCLEAN);
711                     if (clp->lc_program)
712                         clp->lc_flags |= LCL_NEEDSCBNULL;
713                     /* For NFSv4.1, link the session onto the client. */
714                     if (nsep != NULL) {
715                         /* Hold a reference on the xprt for a backchannel. */
716                         if ((nsep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN)
717                             != 0) {
718                             if (clp->lc_req.nr_client == NULL)
719                                 clp->lc_req.nr_client = (struct __rpc_client *)
720                                     clnt_bck_create(nd->nd_xprt->xp_socket,
721                                     cbprogram, NFSV4_CBVERS);
722                             if (clp->lc_req.nr_client != NULL) {
723                                 SVC_ACQUIRE(nd->nd_xprt);
724                                 nd->nd_xprt->xp_p2 =
725                                     clp->lc_req.nr_client->cl_private;
726                                 /* Disable idle timeout. */
727                                 nd->nd_xprt->xp_idletimeout = 0;
728                                 nsep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
729                             } else
730                                 nsep->sess_crflags &= ~NFSV4CRSESS_CONNBACKCHAN;
731                         }
732                         NFSBCOPY(sessid, nsep->sess_sessionid,
733                             NFSX_V4SESSIONID);
734                         NFSBCOPY(sessid, nsep->sess_cbsess.nfsess_sessionid,
735                             NFSX_V4SESSIONID);
736                         shp = NFSSESSIONHASH(nsep->sess_sessionid);
737                         NFSLOCKSTATE();
738                         NFSLOCKSESSION(shp);
739                         LIST_INSERT_HEAD(&shp->list, nsep, sess_hash);
740                         LIST_INSERT_HEAD(&clp->lc_session, nsep, sess_list);
741                         nsep->sess_clp = clp;
742                         NFSUNLOCKSESSION(shp);
743                         NFSUNLOCKSTATE();
744                     }
745                 }
746         } else if (clp->lc_flags & LCL_NEEDSCONFIRM) {
747                 error = NFSERR_EXPIRED;
748         }
749
750         /*
751          * If called by the Renew Op, we must check the principal.
752          */
753         if (!error && (opflags & CLOPS_RENEWOP)) {
754             if (nfsrv_notsamecredname(nd, clp)) {
755                 doneok = 0;
756                 for (i = 0; i < nfsrv_statehashsize && doneok == 0; i++) {
757                     LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
758                         if ((stp->ls_flags & NFSLCK_OPEN) &&
759                             stp->ls_uid == nd->nd_cred->cr_uid) {
760                                 doneok = 1;
761                                 break;
762                         }
763                     }
764                 }
765                 if (!doneok)
766                         error = NFSERR_ACCES;
767             }
768             if (!error && (clp->lc_flags & LCL_CBDOWN))
769                 error = NFSERR_CBPATHDOWN;
770         }
771         if ((!error || error == NFSERR_CBPATHDOWN) &&
772              (opflags & CLOPS_RENEW)) {
773                 clp->lc_expiry = nfsrv_leaseexpiry();
774         }
775         if (opflags & CLOPS_CONFIRM) {
776                 NFSLOCKV4ROOTMUTEX();
777                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
778                 NFSUNLOCKV4ROOTMUTEX();
779         } else if (opflags != CLOPS_RENEW) {
780                 NFSUNLOCKSTATE();
781         }
782         if (clpp)
783                 *clpp = clp;
784
785 out:
786         NFSEXITCODE2(error, nd);
787         return (error);
788 }
789
790 /*
791  * Perform the NFSv4.1 destroy clientid.
792  */
793 int
794 nfsrv_destroyclient(nfsquad_t clientid, NFSPROC_T *p)
795 {
796         struct nfsclient *clp;
797         struct nfsclienthashhead *hp;
798         int error = 0, i, igotlock;
799
800         if (nfsrvboottime != clientid.lval[0]) {
801                 error = NFSERR_STALECLIENTID;
802                 goto out;
803         }
804
805         /* Lock out other nfsd threads */
806         NFSLOCKV4ROOTMUTEX();
807         nfsv4_relref(&nfsv4rootfs_lock);
808         do {
809                 igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
810                     NFSV4ROOTLOCKMUTEXPTR, NULL);
811         } while (igotlock == 0);
812         NFSUNLOCKV4ROOTMUTEX();
813
814         hp = NFSCLIENTHASH(clientid);
815         LIST_FOREACH(clp, hp, lc_hash) {
816                 if (clp->lc_clientid.lval[1] == clientid.lval[1])
817                         break;
818         }
819         if (clp == NULL) {
820                 NFSLOCKV4ROOTMUTEX();
821                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
822                 NFSUNLOCKV4ROOTMUTEX();
823                 /* Just return ok, since it is gone. */
824                 goto out;
825         }
826
827         /*
828          * Free up all layouts on the clientid.  Should the client return the
829          * layouts?
830          */
831         nfsrv_freelayoutlist(clientid);
832
833         /* Scan for state on the clientid. */
834         for (i = 0; i < nfsrv_statehashsize; i++)
835                 if (!LIST_EMPTY(&clp->lc_stateid[i])) {
836                         NFSLOCKV4ROOTMUTEX();
837                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
838                         NFSUNLOCKV4ROOTMUTEX();
839                         error = NFSERR_CLIENTIDBUSY;
840                         goto out;
841                 }
842         if (!LIST_EMPTY(&clp->lc_session) || !LIST_EMPTY(&clp->lc_deleg)) {
843                 NFSLOCKV4ROOTMUTEX();
844                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
845                 NFSUNLOCKV4ROOTMUTEX();
846                 error = NFSERR_CLIENTIDBUSY;
847                 goto out;
848         }
849
850         /* Destroy the clientid and return ok. */
851         nfsrv_cleanclient(clp, p);
852         nfsrv_freedeleglist(&clp->lc_deleg);
853         nfsrv_freedeleglist(&clp->lc_olddeleg);
854         LIST_REMOVE(clp, lc_hash);
855         NFSLOCKV4ROOTMUTEX();
856         nfsv4_unlock(&nfsv4rootfs_lock, 1);
857         NFSUNLOCKV4ROOTMUTEX();
858         nfsrv_zapclient(clp, p);
859 out:
860         NFSEXITCODE2(error, nd);
861         return (error);
862 }
863
864 /*
865  * Called from the new nfssvc syscall to admin revoke a clientid.
866  * Returns 0 for success, error otherwise.
867  */
868 int
869 nfsrv_adminrevoke(struct nfsd_clid *revokep, NFSPROC_T *p)
870 {
871         struct nfsclient *clp = NULL;
872         int i, error = 0;
873         int gotit, igotlock;
874
875         /*
876          * First, lock out the nfsd so that state won't change while the
877          * revocation record is being written to the stable storage restart
878          * file.
879          */
880         NFSLOCKV4ROOTMUTEX();
881         do {
882                 igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
883                     NFSV4ROOTLOCKMUTEXPTR, NULL);
884         } while (!igotlock);
885         NFSUNLOCKV4ROOTMUTEX();
886
887         /*
888          * Search for a match in the client list.
889          */
890         gotit = i = 0;
891         while (i < nfsrv_clienthashsize && !gotit) {
892             LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
893                 if (revokep->nclid_idlen == clp->lc_idlen &&
894                     !NFSBCMP(revokep->nclid_id, clp->lc_id, clp->lc_idlen)) {
895                         gotit = 1;
896                         break;
897                 }
898             }
899             i++;
900         }
901         if (!gotit) {
902                 NFSLOCKV4ROOTMUTEX();
903                 nfsv4_unlock(&nfsv4rootfs_lock, 0);
904                 NFSUNLOCKV4ROOTMUTEX();
905                 error = EPERM;
906                 goto out;
907         }
908
909         /*
910          * Now, write out the revocation record
911          */
912         nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
913         nfsrv_backupstable();
914
915         /*
916          * and clear out the state, marking the clientid revoked.
917          */
918         clp->lc_flags &= ~LCL_CALLBACKSON;
919         clp->lc_flags |= LCL_ADMINREVOKED;
920         nfsrv_cleanclient(clp, p);
921         nfsrv_freedeleglist(&clp->lc_deleg);
922         nfsrv_freedeleglist(&clp->lc_olddeleg);
923         NFSLOCKV4ROOTMUTEX();
924         nfsv4_unlock(&nfsv4rootfs_lock, 0);
925         NFSUNLOCKV4ROOTMUTEX();
926
927 out:
928         NFSEXITCODE(error);
929         return (error);
930 }
931
932 /*
933  * Dump out stats for all clients. Called from nfssvc(2), that is used
934  * nfsstatsv1.
935  */
936 void
937 nfsrv_dumpclients(struct nfsd_dumpclients *dumpp, int maxcnt)
938 {
939         struct nfsclient *clp;
940         int i = 0, cnt = 0;
941
942         /*
943          * First, get a reference on the nfsv4rootfs_lock so that an
944          * exclusive lock cannot be acquired while dumping the clients.
945          */
946         NFSLOCKV4ROOTMUTEX();
947         nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
948         NFSUNLOCKV4ROOTMUTEX();
949         NFSLOCKSTATE();
950         /*
951          * Rattle through the client lists until done.
952          */
953         while (i < nfsrv_clienthashsize && cnt < maxcnt) {
954             clp = LIST_FIRST(&nfsclienthash[i]);
955             while (clp != LIST_END(&nfsclienthash[i]) && cnt < maxcnt) {
956                 nfsrv_dumpaclient(clp, &dumpp[cnt]);
957                 cnt++;
958                 clp = LIST_NEXT(clp, lc_hash);
959             }
960             i++;
961         }
962         if (cnt < maxcnt)
963             dumpp[cnt].ndcl_clid.nclid_idlen = 0;
964         NFSUNLOCKSTATE();
965         NFSLOCKV4ROOTMUTEX();
966         nfsv4_relref(&nfsv4rootfs_lock);
967         NFSUNLOCKV4ROOTMUTEX();
968 }
969
970 /*
971  * Dump stats for a client. Must be called with the NFSSTATELOCK and spl'd.
972  */
973 static void
974 nfsrv_dumpaclient(struct nfsclient *clp, struct nfsd_dumpclients *dumpp)
975 {
976         struct nfsstate *stp, *openstp, *lckownstp;
977         struct nfslock *lop;
978         sa_family_t af;
979 #ifdef INET
980         struct sockaddr_in *rin;
981 #endif
982 #ifdef INET6
983         struct sockaddr_in6 *rin6;
984 #endif
985
986         dumpp->ndcl_nopenowners = dumpp->ndcl_nlockowners = 0;
987         dumpp->ndcl_nopens = dumpp->ndcl_nlocks = 0;
988         dumpp->ndcl_ndelegs = dumpp->ndcl_nolddelegs = 0;
989         dumpp->ndcl_flags = clp->lc_flags;
990         dumpp->ndcl_clid.nclid_idlen = clp->lc_idlen;
991         NFSBCOPY(clp->lc_id, dumpp->ndcl_clid.nclid_id, clp->lc_idlen);
992         af = clp->lc_req.nr_nam->sa_family;
993         dumpp->ndcl_addrfam = af;
994         switch (af) {
995 #ifdef INET
996         case AF_INET:
997                 rin = (struct sockaddr_in *)clp->lc_req.nr_nam;
998                 dumpp->ndcl_cbaddr.sin_addr = rin->sin_addr;
999                 break;
1000 #endif
1001 #ifdef INET6
1002         case AF_INET6:
1003                 rin6 = (struct sockaddr_in6 *)clp->lc_req.nr_nam;
1004                 dumpp->ndcl_cbaddr.sin6_addr = rin6->sin6_addr;
1005                 break;
1006 #endif
1007         }
1008
1009         /*
1010          * Now, scan the state lists and total up the opens and locks.
1011          */
1012         LIST_FOREACH(stp, &clp->lc_open, ls_list) {
1013             dumpp->ndcl_nopenowners++;
1014             LIST_FOREACH(openstp, &stp->ls_open, ls_list) {
1015                 dumpp->ndcl_nopens++;
1016                 LIST_FOREACH(lckownstp, &openstp->ls_open, ls_list) {
1017                     dumpp->ndcl_nlockowners++;
1018                     LIST_FOREACH(lop, &lckownstp->ls_lock, lo_lckowner) {
1019                         dumpp->ndcl_nlocks++;
1020                     }
1021                 }
1022             }
1023         }
1024
1025         /*
1026          * and the delegation lists.
1027          */
1028         LIST_FOREACH(stp, &clp->lc_deleg, ls_list) {
1029             dumpp->ndcl_ndelegs++;
1030         }
1031         LIST_FOREACH(stp, &clp->lc_olddeleg, ls_list) {
1032             dumpp->ndcl_nolddelegs++;
1033         }
1034 }
1035
1036 /*
1037  * Dump out lock stats for a file.
1038  */
1039 void
1040 nfsrv_dumplocks(vnode_t vp, struct nfsd_dumplocks *ldumpp, int maxcnt,
1041     NFSPROC_T *p)
1042 {
1043         struct nfsstate *stp;
1044         struct nfslock *lop;
1045         int cnt = 0;
1046         struct nfslockfile *lfp;
1047         sa_family_t af;
1048 #ifdef INET
1049         struct sockaddr_in *rin;
1050 #endif
1051 #ifdef INET6
1052         struct sockaddr_in6 *rin6;
1053 #endif
1054         int ret;
1055         fhandle_t nfh;
1056
1057         ret = nfsrv_getlockfh(vp, 0, NULL, &nfh, p);
1058         /*
1059          * First, get a reference on the nfsv4rootfs_lock so that an
1060          * exclusive lock on it cannot be acquired while dumping the locks.
1061          */
1062         NFSLOCKV4ROOTMUTEX();
1063         nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
1064         NFSUNLOCKV4ROOTMUTEX();
1065         NFSLOCKSTATE();
1066         if (!ret)
1067                 ret = nfsrv_getlockfile(0, NULL, &lfp, &nfh, 0);
1068         if (ret) {
1069                 ldumpp[0].ndlck_clid.nclid_idlen = 0;
1070                 NFSUNLOCKSTATE();
1071                 NFSLOCKV4ROOTMUTEX();
1072                 nfsv4_relref(&nfsv4rootfs_lock);
1073                 NFSUNLOCKV4ROOTMUTEX();
1074                 return;
1075         }
1076
1077         /*
1078          * For each open share on file, dump it out.
1079          */
1080         stp = LIST_FIRST(&lfp->lf_open);
1081         while (stp != LIST_END(&lfp->lf_open) && cnt < maxcnt) {
1082                 ldumpp[cnt].ndlck_flags = stp->ls_flags;
1083                 ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
1084                 ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
1085                 ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
1086                 ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
1087                 ldumpp[cnt].ndlck_owner.nclid_idlen =
1088                     stp->ls_openowner->ls_ownerlen;
1089                 NFSBCOPY(stp->ls_openowner->ls_owner,
1090                     ldumpp[cnt].ndlck_owner.nclid_id,
1091                     stp->ls_openowner->ls_ownerlen);
1092                 ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
1093                 NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
1094                     stp->ls_clp->lc_idlen);
1095                 af = stp->ls_clp->lc_req.nr_nam->sa_family;
1096                 ldumpp[cnt].ndlck_addrfam = af;
1097                 switch (af) {
1098 #ifdef INET
1099                 case AF_INET:
1100                         rin = (struct sockaddr_in *)stp->ls_clp->lc_req.nr_nam;
1101                         ldumpp[cnt].ndlck_cbaddr.sin_addr = rin->sin_addr;
1102                         break;
1103 #endif
1104 #ifdef INET6
1105                 case AF_INET6:
1106                         rin6 = (struct sockaddr_in6 *)
1107                             stp->ls_clp->lc_req.nr_nam;
1108                         ldumpp[cnt].ndlck_cbaddr.sin6_addr = rin6->sin6_addr;
1109                         break;
1110 #endif
1111                 }
1112                 stp = LIST_NEXT(stp, ls_file);
1113                 cnt++;
1114         }
1115
1116         /*
1117          * and all locks.
1118          */
1119         lop = LIST_FIRST(&lfp->lf_lock);
1120         while (lop != LIST_END(&lfp->lf_lock) && cnt < maxcnt) {
1121                 stp = lop->lo_stp;
1122                 ldumpp[cnt].ndlck_flags = lop->lo_flags;
1123                 ldumpp[cnt].ndlck_first = lop->lo_first;
1124                 ldumpp[cnt].ndlck_end = lop->lo_end;
1125                 ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
1126                 ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
1127                 ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
1128                 ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
1129                 ldumpp[cnt].ndlck_owner.nclid_idlen = stp->ls_ownerlen;
1130                 NFSBCOPY(stp->ls_owner, ldumpp[cnt].ndlck_owner.nclid_id,
1131                     stp->ls_ownerlen);
1132                 ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
1133                 NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
1134                     stp->ls_clp->lc_idlen);
1135                 af = stp->ls_clp->lc_req.nr_nam->sa_family;
1136                 ldumpp[cnt].ndlck_addrfam = af;
1137                 switch (af) {
1138 #ifdef INET
1139                 case AF_INET:
1140                         rin = (struct sockaddr_in *)stp->ls_clp->lc_req.nr_nam;
1141                         ldumpp[cnt].ndlck_cbaddr.sin_addr = rin->sin_addr;
1142                         break;
1143 #endif
1144 #ifdef INET6
1145                 case AF_INET6:
1146                         rin6 = (struct sockaddr_in6 *)
1147                             stp->ls_clp->lc_req.nr_nam;
1148                         ldumpp[cnt].ndlck_cbaddr.sin6_addr = rin6->sin6_addr;
1149                         break;
1150 #endif
1151                 }
1152                 lop = LIST_NEXT(lop, lo_lckfile);
1153                 cnt++;
1154         }
1155
1156         /*
1157          * and the delegations.
1158          */
1159         stp = LIST_FIRST(&lfp->lf_deleg);
1160         while (stp != LIST_END(&lfp->lf_deleg) && cnt < maxcnt) {
1161                 ldumpp[cnt].ndlck_flags = stp->ls_flags;
1162                 ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
1163                 ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
1164                 ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
1165                 ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
1166                 ldumpp[cnt].ndlck_owner.nclid_idlen = 0;
1167                 ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
1168                 NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
1169                     stp->ls_clp->lc_idlen);
1170                 af = stp->ls_clp->lc_req.nr_nam->sa_family;
1171                 ldumpp[cnt].ndlck_addrfam = af;
1172                 switch (af) {
1173 #ifdef INET
1174                 case AF_INET:
1175                         rin = (struct sockaddr_in *)stp->ls_clp->lc_req.nr_nam;
1176                         ldumpp[cnt].ndlck_cbaddr.sin_addr = rin->sin_addr;
1177                         break;
1178 #endif
1179 #ifdef INET6
1180                 case AF_INET6:
1181                         rin6 = (struct sockaddr_in6 *)
1182                             stp->ls_clp->lc_req.nr_nam;
1183                         ldumpp[cnt].ndlck_cbaddr.sin6_addr = rin6->sin6_addr;
1184                         break;
1185 #endif
1186                 }
1187                 stp = LIST_NEXT(stp, ls_file);
1188                 cnt++;
1189         }
1190
1191         /*
1192          * If list isn't full, mark end of list by setting the client name
1193          * to zero length.
1194          */
1195         if (cnt < maxcnt)
1196                 ldumpp[cnt].ndlck_clid.nclid_idlen = 0;
1197         NFSUNLOCKSTATE();
1198         NFSLOCKV4ROOTMUTEX();
1199         nfsv4_relref(&nfsv4rootfs_lock);
1200         NFSUNLOCKV4ROOTMUTEX();
1201 }
1202
1203 /*
1204  * Server timer routine. It can scan any linked list, so long
1205  * as it holds the spin/mutex lock and there is no exclusive lock on
1206  * nfsv4rootfs_lock.
1207  * (For OpenBSD, a kthread is ok. For FreeBSD, I think it is ok
1208  *  to do this from a callout, since the spin locks work. For
1209  *  Darwin, I'm not sure what will work correctly yet.)
1210  * Should be called once per second.
1211  */
1212 void
1213 nfsrv_servertimer(void)
1214 {
1215         struct nfsclient *clp, *nclp;
1216         struct nfsstate *stp, *nstp;
1217         int got_ref, i;
1218
1219         /*
1220          * Make sure nfsboottime is set. This is used by V3 as well
1221          * as V4. Note that nfsboottime is not nfsrvboottime, which is
1222          * only used by the V4 server for leases.
1223          */
1224         if (nfsboottime.tv_sec == 0)
1225                 NFSSETBOOTTIME(nfsboottime);
1226
1227         /*
1228          * If server hasn't started yet, just return.
1229          */
1230         NFSLOCKSTATE();
1231         if (nfsrv_stablefirst.nsf_eograce == 0) {
1232                 NFSUNLOCKSTATE();
1233                 return;
1234         }
1235         if (!(nfsrv_stablefirst.nsf_flags & NFSNSF_UPDATEDONE)) {
1236                 if (!(nfsrv_stablefirst.nsf_flags & NFSNSF_GRACEOVER) &&
1237                     NFSD_MONOSEC > nfsrv_stablefirst.nsf_eograce)
1238                         nfsrv_stablefirst.nsf_flags |=
1239                             (NFSNSF_GRACEOVER | NFSNSF_NEEDLOCK);
1240                 NFSUNLOCKSTATE();
1241                 return;
1242         }
1243
1244         /*
1245          * Try and get a reference count on the nfsv4rootfs_lock so that
1246          * no nfsd thread can acquire an exclusive lock on it before this
1247          * call is done. If it is already exclusively locked, just return.
1248          */
1249         NFSLOCKV4ROOTMUTEX();
1250         got_ref = nfsv4_getref_nonblock(&nfsv4rootfs_lock);
1251         NFSUNLOCKV4ROOTMUTEX();
1252         if (got_ref == 0) {
1253                 NFSUNLOCKSTATE();
1254                 return;
1255         }
1256
1257         /*
1258          * For each client...
1259          */
1260         for (i = 0; i < nfsrv_clienthashsize; i++) {
1261             clp = LIST_FIRST(&nfsclienthash[i]);
1262             while (clp != LIST_END(&nfsclienthash[i])) {
1263                 nclp = LIST_NEXT(clp, lc_hash);
1264                 if (!(clp->lc_flags & LCL_EXPIREIT)) {
1265                     if (((clp->lc_expiry + NFSRV_STALELEASE) < NFSD_MONOSEC
1266                          && ((LIST_EMPTY(&clp->lc_deleg)
1267                               && LIST_EMPTY(&clp->lc_open)) ||
1268                              nfsrv_clients > nfsrv_clienthighwater)) ||
1269                         (clp->lc_expiry + NFSRV_MOULDYLEASE) < NFSD_MONOSEC ||
1270                         (clp->lc_expiry < NFSD_MONOSEC &&
1271                          (nfsrv_openpluslock * 10 / 9) > nfsrv_v4statelimit)) {
1272                         /*
1273                          * Lease has expired several nfsrv_lease times ago:
1274                          * PLUS
1275                          *    - no state is associated with it
1276                          *    OR
1277                          *    - above high water mark for number of clients
1278                          *      (nfsrv_clienthighwater should be large enough
1279                          *       that this only occurs when clients fail to
1280                          *       use the same nfs_client_id4.id. Maybe somewhat
1281                          *       higher that the maximum number of clients that
1282                          *       will mount this server?)
1283                          * OR
1284                          * Lease has expired a very long time ago
1285                          * OR
1286                          * Lease has expired PLUS the number of opens + locks
1287                          * has exceeded 90% of capacity
1288                          *
1289                          * --> Mark for expiry. The actual expiry will be done
1290                          *     by an nfsd sometime soon.
1291                          */
1292                         clp->lc_flags |= LCL_EXPIREIT;
1293                         nfsrv_stablefirst.nsf_flags |=
1294                             (NFSNSF_NEEDLOCK | NFSNSF_EXPIREDCLIENT);
1295                     } else {
1296                         /*
1297                          * If there are no opens, increment no open tick cnt
1298                          * If time exceeds NFSNOOPEN, mark it to be thrown away
1299                          * otherwise, if there is an open, reset no open time
1300                          * Hopefully, this will avoid excessive re-creation
1301                          * of open owners and subsequent open confirms.
1302                          */
1303                         stp = LIST_FIRST(&clp->lc_open);
1304                         while (stp != LIST_END(&clp->lc_open)) {
1305                                 nstp = LIST_NEXT(stp, ls_list);
1306                                 if (LIST_EMPTY(&stp->ls_open)) {
1307                                         stp->ls_noopens++;
1308                                         if (stp->ls_noopens > NFSNOOPEN ||
1309                                             (nfsrv_openpluslock * 2) >
1310                                             nfsrv_v4statelimit)
1311                                                 nfsrv_stablefirst.nsf_flags |=
1312                                                         NFSNSF_NOOPENS;
1313                                 } else {
1314                                         stp->ls_noopens = 0;
1315                                 }
1316                                 stp = nstp;
1317                         }
1318                     }
1319                 }
1320                 clp = nclp;
1321             }
1322         }
1323         NFSUNLOCKSTATE();
1324         NFSLOCKV4ROOTMUTEX();
1325         nfsv4_relref(&nfsv4rootfs_lock);
1326         NFSUNLOCKV4ROOTMUTEX();
1327 }
1328
1329 /*
1330  * The following set of functions free up the various data structures.
1331  */
1332 /*
1333  * Clear out all open/lock state related to this nfsclient.
1334  * Caller must hold an exclusive lock on nfsv4rootfs_lock, so that
1335  * there are no other active nfsd threads.
1336  */
1337 void
1338 nfsrv_cleanclient(struct nfsclient *clp, NFSPROC_T *p)
1339 {
1340         struct nfsstate *stp, *nstp;
1341         struct nfsdsession *sep, *nsep;
1342
1343         LIST_FOREACH_SAFE(stp, &clp->lc_open, ls_list, nstp)
1344                 nfsrv_freeopenowner(stp, 1, p);
1345         if ((clp->lc_flags & LCL_ADMINREVOKED) == 0)
1346                 LIST_FOREACH_SAFE(sep, &clp->lc_session, sess_list, nsep)
1347                         (void)nfsrv_freesession(sep, NULL);
1348 }
1349
1350 /*
1351  * Free a client that has been cleaned. It should also already have been
1352  * removed from the lists.
1353  * (Just to be safe w.r.t. newnfs_disconnect(), call this function when
1354  *  softclock interrupts are enabled.)
1355  */
1356 void
1357 nfsrv_zapclient(struct nfsclient *clp, NFSPROC_T *p)
1358 {
1359
1360 #ifdef notyet
1361         if ((clp->lc_flags & (LCL_GSS | LCL_CALLBACKSON)) ==
1362              (LCL_GSS | LCL_CALLBACKSON) &&
1363             (clp->lc_hand.nfsh_flag & NFSG_COMPLETE) &&
1364             clp->lc_handlelen > 0) {
1365                 clp->lc_hand.nfsh_flag &= ~NFSG_COMPLETE;
1366                 clp->lc_hand.nfsh_flag |= NFSG_DESTROYED;
1367                 (void) nfsrv_docallback(clp, NFSV4PROC_CBNULL,
1368                         NULL, 0, NULL, NULL, NULL, 0, p);
1369         }
1370 #endif
1371         newnfs_disconnect(&clp->lc_req);
1372         free(clp->lc_req.nr_nam, M_SONAME);
1373         NFSFREEMUTEX(&clp->lc_req.nr_mtx);
1374         free(clp->lc_stateid, M_NFSDCLIENT);
1375         free(clp, M_NFSDCLIENT);
1376         NFSLOCKSTATE();
1377         nfsstatsv1.srvclients--;
1378         nfsrv_openpluslock--;
1379         nfsrv_clients--;
1380         NFSUNLOCKSTATE();
1381 }
1382
1383 /*
1384  * Free a list of delegation state structures.
1385  * (This function will also free all nfslockfile structures that no
1386  *  longer have associated state.)
1387  */
1388 void
1389 nfsrv_freedeleglist(struct nfsstatehead *sthp)
1390 {
1391         struct nfsstate *stp, *nstp;
1392
1393         LIST_FOREACH_SAFE(stp, sthp, ls_list, nstp) {
1394                 nfsrv_freedeleg(stp);
1395         }
1396         LIST_INIT(sthp);
1397 }
1398
1399 /*
1400  * Free up a delegation.
1401  */
1402 static void
1403 nfsrv_freedeleg(struct nfsstate *stp)
1404 {
1405         struct nfslockfile *lfp;
1406
1407         LIST_REMOVE(stp, ls_hash);
1408         LIST_REMOVE(stp, ls_list);
1409         LIST_REMOVE(stp, ls_file);
1410         if ((stp->ls_flags & NFSLCK_DELEGWRITE) != 0)
1411                 nfsrv_writedelegcnt--;
1412         lfp = stp->ls_lfp;
1413         if (LIST_EMPTY(&lfp->lf_open) &&
1414             LIST_EMPTY(&lfp->lf_lock) && LIST_EMPTY(&lfp->lf_deleg) &&
1415             LIST_EMPTY(&lfp->lf_locallock) && LIST_EMPTY(&lfp->lf_rollback) &&
1416             lfp->lf_usecount == 0 &&
1417             nfsv4_testlock(&lfp->lf_locallock_lck) == 0)
1418                 nfsrv_freenfslockfile(lfp);
1419         free(stp, M_NFSDSTATE);
1420         nfsstatsv1.srvdelegates--;
1421         nfsrv_openpluslock--;
1422         nfsrv_delegatecnt--;
1423 }
1424
1425 /*
1426  * This function frees an open owner and all associated opens.
1427  */
1428 static void
1429 nfsrv_freeopenowner(struct nfsstate *stp, int cansleep, NFSPROC_T *p)
1430 {
1431         struct nfsstate *nstp, *tstp;
1432
1433         LIST_REMOVE(stp, ls_list);
1434         /*
1435          * Now, free all associated opens.
1436          */
1437         nstp = LIST_FIRST(&stp->ls_open);
1438         while (nstp != LIST_END(&stp->ls_open)) {
1439                 tstp = nstp;
1440                 nstp = LIST_NEXT(nstp, ls_list);
1441                 (void) nfsrv_freeopen(tstp, NULL, cansleep, p);
1442         }
1443         if (stp->ls_op)
1444                 nfsrvd_derefcache(stp->ls_op);
1445         free(stp, M_NFSDSTATE);
1446         nfsstatsv1.srvopenowners--;
1447         nfsrv_openpluslock--;
1448 }
1449
1450 /*
1451  * This function frees an open (nfsstate open structure) with all associated
1452  * lock_owners and locks. It also frees the nfslockfile structure iff there
1453  * are no other opens on the file.
1454  * Returns 1 if it free'd the nfslockfile, 0 otherwise.
1455  */
1456 static int
1457 nfsrv_freeopen(struct nfsstate *stp, vnode_t vp, int cansleep, NFSPROC_T *p)
1458 {
1459         struct nfsstate *nstp, *tstp;
1460         struct nfslockfile *lfp;
1461         int ret;
1462
1463         LIST_REMOVE(stp, ls_hash);
1464         LIST_REMOVE(stp, ls_list);
1465         LIST_REMOVE(stp, ls_file);
1466
1467         lfp = stp->ls_lfp;
1468         /*
1469          * Now, free all lockowners associated with this open.
1470          */
1471         LIST_FOREACH_SAFE(tstp, &stp->ls_open, ls_list, nstp)
1472                 nfsrv_freelockowner(tstp, vp, cansleep, p);
1473
1474         /*
1475          * The nfslockfile is freed here if there are no locks
1476          * associated with the open.
1477          * If there are locks associated with the open, the
1478          * nfslockfile structure can be freed via nfsrv_freelockowner().
1479          * Acquire the state mutex to avoid races with calls to
1480          * nfsrv_getlockfile().
1481          */
1482         if (cansleep != 0)
1483                 NFSLOCKSTATE();
1484         if (lfp != NULL && LIST_EMPTY(&lfp->lf_open) &&
1485             LIST_EMPTY(&lfp->lf_deleg) && LIST_EMPTY(&lfp->lf_lock) &&
1486             LIST_EMPTY(&lfp->lf_locallock) && LIST_EMPTY(&lfp->lf_rollback) &&
1487             lfp->lf_usecount == 0 &&
1488             (cansleep != 0 || nfsv4_testlock(&lfp->lf_locallock_lck) == 0)) {
1489                 nfsrv_freenfslockfile(lfp);
1490                 ret = 1;
1491         } else
1492                 ret = 0;
1493         if (cansleep != 0)
1494                 NFSUNLOCKSTATE();
1495         free(stp, M_NFSDSTATE);
1496         nfsstatsv1.srvopens--;
1497         nfsrv_openpluslock--;
1498         return (ret);
1499 }
1500
1501 /*
1502  * Frees a lockowner and all associated locks.
1503  */
1504 static void
1505 nfsrv_freelockowner(struct nfsstate *stp, vnode_t vp, int cansleep,
1506     NFSPROC_T *p)
1507 {
1508
1509         LIST_REMOVE(stp, ls_hash);
1510         LIST_REMOVE(stp, ls_list);
1511         nfsrv_freeallnfslocks(stp, vp, cansleep, p);
1512         if (stp->ls_op)
1513                 nfsrvd_derefcache(stp->ls_op);
1514         free(stp, M_NFSDSTATE);
1515         nfsstatsv1.srvlockowners--;
1516         nfsrv_openpluslock--;
1517 }
1518
1519 /*
1520  * Free all the nfs locks on a lockowner.
1521  */
1522 static void
1523 nfsrv_freeallnfslocks(struct nfsstate *stp, vnode_t vp, int cansleep,
1524     NFSPROC_T *p)
1525 {
1526         struct nfslock *lop, *nlop;
1527         struct nfsrollback *rlp, *nrlp;
1528         struct nfslockfile *lfp = NULL;
1529         int gottvp = 0;
1530         vnode_t tvp = NULL;
1531         uint64_t first, end;
1532
1533         if (vp != NULL)
1534                 ASSERT_VOP_UNLOCKED(vp, "nfsrv_freeallnfslocks: vnode locked");
1535         lop = LIST_FIRST(&stp->ls_lock);
1536         while (lop != LIST_END(&stp->ls_lock)) {
1537                 nlop = LIST_NEXT(lop, lo_lckowner);
1538                 /*
1539                  * Since all locks should be for the same file, lfp should
1540                  * not change.
1541                  */
1542                 if (lfp == NULL)
1543                         lfp = lop->lo_lfp;
1544                 else if (lfp != lop->lo_lfp)
1545                         panic("allnfslocks");
1546                 /*
1547                  * If vp is NULL and cansleep != 0, a vnode must be acquired
1548                  * from the file handle. This only occurs when called from
1549                  * nfsrv_cleanclient().
1550                  */
1551                 if (gottvp == 0) {
1552                         if (nfsrv_dolocallocks == 0)
1553                                 tvp = NULL;
1554                         else if (vp == NULL && cansleep != 0) {
1555                                 tvp = nfsvno_getvp(&lfp->lf_fh);
1556                                 if (tvp != NULL)
1557                                         NFSVOPUNLOCK(tvp, 0);
1558                         } else
1559                                 tvp = vp;
1560                         gottvp = 1;
1561                 }
1562
1563                 if (tvp != NULL) {
1564                         if (cansleep == 0)
1565                                 panic("allnfs2");
1566                         first = lop->lo_first;
1567                         end = lop->lo_end;
1568                         nfsrv_freenfslock(lop);
1569                         nfsrv_localunlock(tvp, lfp, first, end, p);
1570                         LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list,
1571                             nrlp)
1572                                 free(rlp, M_NFSDROLLBACK);
1573                         LIST_INIT(&lfp->lf_rollback);
1574                 } else
1575                         nfsrv_freenfslock(lop);
1576                 lop = nlop;
1577         }
1578         if (vp == NULL && tvp != NULL)
1579                 vrele(tvp);
1580 }
1581
1582 /*
1583  * Free an nfslock structure.
1584  */
1585 static void
1586 nfsrv_freenfslock(struct nfslock *lop)
1587 {
1588
1589         if (lop->lo_lckfile.le_prev != NULL) {
1590                 LIST_REMOVE(lop, lo_lckfile);
1591                 nfsstatsv1.srvlocks--;
1592                 nfsrv_openpluslock--;
1593         }
1594         LIST_REMOVE(lop, lo_lckowner);
1595         free(lop, M_NFSDLOCK);
1596 }
1597
1598 /*
1599  * This function frees an nfslockfile structure.
1600  */
1601 static void
1602 nfsrv_freenfslockfile(struct nfslockfile *lfp)
1603 {
1604
1605         LIST_REMOVE(lfp, lf_hash);
1606         free(lfp, M_NFSDLOCKFILE);
1607 }
1608
1609 /*
1610  * This function looks up an nfsstate structure via stateid.
1611  */
1612 static int
1613 nfsrv_getstate(struct nfsclient *clp, nfsv4stateid_t *stateidp, __unused u_int32_t flags,
1614     struct nfsstate **stpp)
1615 {
1616         struct nfsstate *stp;
1617         struct nfsstatehead *hp;
1618         int error = 0;
1619
1620         *stpp = NULL;
1621         hp = NFSSTATEHASH(clp, *stateidp);
1622         LIST_FOREACH(stp, hp, ls_hash) {
1623                 if (!NFSBCMP(stp->ls_stateid.other, stateidp->other,
1624                         NFSX_STATEIDOTHER))
1625                         break;
1626         }
1627
1628         /*
1629          * If no state id in list, return NFSERR_BADSTATEID.
1630          */
1631         if (stp == LIST_END(hp)) {
1632                 error = NFSERR_BADSTATEID;
1633                 goto out;
1634         }
1635         *stpp = stp;
1636
1637 out:
1638         NFSEXITCODE(error);
1639         return (error);
1640 }
1641
1642 /*
1643  * This function gets an nfsstate structure via owner string.
1644  */
1645 static void
1646 nfsrv_getowner(struct nfsstatehead *hp, struct nfsstate *new_stp,
1647     struct nfsstate **stpp)
1648 {
1649         struct nfsstate *stp;
1650
1651         *stpp = NULL;
1652         LIST_FOREACH(stp, hp, ls_list) {
1653                 if (new_stp->ls_ownerlen == stp->ls_ownerlen &&
1654                   !NFSBCMP(new_stp->ls_owner,stp->ls_owner,stp->ls_ownerlen)) {
1655                         *stpp = stp;
1656                         return;
1657                 }
1658         }
1659 }
1660
1661 /*
1662  * Lock control function called to update lock status.
1663  * Returns 0 upon success, -1 if there is no lock and the flags indicate
1664  * that one isn't to be created and an NFSERR_xxx for other errors.
1665  * The structures new_stp and new_lop are passed in as pointers that should
1666  * be set to NULL if the structure is used and shouldn't be free'd.
1667  * For the NFSLCK_TEST and NFSLCK_CHECK cases, the structures are
1668  * never used and can safely be allocated on the stack. For all other
1669  * cases, *new_stpp and *new_lopp should be malloc'd before the call,
1670  * in case they are used.
1671  */
1672 int
1673 nfsrv_lockctrl(vnode_t vp, struct nfsstate **new_stpp,
1674     struct nfslock **new_lopp, struct nfslockconflict *cfp,
1675     nfsquad_t clientid, nfsv4stateid_t *stateidp,
1676     __unused struct nfsexstuff *exp,
1677     struct nfsrv_descript *nd, NFSPROC_T *p)
1678 {
1679         struct nfslock *lop;
1680         struct nfsstate *new_stp = *new_stpp;
1681         struct nfslock *new_lop = *new_lopp;
1682         struct nfsstate *tstp, *mystp, *nstp;
1683         int specialid = 0;
1684         struct nfslockfile *lfp;
1685         struct nfslock *other_lop = NULL;
1686         struct nfsstate *stp, *lckstp = NULL;
1687         struct nfsclient *clp = NULL;
1688         u_int32_t bits;
1689         int error = 0, haslock = 0, ret, reterr;
1690         int getlckret, delegation = 0, filestruct_locked, vnode_unlocked = 0;
1691         fhandle_t nfh;
1692         uint64_t first, end;
1693         uint32_t lock_flags;
1694
1695         if (new_stp->ls_flags & (NFSLCK_CHECK | NFSLCK_SETATTR)) {
1696                 /*
1697                  * Note the special cases of "all 1s" or "all 0s" stateids and
1698                  * let reads with all 1s go ahead.
1699                  */
1700                 if (new_stp->ls_stateid.seqid == 0x0 &&
1701                     new_stp->ls_stateid.other[0] == 0x0 &&
1702                     new_stp->ls_stateid.other[1] == 0x0 &&
1703                     new_stp->ls_stateid.other[2] == 0x0)
1704                         specialid = 1;
1705                 else if (new_stp->ls_stateid.seqid == 0xffffffff &&
1706                     new_stp->ls_stateid.other[0] == 0xffffffff &&
1707                     new_stp->ls_stateid.other[1] == 0xffffffff &&
1708                     new_stp->ls_stateid.other[2] == 0xffffffff)
1709                         specialid = 2;
1710         }
1711
1712         /*
1713          * Check for restart conditions (client and server).
1714          */
1715         error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
1716             &new_stp->ls_stateid, specialid);
1717         if (error)
1718                 goto out;
1719
1720         /*
1721          * Check for state resource limit exceeded.
1722          */
1723         if ((new_stp->ls_flags & NFSLCK_LOCK) &&
1724             nfsrv_openpluslock > nfsrv_v4statelimit) {
1725                 error = NFSERR_RESOURCE;
1726                 goto out;
1727         }
1728
1729         /*
1730          * For the lock case, get another nfslock structure,
1731          * just in case we need it.
1732          * Malloc now, before we start sifting through the linked lists,
1733          * in case we have to wait for memory.
1734          */
1735 tryagain:
1736         if (new_stp->ls_flags & NFSLCK_LOCK)
1737                 other_lop = malloc(sizeof (struct nfslock),
1738                     M_NFSDLOCK, M_WAITOK);
1739         filestruct_locked = 0;
1740         reterr = 0;
1741         lfp = NULL;
1742
1743         /*
1744          * Get the lockfile structure for CFH now, so we can do a sanity
1745          * check against the stateid, before incrementing the seqid#, since
1746          * we want to return NFSERR_BADSTATEID on failure and the seqid#
1747          * shouldn't be incremented for this case.
1748          * If nfsrv_getlockfile() returns -1, it means "not found", which
1749          * will be handled later.
1750          * If we are doing Lock/LockU and local locking is enabled, sleep
1751          * lock the nfslockfile structure.
1752          */
1753         getlckret = nfsrv_getlockfh(vp, new_stp->ls_flags, NULL, &nfh, p);
1754         NFSLOCKSTATE();
1755         if (getlckret == 0) {
1756                 if ((new_stp->ls_flags & (NFSLCK_LOCK | NFSLCK_UNLOCK)) != 0 &&
1757                     nfsrv_dolocallocks != 0 && nd->nd_repstat == 0) {
1758                         getlckret = nfsrv_getlockfile(new_stp->ls_flags, NULL,
1759                             &lfp, &nfh, 1);
1760                         if (getlckret == 0)
1761                                 filestruct_locked = 1;
1762                 } else
1763                         getlckret = nfsrv_getlockfile(new_stp->ls_flags, NULL,
1764                             &lfp, &nfh, 0);
1765         }
1766         if (getlckret != 0 && getlckret != -1)
1767                 reterr = getlckret;
1768
1769         if (filestruct_locked != 0) {
1770                 LIST_INIT(&lfp->lf_rollback);
1771                 if ((new_stp->ls_flags & NFSLCK_LOCK)) {
1772                         /*
1773                          * For local locking, do the advisory locking now, so
1774                          * that any conflict can be detected. A failure later
1775                          * can be rolled back locally. If an error is returned,
1776                          * struct nfslockfile has been unlocked and any local
1777                          * locking rolled back.
1778                          */
1779                         NFSUNLOCKSTATE();
1780                         if (vnode_unlocked == 0) {
1781                                 ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl1");
1782                                 vnode_unlocked = 1;
1783                                 NFSVOPUNLOCK(vp, 0);
1784                         }
1785                         reterr = nfsrv_locallock(vp, lfp,
1786                             (new_lop->lo_flags & (NFSLCK_READ | NFSLCK_WRITE)),
1787                             new_lop->lo_first, new_lop->lo_end, cfp, p);
1788                         NFSLOCKSTATE();
1789                 }
1790         }
1791
1792         if (specialid == 0) {
1793             if (new_stp->ls_flags & NFSLCK_TEST) {
1794                 /*
1795                  * RFC 3530 does not list LockT as an op that renews a
1796                  * lease, but the consensus seems to be that it is ok
1797                  * for a server to do so.
1798                  */
1799                 error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
1800                     (nfsquad_t)((u_quad_t)0), 0, nd, p);
1801
1802                 /*
1803                  * Since NFSERR_EXPIRED, NFSERR_ADMINREVOKED are not valid
1804                  * error returns for LockT, just go ahead and test for a lock,
1805                  * since there are no locks for this client, but other locks
1806                  * can conflict. (ie. same client will always be false)
1807                  */
1808                 if (error == NFSERR_EXPIRED || error == NFSERR_ADMINREVOKED)
1809                     error = 0;
1810                 lckstp = new_stp;
1811             } else {
1812               error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
1813                 (nfsquad_t)((u_quad_t)0), 0, nd, p);
1814               if (error == 0)
1815                 /*
1816                  * Look up the stateid
1817                  */
1818                 error = nfsrv_getstate(clp, &new_stp->ls_stateid,
1819                   new_stp->ls_flags, &stp);
1820               /*
1821                * do some sanity checks for an unconfirmed open or a
1822                * stateid that refers to the wrong file, for an open stateid
1823                */
1824               if (error == 0 && (stp->ls_flags & NFSLCK_OPEN) &&
1825                   ((stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM) ||
1826                    (getlckret == 0 && stp->ls_lfp != lfp))){
1827                       /*
1828                        * NFSLCK_SETATTR should return OK rather than NFSERR_BADSTATEID
1829                        * The only exception is using SETATTR with SIZE.
1830                        * */
1831                     if ((new_stp->ls_flags &
1832                          (NFSLCK_SETATTR | NFSLCK_CHECK)) != NFSLCK_SETATTR)
1833                              error = NFSERR_BADSTATEID;
1834               }
1835               
1836                 if (error == 0 &&
1837                   (stp->ls_flags & (NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) &&
1838                   getlckret == 0 && stp->ls_lfp != lfp)
1839                         error = NFSERR_BADSTATEID;
1840
1841               /*
1842                * If the lockowner stateid doesn't refer to the same file,
1843                * I believe that is considered ok, since some clients will
1844                * only create a single lockowner and use that for all locks
1845                * on all files.
1846                * For now, log it as a diagnostic, instead of considering it
1847                * a BadStateid.
1848                */
1849               if (error == 0 && (stp->ls_flags &
1850                   (NFSLCK_OPEN | NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) == 0 &&
1851                   getlckret == 0 && stp->ls_lfp != lfp) {
1852 #ifdef DIAGNOSTIC
1853                   printf("Got a lock statid for different file open\n");
1854 #endif
1855                   /*
1856                   error = NFSERR_BADSTATEID;
1857                   */
1858               }
1859
1860               if (error == 0) {
1861                     if (new_stp->ls_flags & NFSLCK_OPENTOLOCK) {
1862                         /*
1863                          * If haslock set, we've already checked the seqid.
1864                          */
1865                         if (!haslock) {
1866                             if (stp->ls_flags & NFSLCK_OPEN)
1867                                 error = nfsrv_checkseqid(nd, new_stp->ls_seq,
1868                                     stp->ls_openowner, new_stp->ls_op);
1869                             else
1870                                 error = NFSERR_BADSTATEID;
1871                         }
1872                         if (!error)
1873                             nfsrv_getowner(&stp->ls_open, new_stp, &lckstp);
1874                         if (lckstp)
1875                             /*
1876                              * I believe this should be an error, but it
1877                              * isn't obvious what NFSERR_xxx would be
1878                              * appropriate, so I'll use NFSERR_INVAL for now.
1879                              */
1880                             error = NFSERR_INVAL;
1881                         else
1882                             lckstp = new_stp;
1883                     } else if (new_stp->ls_flags&(NFSLCK_LOCK|NFSLCK_UNLOCK)) {
1884                         /*
1885                          * If haslock set, ditto above.
1886                          */
1887                         if (!haslock) {
1888                             if (stp->ls_flags & NFSLCK_OPEN)
1889                                 error = NFSERR_BADSTATEID;
1890                             else
1891                                 error = nfsrv_checkseqid(nd, new_stp->ls_seq,
1892                                     stp, new_stp->ls_op);
1893                         }
1894                         lckstp = stp;
1895                     } else {
1896                         lckstp = stp;
1897                     }
1898               }
1899               /*
1900                * If the seqid part of the stateid isn't the same, return
1901                * NFSERR_OLDSTATEID for cases other than I/O Ops.
1902                * For I/O Ops, only return NFSERR_OLDSTATEID if
1903                * nfsrv_returnoldstateid is set. (The consensus on the email
1904                * list was that most clients would prefer to not receive
1905                * NFSERR_OLDSTATEID for I/O Ops, but the RFC suggests that that
1906                * is what will happen, so I use the nfsrv_returnoldstateid to
1907                * allow for either server configuration.)
1908                */
1909               if (!error && stp->ls_stateid.seqid!=new_stp->ls_stateid.seqid &&
1910                   (((nd->nd_flag & ND_NFSV41) == 0 &&
1911                    (!(new_stp->ls_flags & NFSLCK_CHECK) ||
1912                     nfsrv_returnoldstateid)) ||
1913                    ((nd->nd_flag & ND_NFSV41) != 0 &&
1914                     new_stp->ls_stateid.seqid != 0)))
1915                     error = NFSERR_OLDSTATEID;
1916             }
1917         }
1918
1919         /*
1920          * Now we can check for grace.
1921          */
1922         if (!error)
1923                 error = nfsrv_checkgrace(nd, clp, new_stp->ls_flags);
1924         if ((new_stp->ls_flags & NFSLCK_RECLAIM) && !error &&
1925                 nfsrv_checkstable(clp))
1926                 error = NFSERR_NOGRACE;
1927         /*
1928          * If we successfully Reclaimed state, note that.
1929          */
1930         if ((new_stp->ls_flags & NFSLCK_RECLAIM) && !error)
1931                 nfsrv_markstable(clp);
1932
1933         /*
1934          * At this point, either error == NFSERR_BADSTATEID or the
1935          * seqid# has been updated, so we can return any error.
1936          * If error == 0, there may be an error in:
1937          *    nd_repstat - Set by the calling function.
1938          *    reterr - Set above, if getting the nfslockfile structure
1939          *       or acquiring the local lock failed.
1940          *    (If both of these are set, nd_repstat should probably be
1941          *     returned, since that error was detected before this
1942          *     function call.)
1943          */
1944         if (error != 0 || nd->nd_repstat != 0 || reterr != 0) {
1945                 if (error == 0) {
1946                         if (nd->nd_repstat != 0)
1947                                 error = nd->nd_repstat;
1948                         else
1949                                 error = reterr;
1950                 }
1951                 if (filestruct_locked != 0) {
1952                         /* Roll back local locks. */
1953                         NFSUNLOCKSTATE();
1954                         if (vnode_unlocked == 0) {
1955                                 ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl2");
1956                                 vnode_unlocked = 1;
1957                                 NFSVOPUNLOCK(vp, 0);
1958                         }
1959                         nfsrv_locallock_rollback(vp, lfp, p);
1960                         NFSLOCKSTATE();
1961                         nfsrv_unlocklf(lfp);
1962                 }
1963                 NFSUNLOCKSTATE();
1964                 goto out;
1965         }
1966
1967         /*
1968          * Check the nfsrv_getlockfile return.
1969          * Returned -1 if no structure found.
1970          */
1971         if (getlckret == -1) {
1972                 error = NFSERR_EXPIRED;
1973                 /*
1974                  * Called from lockt, so no lock is OK.
1975                  */
1976                 if (new_stp->ls_flags & NFSLCK_TEST) {
1977                         error = 0;
1978                 } else if (new_stp->ls_flags &
1979                     (NFSLCK_CHECK | NFSLCK_SETATTR)) {
1980                         /*
1981                          * Called to check for a lock, OK if the stateid is all
1982                          * 1s or all 0s, but there should be an nfsstate
1983                          * otherwise.
1984                          * (ie. If there is no open, I'll assume no share
1985                          *  deny bits.)
1986                          */
1987                         if (specialid)
1988                                 error = 0;
1989                         else
1990                                 error = NFSERR_BADSTATEID;
1991                 }
1992                 NFSUNLOCKSTATE();
1993                 goto out;
1994         }
1995
1996         /*
1997          * For NFSLCK_CHECK and NFSLCK_LOCK, test for a share conflict.
1998          * For NFSLCK_CHECK, allow a read if write access is granted,
1999          * but check for a deny. For NFSLCK_LOCK, require correct access,
2000          * which implies a conflicting deny can't exist.
2001          */
2002         if (new_stp->ls_flags & (NFSLCK_CHECK | NFSLCK_LOCK)) {
2003             /*
2004              * Four kinds of state id:
2005              * - specialid (all 0s or all 1s), only for NFSLCK_CHECK
2006              * - stateid for an open
2007              * - stateid for a delegation
2008              * - stateid for a lock owner
2009              */
2010             if (!specialid) {
2011                 if (stp->ls_flags & (NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) {
2012                     delegation = 1;
2013                     mystp = stp;
2014                     nfsrv_delaydelegtimeout(stp);
2015                 } else if (stp->ls_flags & NFSLCK_OPEN) {
2016                     mystp = stp;
2017                 } else {
2018                     mystp = stp->ls_openstp;
2019                 }
2020                 /*
2021                  * If locking or checking, require correct access
2022                  * bit set.
2023                  */
2024                 if (((new_stp->ls_flags & NFSLCK_LOCK) &&
2025                      !((new_lop->lo_flags >> NFSLCK_LOCKSHIFT) &
2026                        mystp->ls_flags & NFSLCK_ACCESSBITS)) ||
2027                     ((new_stp->ls_flags & (NFSLCK_CHECK|NFSLCK_READACCESS)) ==
2028                       (NFSLCK_CHECK | NFSLCK_READACCESS) &&
2029                      !(mystp->ls_flags & NFSLCK_READACCESS) &&
2030                      nfsrv_allowreadforwriteopen == 0) ||
2031                     ((new_stp->ls_flags & (NFSLCK_CHECK|NFSLCK_WRITEACCESS)) ==
2032                       (NFSLCK_CHECK | NFSLCK_WRITEACCESS) &&
2033                      !(mystp->ls_flags & NFSLCK_WRITEACCESS))) {
2034                         if (filestruct_locked != 0) {
2035                                 /* Roll back local locks. */
2036                                 NFSUNLOCKSTATE();
2037                                 if (vnode_unlocked == 0) {
2038                                         ASSERT_VOP_ELOCKED(vp,
2039                                             "nfsrv_lockctrl3");
2040                                         vnode_unlocked = 1;
2041                                         NFSVOPUNLOCK(vp, 0);
2042                                 }
2043                                 nfsrv_locallock_rollback(vp, lfp, p);
2044                                 NFSLOCKSTATE();
2045                                 nfsrv_unlocklf(lfp);
2046                         }
2047                         NFSUNLOCKSTATE();
2048                         error = NFSERR_OPENMODE;
2049                         goto out;
2050                 }
2051             } else
2052                 mystp = NULL;
2053             if ((new_stp->ls_flags & NFSLCK_CHECK) && !delegation) {
2054                 /*
2055                  * Check for a conflicting deny bit.
2056                  */
2057                 LIST_FOREACH(tstp, &lfp->lf_open, ls_file) {
2058                     if (tstp != mystp) {
2059                         bits = tstp->ls_flags;
2060                         bits >>= NFSLCK_SHIFT;
2061                         if (new_stp->ls_flags & bits & NFSLCK_ACCESSBITS) {
2062                             KASSERT(vnode_unlocked == 0,
2063                                 ("nfsrv_lockctrl: vnode unlocked1"));
2064                             ret = nfsrv_clientconflict(tstp->ls_clp, &haslock,
2065                                 vp, p);
2066                             if (ret == 1) {
2067                                 /*
2068                                 * nfsrv_clientconflict unlocks state
2069                                  * when it returns non-zero.
2070                                  */
2071                                 lckstp = NULL;
2072                                 goto tryagain;
2073                             }
2074                             if (ret == 0)
2075                                 NFSUNLOCKSTATE();
2076                             if (ret == 2)
2077                                 error = NFSERR_PERM;
2078                             else
2079                                 error = NFSERR_OPENMODE;
2080                             goto out;
2081                         }
2082                     }
2083                 }
2084
2085                 /* We're outta here */
2086                 NFSUNLOCKSTATE();
2087                 goto out;
2088             }
2089         }
2090
2091         /*
2092          * For setattr, just get rid of all the Delegations for other clients.
2093          */
2094         if (new_stp->ls_flags & NFSLCK_SETATTR) {
2095                 KASSERT(vnode_unlocked == 0,
2096                     ("nfsrv_lockctrl: vnode unlocked2"));
2097                 ret = nfsrv_cleandeleg(vp, lfp, clp, &haslock, p);
2098                 if (ret) {
2099                         /*
2100                          * nfsrv_cleandeleg() unlocks state when it
2101                          * returns non-zero.
2102                          */
2103                         if (ret == -1) {
2104                                 lckstp = NULL;
2105                                 goto tryagain;
2106                         }
2107                         error = ret;
2108                         goto out;
2109                 }
2110                 if (!(new_stp->ls_flags & NFSLCK_CHECK) ||
2111                     (LIST_EMPTY(&lfp->lf_open) && LIST_EMPTY(&lfp->lf_lock) &&
2112                      LIST_EMPTY(&lfp->lf_deleg))) {
2113                         NFSUNLOCKSTATE();
2114                         goto out;
2115                 }
2116         }
2117
2118         /*
2119          * Check for a conflicting delegation. If one is found, call
2120          * nfsrv_delegconflict() to handle it. If the v4root lock hasn't
2121          * been set yet, it will get the lock. Otherwise, it will recall
2122          * the delegation. Then, we try try again...
2123          * I currently believe the conflict algorithm to be:
2124          * For Lock Ops (Lock/LockT/LockU)
2125          * - there is a conflict iff a different client has a write delegation
2126          * For Reading (Read Op)
2127          * - there is a conflict iff a different client has a write delegation
2128          *   (the specialids are always a different client)
2129          * For Writing (Write/Setattr of size)
2130          * - there is a conflict if a different client has any delegation
2131          * - there is a conflict if the same client has a read delegation
2132          *   (I don't understand why this isn't allowed, but that seems to be
2133          *    the current consensus?)
2134          */
2135         tstp = LIST_FIRST(&lfp->lf_deleg);
2136         while (tstp != LIST_END(&lfp->lf_deleg)) {
2137             nstp = LIST_NEXT(tstp, ls_file);
2138             if ((((new_stp->ls_flags&(NFSLCK_LOCK|NFSLCK_UNLOCK|NFSLCK_TEST))||
2139                  ((new_stp->ls_flags & NFSLCK_CHECK) &&
2140                   (new_lop->lo_flags & NFSLCK_READ))) &&
2141                   clp != tstp->ls_clp &&
2142                  (tstp->ls_flags & NFSLCK_DELEGWRITE)) ||
2143                  ((new_stp->ls_flags & NFSLCK_CHECK) &&
2144                    (new_lop->lo_flags & NFSLCK_WRITE) &&
2145                   (clp != tstp->ls_clp ||
2146                    (tstp->ls_flags & NFSLCK_DELEGREAD)))) {
2147                 ret = 0;
2148                 if (filestruct_locked != 0) {
2149                         /* Roll back local locks. */
2150                         NFSUNLOCKSTATE();
2151                         if (vnode_unlocked == 0) {
2152                                 ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl4");
2153                                 NFSVOPUNLOCK(vp, 0);
2154                         }
2155                         nfsrv_locallock_rollback(vp, lfp, p);
2156                         NFSLOCKSTATE();
2157                         nfsrv_unlocklf(lfp);
2158                         NFSUNLOCKSTATE();
2159                         NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
2160                         vnode_unlocked = 0;
2161                         if ((vp->v_iflag & VI_DOOMED) != 0)
2162                                 ret = NFSERR_SERVERFAULT;
2163                         NFSLOCKSTATE();
2164                 }
2165                 if (ret == 0)
2166                         ret = nfsrv_delegconflict(tstp, &haslock, p, vp);
2167                 if (ret) {
2168                     /*
2169                      * nfsrv_delegconflict unlocks state when it
2170                      * returns non-zero, which it always does.
2171                      */
2172                     if (other_lop) {
2173                         free(other_lop, M_NFSDLOCK);
2174                         other_lop = NULL;
2175                     }
2176                     if (ret == -1) {
2177                         lckstp = NULL;
2178                         goto tryagain;
2179                     }
2180                     error = ret;
2181                     goto out;
2182                 }
2183                 /* Never gets here. */
2184             }
2185             tstp = nstp;
2186         }
2187
2188         /*
2189          * Handle the unlock case by calling nfsrv_updatelock().
2190          * (Should I have done some access checking above for unlock? For now,
2191          *  just let it happen.)
2192          */
2193         if (new_stp->ls_flags & NFSLCK_UNLOCK) {
2194                 first = new_lop->lo_first;
2195                 end = new_lop->lo_end;
2196                 nfsrv_updatelock(stp, new_lopp, &other_lop, lfp);
2197                 stateidp->seqid = ++(stp->ls_stateid.seqid);
2198                 if ((nd->nd_flag & ND_NFSV41) != 0 && stateidp->seqid == 0)
2199                         stateidp->seqid = stp->ls_stateid.seqid = 1;
2200                 stateidp->other[0] = stp->ls_stateid.other[0];
2201                 stateidp->other[1] = stp->ls_stateid.other[1];
2202                 stateidp->other[2] = stp->ls_stateid.other[2];
2203                 if (filestruct_locked != 0) {
2204                         NFSUNLOCKSTATE();
2205                         if (vnode_unlocked == 0) {
2206                                 ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl5");
2207                                 vnode_unlocked = 1;
2208                                 NFSVOPUNLOCK(vp, 0);
2209                         }
2210                         /* Update the local locks. */
2211                         nfsrv_localunlock(vp, lfp, first, end, p);
2212                         NFSLOCKSTATE();
2213                         nfsrv_unlocklf(lfp);
2214                 }
2215                 NFSUNLOCKSTATE();
2216                 goto out;
2217         }
2218
2219         /*
2220          * Search for a conflicting lock. A lock conflicts if:
2221          * - the lock range overlaps and
2222          * - at least one lock is a write lock and
2223          * - it is not owned by the same lock owner
2224          */
2225         if (!delegation) {
2226           LIST_FOREACH(lop, &lfp->lf_lock, lo_lckfile) {
2227             if (new_lop->lo_end > lop->lo_first &&
2228                 new_lop->lo_first < lop->lo_end &&
2229                 (new_lop->lo_flags == NFSLCK_WRITE ||
2230                  lop->lo_flags == NFSLCK_WRITE) &&
2231                 lckstp != lop->lo_stp &&
2232                 (clp != lop->lo_stp->ls_clp ||
2233                  lckstp->ls_ownerlen != lop->lo_stp->ls_ownerlen ||
2234                  NFSBCMP(lckstp->ls_owner, lop->lo_stp->ls_owner,
2235                     lckstp->ls_ownerlen))) {
2236                 if (other_lop) {
2237                     free(other_lop, M_NFSDLOCK);
2238                     other_lop = NULL;
2239                 }
2240                 if (vnode_unlocked != 0)
2241                     ret = nfsrv_clientconflict(lop->lo_stp->ls_clp, &haslock,
2242                         NULL, p);
2243                 else
2244                     ret = nfsrv_clientconflict(lop->lo_stp->ls_clp, &haslock,
2245                         vp, p);
2246                 if (ret == 1) {
2247                     if (filestruct_locked != 0) {
2248                         if (vnode_unlocked == 0) {
2249                                 ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl6");
2250                                 NFSVOPUNLOCK(vp, 0);
2251                         }
2252                         /* Roll back local locks. */
2253                         nfsrv_locallock_rollback(vp, lfp, p);
2254                         NFSLOCKSTATE();
2255                         nfsrv_unlocklf(lfp);
2256                         NFSUNLOCKSTATE();
2257                         NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
2258                         vnode_unlocked = 0;
2259                         if ((vp->v_iflag & VI_DOOMED) != 0) {
2260                                 error = NFSERR_SERVERFAULT;
2261                                 goto out;
2262                         }
2263                     }
2264                     /*
2265                      * nfsrv_clientconflict() unlocks state when it
2266                      * returns non-zero.
2267                      */
2268                     lckstp = NULL;
2269                     goto tryagain;
2270                 }
2271                 /*
2272                  * Found a conflicting lock, so record the conflict and
2273                  * return the error.
2274                  */
2275                 if (cfp != NULL && ret == 0) {
2276                     cfp->cl_clientid.lval[0]=lop->lo_stp->ls_stateid.other[0];
2277                     cfp->cl_clientid.lval[1]=lop->lo_stp->ls_stateid.other[1];
2278                     cfp->cl_first = lop->lo_first;
2279                     cfp->cl_end = lop->lo_end;
2280                     cfp->cl_flags = lop->lo_flags;
2281                     cfp->cl_ownerlen = lop->lo_stp->ls_ownerlen;
2282                     NFSBCOPY(lop->lo_stp->ls_owner, cfp->cl_owner,
2283                         cfp->cl_ownerlen);
2284                 }
2285                 if (ret == 2)
2286                     error = NFSERR_PERM;
2287                 else if (new_stp->ls_flags & NFSLCK_RECLAIM)
2288                     error = NFSERR_RECLAIMCONFLICT;
2289                 else if (new_stp->ls_flags & NFSLCK_CHECK)
2290                     error = NFSERR_LOCKED;
2291                 else
2292                     error = NFSERR_DENIED;
2293                 if (filestruct_locked != 0 && ret == 0) {
2294                         /* Roll back local locks. */
2295                         NFSUNLOCKSTATE();
2296                         if (vnode_unlocked == 0) {
2297                                 ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl7");
2298                                 vnode_unlocked = 1;
2299                                 NFSVOPUNLOCK(vp, 0);
2300                         }
2301                         nfsrv_locallock_rollback(vp, lfp, p);
2302                         NFSLOCKSTATE();
2303                         nfsrv_unlocklf(lfp);
2304                 }
2305                 if (ret == 0)
2306                         NFSUNLOCKSTATE();
2307                 goto out;
2308             }
2309           }
2310         }
2311
2312         /*
2313          * We only get here if there was no lock that conflicted.
2314          */
2315         if (new_stp->ls_flags & (NFSLCK_TEST | NFSLCK_CHECK)) {
2316                 NFSUNLOCKSTATE();
2317                 goto out;
2318         }
2319
2320         /*
2321          * We only get here when we are creating or modifying a lock.
2322          * There are two variants:
2323          * - exist_lock_owner where lock_owner exists
2324          * - open_to_lock_owner with new lock_owner
2325          */
2326         first = new_lop->lo_first;
2327         end = new_lop->lo_end;
2328         lock_flags = new_lop->lo_flags;
2329         if (!(new_stp->ls_flags & NFSLCK_OPENTOLOCK)) {
2330                 nfsrv_updatelock(lckstp, new_lopp, &other_lop, lfp);
2331                 stateidp->seqid = ++(lckstp->ls_stateid.seqid);
2332                 if ((nd->nd_flag & ND_NFSV41) != 0 && stateidp->seqid == 0)
2333                         stateidp->seqid = lckstp->ls_stateid.seqid = 1;
2334                 stateidp->other[0] = lckstp->ls_stateid.other[0];
2335                 stateidp->other[1] = lckstp->ls_stateid.other[1];
2336                 stateidp->other[2] = lckstp->ls_stateid.other[2];
2337         } else {
2338                 /*
2339                  * The new open_to_lock_owner case.
2340                  * Link the new nfsstate into the lists.
2341                  */
2342                 new_stp->ls_seq = new_stp->ls_opentolockseq;
2343                 nfsrvd_refcache(new_stp->ls_op);
2344                 stateidp->seqid = new_stp->ls_stateid.seqid = 1;
2345                 stateidp->other[0] = new_stp->ls_stateid.other[0] =
2346                     clp->lc_clientid.lval[0];
2347                 stateidp->other[1] = new_stp->ls_stateid.other[1] =
2348                     clp->lc_clientid.lval[1];
2349                 stateidp->other[2] = new_stp->ls_stateid.other[2] =
2350                     nfsrv_nextstateindex(clp);
2351                 new_stp->ls_clp = clp;
2352                 LIST_INIT(&new_stp->ls_lock);
2353                 new_stp->ls_openstp = stp;
2354                 new_stp->ls_lfp = lfp;
2355                 nfsrv_insertlock(new_lop, (struct nfslock *)new_stp, new_stp,
2356                     lfp);
2357                 LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_stp->ls_stateid),
2358                     new_stp, ls_hash);
2359                 LIST_INSERT_HEAD(&stp->ls_open, new_stp, ls_list);
2360                 *new_lopp = NULL;
2361                 *new_stpp = NULL;
2362                 nfsstatsv1.srvlockowners++;
2363                 nfsrv_openpluslock++;
2364         }
2365         if (filestruct_locked != 0) {
2366                 NFSUNLOCKSTATE();
2367                 nfsrv_locallock_commit(lfp, lock_flags, first, end);
2368                 NFSLOCKSTATE();
2369                 nfsrv_unlocklf(lfp);
2370         }
2371         NFSUNLOCKSTATE();
2372
2373 out:
2374         if (haslock) {
2375                 NFSLOCKV4ROOTMUTEX();
2376                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
2377                 NFSUNLOCKV4ROOTMUTEX();
2378         }
2379         if (vnode_unlocked != 0) {
2380                 NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
2381                 if (error == 0 && (vp->v_iflag & VI_DOOMED) != 0)
2382                         error = NFSERR_SERVERFAULT;
2383         }
2384         if (other_lop)
2385                 free(other_lop, M_NFSDLOCK);
2386         NFSEXITCODE2(error, nd);
2387         return (error);
2388 }
2389
2390 /*
2391  * Check for state errors for Open.
2392  * repstat is passed back out as an error if more critical errors
2393  * are not detected.
2394  */
2395 int
2396 nfsrv_opencheck(nfsquad_t clientid, nfsv4stateid_t *stateidp,
2397     struct nfsstate *new_stp, vnode_t vp, struct nfsrv_descript *nd,
2398     NFSPROC_T *p, int repstat)
2399 {
2400         struct nfsstate *stp, *nstp;
2401         struct nfsclient *clp;
2402         struct nfsstate *ownerstp;
2403         struct nfslockfile *lfp, *new_lfp;
2404         int error = 0, haslock = 0, ret, readonly = 0, getfhret = 0;
2405
2406         if ((new_stp->ls_flags & NFSLCK_SHAREBITS) == NFSLCK_READACCESS)
2407                 readonly = 1;
2408         /*
2409          * Check for restart conditions (client and server).
2410          */
2411         error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
2412                 &new_stp->ls_stateid, 0);
2413         if (error)
2414                 goto out;
2415
2416         /*
2417          * Check for state resource limit exceeded.
2418          * Technically this should be SMP protected, but the worst
2419          * case error is "out by one or two" on the count when it
2420          * returns NFSERR_RESOURCE and the limit is just a rather
2421          * arbitrary high water mark, so no harm is done.
2422          */
2423         if (nfsrv_openpluslock > nfsrv_v4statelimit) {
2424                 error = NFSERR_RESOURCE;
2425                 goto out;
2426         }
2427
2428 tryagain:
2429         new_lfp = malloc(sizeof (struct nfslockfile),
2430             M_NFSDLOCKFILE, M_WAITOK);
2431         if (vp)
2432                 getfhret = nfsrv_getlockfh(vp, new_stp->ls_flags, new_lfp,
2433                     NULL, p);
2434         NFSLOCKSTATE();
2435         /*
2436          * Get the nfsclient structure.
2437          */
2438         error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
2439             (nfsquad_t)((u_quad_t)0), 0, nd, p);
2440
2441         /*
2442          * Look up the open owner. See if it needs confirmation and
2443          * check the seq#, as required.
2444          */
2445         if (!error)
2446                 nfsrv_getowner(&clp->lc_open, new_stp, &ownerstp);
2447
2448         if (!error && ownerstp) {
2449                 error = nfsrv_checkseqid(nd, new_stp->ls_seq, ownerstp,
2450                     new_stp->ls_op);
2451                 /*
2452                  * If the OpenOwner hasn't been confirmed, assume the
2453                  * old one was a replay and this one is ok.
2454                  * See: RFC3530 Sec. 14.2.18.
2455                  */
2456                 if (error == NFSERR_BADSEQID &&
2457                     (ownerstp->ls_flags & NFSLCK_NEEDSCONFIRM))
2458                         error = 0;
2459         }
2460
2461         /*
2462          * Check for grace.
2463          */
2464         if (!error)
2465                 error = nfsrv_checkgrace(nd, clp, new_stp->ls_flags);
2466         if ((new_stp->ls_flags & NFSLCK_RECLAIM) && !error &&
2467                 nfsrv_checkstable(clp))
2468                 error = NFSERR_NOGRACE;
2469
2470         /*
2471          * If none of the above errors occurred, let repstat be
2472          * returned.
2473          */
2474         if (repstat && !error)
2475                 error = repstat;
2476         if (error) {
2477                 NFSUNLOCKSTATE();
2478                 if (haslock) {
2479                         NFSLOCKV4ROOTMUTEX();
2480                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
2481                         NFSUNLOCKV4ROOTMUTEX();
2482                 }
2483                 free(new_lfp, M_NFSDLOCKFILE);
2484                 goto out;
2485         }
2486
2487         /*
2488          * If vp == NULL, the file doesn't exist yet, so return ok.
2489          * (This always happens on the first pass, so haslock must be 0.)
2490          */
2491         if (vp == NULL) {
2492                 NFSUNLOCKSTATE();
2493                 free(new_lfp, M_NFSDLOCKFILE);
2494                 goto out;
2495         }
2496
2497         /*
2498          * Get the structure for the underlying file.
2499          */
2500         if (getfhret)
2501                 error = getfhret;
2502         else
2503                 error = nfsrv_getlockfile(new_stp->ls_flags, &new_lfp, &lfp,
2504                     NULL, 0);
2505         if (new_lfp)
2506                 free(new_lfp, M_NFSDLOCKFILE);
2507         if (error) {
2508                 NFSUNLOCKSTATE();
2509                 if (haslock) {
2510                         NFSLOCKV4ROOTMUTEX();
2511                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
2512                         NFSUNLOCKV4ROOTMUTEX();
2513                 }
2514                 goto out;
2515         }
2516
2517         /*
2518          * Search for a conflicting open/share.
2519          */
2520         if (new_stp->ls_flags & NFSLCK_DELEGCUR) {
2521             /*
2522              * For Delegate_Cur, search for the matching Delegation,
2523              * which indicates no conflict.
2524              * An old delegation should have been recovered by the
2525              * client doing a Claim_DELEGATE_Prev, so I won't let
2526              * it match and return NFSERR_EXPIRED. Should I let it
2527              * match?
2528              */
2529             LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
2530                 if (!(stp->ls_flags & NFSLCK_OLDDELEG) &&
2531                     (((nd->nd_flag & ND_NFSV41) != 0 &&
2532                     stateidp->seqid == 0) ||
2533                     stateidp->seqid == stp->ls_stateid.seqid) &&
2534                     !NFSBCMP(stateidp->other, stp->ls_stateid.other,
2535                           NFSX_STATEIDOTHER))
2536                         break;
2537             }
2538             if (stp == LIST_END(&lfp->lf_deleg) ||
2539                 ((new_stp->ls_flags & NFSLCK_WRITEACCESS) &&
2540                  (stp->ls_flags & NFSLCK_DELEGREAD))) {
2541                 NFSUNLOCKSTATE();
2542                 if (haslock) {
2543                         NFSLOCKV4ROOTMUTEX();
2544                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
2545                         NFSUNLOCKV4ROOTMUTEX();
2546                 }
2547                 error = NFSERR_EXPIRED;
2548                 goto out;
2549             }
2550         }
2551
2552         /*
2553          * Check for access/deny bit conflicts. I check for the same
2554          * owner as well, in case the client didn't bother.
2555          */
2556         LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
2557                 if (!(new_stp->ls_flags & NFSLCK_DELEGCUR) &&
2558                     (((new_stp->ls_flags & NFSLCK_ACCESSBITS) &
2559                       ((stp->ls_flags>>NFSLCK_SHIFT) & NFSLCK_ACCESSBITS))||
2560                      ((stp->ls_flags & NFSLCK_ACCESSBITS) &
2561                       ((new_stp->ls_flags>>NFSLCK_SHIFT)&NFSLCK_ACCESSBITS)))){
2562                         ret = nfsrv_clientconflict(stp->ls_clp,&haslock,vp,p);
2563                         if (ret == 1) {
2564                                 /*
2565                                  * nfsrv_clientconflict() unlocks
2566                                  * state when it returns non-zero.
2567                                  */
2568                                 goto tryagain;
2569                         }
2570                         if (ret == 2)
2571                                 error = NFSERR_PERM;
2572                         else if (new_stp->ls_flags & NFSLCK_RECLAIM)
2573                                 error = NFSERR_RECLAIMCONFLICT;
2574                         else
2575                                 error = NFSERR_SHAREDENIED;
2576                         if (ret == 0)
2577                                 NFSUNLOCKSTATE();
2578                         if (haslock) {
2579                                 NFSLOCKV4ROOTMUTEX();
2580                                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
2581                                 NFSUNLOCKV4ROOTMUTEX();
2582                         }
2583                         goto out;
2584                 }
2585         }
2586
2587         /*
2588          * Check for a conflicting delegation. If one is found, call
2589          * nfsrv_delegconflict() to handle it. If the v4root lock hasn't
2590          * been set yet, it will get the lock. Otherwise, it will recall
2591          * the delegation. Then, we try try again...
2592          * (If NFSLCK_DELEGCUR is set, it has a delegation, so there
2593          *  isn't a conflict.)
2594          * I currently believe the conflict algorithm to be:
2595          * For Open with Read Access and Deny None
2596          * - there is a conflict iff a different client has a write delegation
2597          * For Open with other Write Access or any Deny except None
2598          * - there is a conflict if a different client has any delegation
2599          * - there is a conflict if the same client has a read delegation
2600          *   (The current consensus is that this last case should be
2601          *    considered a conflict since the client with a read delegation
2602          *    could have done an Open with ReadAccess and WriteDeny
2603          *    locally and then not have checked for the WriteDeny.)
2604          * Don't check for a Reclaim, since that will be dealt with
2605          * by nfsrv_openctrl().
2606          */
2607         if (!(new_stp->ls_flags &
2608                 (NFSLCK_DELEGPREV | NFSLCK_DELEGCUR | NFSLCK_RECLAIM))) {
2609             stp = LIST_FIRST(&lfp->lf_deleg);
2610             while (stp != LIST_END(&lfp->lf_deleg)) {
2611                 nstp = LIST_NEXT(stp, ls_file);
2612                 if ((readonly && stp->ls_clp != clp &&
2613                        (stp->ls_flags & NFSLCK_DELEGWRITE)) ||
2614                     (!readonly && (stp->ls_clp != clp ||
2615                          (stp->ls_flags & NFSLCK_DELEGREAD)))) {
2616                         ret = nfsrv_delegconflict(stp, &haslock, p, vp);
2617                         if (ret) {
2618                             /*
2619                              * nfsrv_delegconflict() unlocks state
2620                              * when it returns non-zero.
2621                              */
2622                             if (ret == -1)
2623                                 goto tryagain;
2624                             error = ret;
2625                             goto out;
2626                         }
2627                 }
2628                 stp = nstp;
2629             }
2630         }
2631         NFSUNLOCKSTATE();
2632         if (haslock) {
2633                 NFSLOCKV4ROOTMUTEX();
2634                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
2635                 NFSUNLOCKV4ROOTMUTEX();
2636         }
2637
2638 out:
2639         NFSEXITCODE2(error, nd);
2640         return (error);
2641 }
2642
2643 /*
2644  * Open control function to create/update open state for an open.
2645  */
2646 int
2647 nfsrv_openctrl(struct nfsrv_descript *nd, vnode_t vp,
2648     struct nfsstate **new_stpp, nfsquad_t clientid, nfsv4stateid_t *stateidp,
2649     nfsv4stateid_t *delegstateidp, u_int32_t *rflagsp, struct nfsexstuff *exp,
2650     NFSPROC_T *p, u_quad_t filerev)
2651 {
2652         struct nfsstate *new_stp = *new_stpp;
2653         struct nfsstate *stp, *nstp;
2654         struct nfsstate *openstp = NULL, *new_open, *ownerstp, *new_deleg;
2655         struct nfslockfile *lfp, *new_lfp;
2656         struct nfsclient *clp;
2657         int error = 0, haslock = 0, ret, delegate = 1, writedeleg = 1;
2658         int readonly = 0, cbret = 1, getfhret = 0;
2659         int gotstate = 0, len = 0;
2660         u_char *clidp = NULL;
2661
2662         if ((new_stp->ls_flags & NFSLCK_SHAREBITS) == NFSLCK_READACCESS)
2663                 readonly = 1;
2664         /*
2665          * Check for restart conditions (client and server).
2666          * (Paranoia, should have been detected by nfsrv_opencheck().)
2667          * If an error does show up, return NFSERR_EXPIRED, since the
2668          * the seqid# has already been incremented.
2669          */
2670         error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
2671             &new_stp->ls_stateid, 0);
2672         if (error) {
2673                 printf("Nfsd: openctrl unexpected restart err=%d\n",
2674                     error);
2675                 error = NFSERR_EXPIRED;
2676                 goto out;
2677         }
2678
2679         clidp = malloc(NFSV4_OPAQUELIMIT, M_TEMP, M_WAITOK);
2680 tryagain:
2681         new_lfp = malloc(sizeof (struct nfslockfile),
2682             M_NFSDLOCKFILE, M_WAITOK);
2683         new_open = malloc(sizeof (struct nfsstate),
2684             M_NFSDSTATE, M_WAITOK);
2685         new_deleg = malloc(sizeof (struct nfsstate),
2686             M_NFSDSTATE, M_WAITOK);
2687         getfhret = nfsrv_getlockfh(vp, new_stp->ls_flags, new_lfp,
2688             NULL, p);
2689         NFSLOCKSTATE();
2690         /*
2691          * Get the client structure. Since the linked lists could be changed
2692          * by other nfsd processes if this process does a tsleep(), one of
2693          * two things must be done.
2694          * 1 - don't tsleep()
2695          * or
2696          * 2 - get the nfsv4_lock() { indicated by haslock == 1 }
2697          *     before using the lists, since this lock stops the other
2698          *     nfsd. This should only be used for rare cases, since it
2699          *     essentially single threads the nfsd.
2700          *     At this time, it is only done for cases where the stable
2701          *     storage file must be written prior to completion of state
2702          *     expiration.
2703          */
2704         error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
2705             (nfsquad_t)((u_quad_t)0), 0, nd, p);
2706         if (!error && (clp->lc_flags & LCL_NEEDSCBNULL) &&
2707             clp->lc_program) {
2708                 /*
2709                  * This happens on the first open for a client
2710                  * that supports callbacks.
2711                  */
2712                 NFSUNLOCKSTATE();
2713                 /*
2714                  * Although nfsrv_docallback() will sleep, clp won't
2715                  * go away, since they are only removed when the
2716                  * nfsv4_lock() has blocked the nfsd threads. The
2717                  * fields in clp can change, but having multiple
2718                  * threads do this Null callback RPC should be
2719                  * harmless.
2720                  */
2721                 cbret = nfsrv_docallback(clp, NFSV4PROC_CBNULL,
2722                     NULL, 0, NULL, NULL, NULL, 0, p);
2723                 NFSLOCKSTATE();
2724                 clp->lc_flags &= ~LCL_NEEDSCBNULL;
2725                 if (!cbret)
2726                         clp->lc_flags |= LCL_CALLBACKSON;
2727         }
2728
2729         /*
2730          * Look up the open owner. See if it needs confirmation and
2731          * check the seq#, as required.
2732          */
2733         if (!error)
2734                 nfsrv_getowner(&clp->lc_open, new_stp, &ownerstp);
2735
2736         if (error) {
2737                 NFSUNLOCKSTATE();
2738                 printf("Nfsd: openctrl unexpected state err=%d\n",
2739                         error);
2740                 free(new_lfp, M_NFSDLOCKFILE);
2741                 free(new_open, M_NFSDSTATE);
2742                 free(new_deleg, M_NFSDSTATE);
2743                 if (haslock) {
2744                         NFSLOCKV4ROOTMUTEX();
2745                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
2746                         NFSUNLOCKV4ROOTMUTEX();
2747                 }
2748                 error = NFSERR_EXPIRED;
2749                 goto out;
2750         }
2751
2752         if (new_stp->ls_flags & NFSLCK_RECLAIM)
2753                 nfsrv_markstable(clp);
2754
2755         /*
2756          * Get the structure for the underlying file.
2757          */
2758         if (getfhret)
2759                 error = getfhret;
2760         else
2761                 error = nfsrv_getlockfile(new_stp->ls_flags, &new_lfp, &lfp,
2762                     NULL, 0);
2763         if (new_lfp)
2764                 free(new_lfp, M_NFSDLOCKFILE);
2765         if (error) {
2766                 NFSUNLOCKSTATE();
2767                 printf("Nfsd openctrl unexpected getlockfile err=%d\n",
2768                     error);
2769                 free(new_open, M_NFSDSTATE);
2770                 free(new_deleg, M_NFSDSTATE);
2771                 if (haslock) {
2772                         NFSLOCKV4ROOTMUTEX();
2773                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
2774                         NFSUNLOCKV4ROOTMUTEX();
2775                 }
2776                 goto out;
2777         }
2778
2779         /*
2780          * Search for a conflicting open/share.
2781          */
2782         if (new_stp->ls_flags & NFSLCK_DELEGCUR) {
2783             /*
2784              * For Delegate_Cur, search for the matching Delegation,
2785              * which indicates no conflict.
2786              * An old delegation should have been recovered by the
2787              * client doing a Claim_DELEGATE_Prev, so I won't let
2788              * it match and return NFSERR_EXPIRED. Should I let it
2789              * match?
2790              */
2791             LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
2792                 if (!(stp->ls_flags & NFSLCK_OLDDELEG) &&
2793                     (((nd->nd_flag & ND_NFSV41) != 0 &&
2794                     stateidp->seqid == 0) ||
2795                     stateidp->seqid == stp->ls_stateid.seqid) &&
2796                     !NFSBCMP(stateidp->other, stp->ls_stateid.other,
2797                         NFSX_STATEIDOTHER))
2798                         break;
2799             }
2800             if (stp == LIST_END(&lfp->lf_deleg) ||
2801                 ((new_stp->ls_flags & NFSLCK_WRITEACCESS) &&
2802                  (stp->ls_flags & NFSLCK_DELEGREAD))) {
2803                 NFSUNLOCKSTATE();
2804                 printf("Nfsd openctrl unexpected expiry\n");
2805                 free(new_open, M_NFSDSTATE);
2806                 free(new_deleg, M_NFSDSTATE);
2807                 if (haslock) {
2808                         NFSLOCKV4ROOTMUTEX();
2809                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
2810                         NFSUNLOCKV4ROOTMUTEX();
2811                 }
2812                 error = NFSERR_EXPIRED;
2813                 goto out;
2814             }
2815
2816             /*
2817              * Don't issue a Delegation, since one already exists and
2818              * delay delegation timeout, as required.
2819              */
2820             delegate = 0;
2821             nfsrv_delaydelegtimeout(stp);
2822         }
2823
2824         /*
2825          * Check for access/deny bit conflicts. I also check for the
2826          * same owner, since the client might not have bothered to check.
2827          * Also, note an open for the same file and owner, if found,
2828          * which is all we do here for Delegate_Cur, since conflict
2829          * checking is already done.
2830          */
2831         LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
2832                 if (ownerstp && stp->ls_openowner == ownerstp)
2833                         openstp = stp;
2834                 if (!(new_stp->ls_flags & NFSLCK_DELEGCUR)) {
2835                     /*
2836                      * If another client has the file open, the only
2837                      * delegation that can be issued is a Read delegation
2838                      * and only if it is a Read open with Deny none.
2839                      */
2840                     if (clp != stp->ls_clp) {
2841                         if ((stp->ls_flags & NFSLCK_SHAREBITS) ==
2842                             NFSLCK_READACCESS)
2843                             writedeleg = 0;
2844                         else
2845                             delegate = 0;
2846                     }
2847                     if(((new_stp->ls_flags & NFSLCK_ACCESSBITS) &
2848                         ((stp->ls_flags>>NFSLCK_SHIFT) & NFSLCK_ACCESSBITS))||
2849                        ((stp->ls_flags & NFSLCK_ACCESSBITS) &
2850                         ((new_stp->ls_flags>>NFSLCK_SHIFT)&NFSLCK_ACCESSBITS))){
2851                         ret = nfsrv_clientconflict(stp->ls_clp,&haslock,vp,p);
2852                         if (ret == 1) {
2853                                 /*
2854                                  * nfsrv_clientconflict() unlocks state
2855                                  * when it returns non-zero.
2856                                  */
2857                                 free(new_open, M_NFSDSTATE);
2858                                 free(new_deleg, M_NFSDSTATE);
2859                                 openstp = NULL;
2860                                 goto tryagain;
2861                         }
2862                         if (ret == 2)
2863                                 error = NFSERR_PERM;
2864                         else if (new_stp->ls_flags & NFSLCK_RECLAIM)
2865                                 error = NFSERR_RECLAIMCONFLICT;
2866                         else
2867                                 error = NFSERR_SHAREDENIED;
2868                         if (ret == 0)
2869                                 NFSUNLOCKSTATE();
2870                         if (haslock) {
2871                                 NFSLOCKV4ROOTMUTEX();
2872                                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
2873                                 NFSUNLOCKV4ROOTMUTEX();
2874                         }
2875                         free(new_open, M_NFSDSTATE);
2876                         free(new_deleg, M_NFSDSTATE);
2877                         printf("nfsd openctrl unexpected client cnfl\n");
2878                         goto out;
2879                     }
2880                 }
2881         }
2882
2883         /*
2884          * Check for a conflicting delegation. If one is found, call
2885          * nfsrv_delegconflict() to handle it. If the v4root lock hasn't
2886          * been set yet, it will get the lock. Otherwise, it will recall
2887          * the delegation. Then, we try try again...
2888          * (If NFSLCK_DELEGCUR is set, it has a delegation, so there
2889          *  isn't a conflict.)
2890          * I currently believe the conflict algorithm to be:
2891          * For Open with Read Access and Deny None
2892          * - there is a conflict iff a different client has a write delegation
2893          * For Open with other Write Access or any Deny except None
2894          * - there is a conflict if a different client has any delegation
2895          * - there is a conflict if the same client has a read delegation
2896          *   (The current consensus is that this last case should be
2897          *    considered a conflict since the client with a read delegation
2898          *    could have done an Open with ReadAccess and WriteDeny
2899          *    locally and then not have checked for the WriteDeny.)
2900          */
2901         if (!(new_stp->ls_flags & (NFSLCK_DELEGPREV | NFSLCK_DELEGCUR))) {
2902             stp = LIST_FIRST(&lfp->lf_deleg);
2903             while (stp != LIST_END(&lfp->lf_deleg)) {
2904                 nstp = LIST_NEXT(stp, ls_file);
2905                 if (stp->ls_clp != clp && (stp->ls_flags & NFSLCK_DELEGREAD))
2906                         writedeleg = 0;
2907                 else
2908                         delegate = 0;
2909                 if ((readonly && stp->ls_clp != clp &&
2910                        (stp->ls_flags & NFSLCK_DELEGWRITE)) ||
2911                     (!readonly && (stp->ls_clp != clp ||
2912                          (stp->ls_flags & NFSLCK_DELEGREAD)))) {
2913                     if (new_stp->ls_flags & NFSLCK_RECLAIM) {
2914                         delegate = 2;
2915                     } else {
2916                         ret = nfsrv_delegconflict(stp, &haslock, p, vp);
2917                         if (ret) {
2918                             /*
2919                              * nfsrv_delegconflict() unlocks state
2920                              * when it returns non-zero.
2921                              */
2922                             printf("Nfsd openctrl unexpected deleg cnfl\n");
2923                             free(new_open, M_NFSDSTATE);
2924                             free(new_deleg, M_NFSDSTATE);
2925                             if (ret == -1) {
2926                                 openstp = NULL;
2927                                 goto tryagain;
2928                             }
2929                             error = ret;
2930                             goto out;
2931                         }
2932                     }
2933                 }
2934                 stp = nstp;
2935             }
2936         }
2937
2938         /*
2939          * We only get here if there was no open that conflicted.
2940          * If an open for the owner exists, or in the access/deny bits.
2941          * Otherwise it is a new open. If the open_owner hasn't been
2942          * confirmed, replace the open with the new one needing confirmation,
2943          * otherwise add the open.
2944          */
2945         if (new_stp->ls_flags & NFSLCK_DELEGPREV) {
2946             /*
2947              * Handle NFSLCK_DELEGPREV by searching the old delegations for
2948              * a match. If found, just move the old delegation to the current
2949              * delegation list and issue open. If not found, return
2950              * NFSERR_EXPIRED.
2951              */
2952             LIST_FOREACH(stp, &clp->lc_olddeleg, ls_list) {
2953                 if (stp->ls_lfp == lfp) {
2954                     /* Found it */
2955                     if (stp->ls_clp != clp)
2956                         panic("olddeleg clp");
2957                     LIST_REMOVE(stp, ls_list);
2958                     LIST_REMOVE(stp, ls_hash);
2959                     stp->ls_flags &= ~NFSLCK_OLDDELEG;
2960                     stp->ls_stateid.seqid = delegstateidp->seqid = 1;
2961                     stp->ls_stateid.other[0] = delegstateidp->other[0] =
2962                         clp->lc_clientid.lval[0];
2963                     stp->ls_stateid.other[1] = delegstateidp->other[1] =
2964                         clp->lc_clientid.lval[1];
2965                     stp->ls_stateid.other[2] = delegstateidp->other[2] =
2966                         nfsrv_nextstateindex(clp);
2967                     stp->ls_compref = nd->nd_compref;
2968                     LIST_INSERT_HEAD(&clp->lc_deleg, stp, ls_list);
2969                     LIST_INSERT_HEAD(NFSSTATEHASH(clp,
2970                         stp->ls_stateid), stp, ls_hash);
2971                     if (stp->ls_flags & NFSLCK_DELEGWRITE)
2972                         *rflagsp |= NFSV4OPEN_WRITEDELEGATE;
2973                     else
2974                         *rflagsp |= NFSV4OPEN_READDELEGATE;
2975                     clp->lc_delegtime = NFSD_MONOSEC +
2976                         nfsrv_lease + NFSRV_LEASEDELTA;
2977
2978                     /*
2979                      * Now, do the associated open.
2980                      */
2981                     new_open->ls_stateid.seqid = 1;
2982                     new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
2983                     new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
2984                     new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
2985                     new_open->ls_flags = (new_stp->ls_flags&NFSLCK_DENYBITS)|
2986                         NFSLCK_OPEN;
2987                     if (stp->ls_flags & NFSLCK_DELEGWRITE)
2988                         new_open->ls_flags |= (NFSLCK_READACCESS |
2989                             NFSLCK_WRITEACCESS);
2990                     else
2991                         new_open->ls_flags |= NFSLCK_READACCESS;
2992                     new_open->ls_uid = new_stp->ls_uid;
2993                     new_open->ls_lfp = lfp;
2994                     new_open->ls_clp = clp;
2995                     LIST_INIT(&new_open->ls_open);
2996                     LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
2997                     LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
2998                         new_open, ls_hash);
2999                     /*
3000                      * and handle the open owner
3001                      */
3002                     if (ownerstp) {
3003                         new_open->ls_openowner = ownerstp;
3004                         LIST_INSERT_HEAD(&ownerstp->ls_open,new_open,ls_list);
3005                     } else {
3006                         new_open->ls_openowner = new_stp;
3007                         new_stp->ls_flags = 0;
3008                         nfsrvd_refcache(new_stp->ls_op);
3009                         new_stp->ls_noopens = 0;
3010                         LIST_INIT(&new_stp->ls_open);
3011                         LIST_INSERT_HEAD(&new_stp->ls_open, new_open, ls_list);
3012                         LIST_INSERT_HEAD(&clp->lc_open, new_stp, ls_list);
3013                         *new_stpp = NULL;
3014                         nfsstatsv1.srvopenowners++;
3015                         nfsrv_openpluslock++;
3016                     }
3017                     openstp = new_open;
3018                     new_open = NULL;
3019                     nfsstatsv1.srvopens++;
3020                     nfsrv_openpluslock++;
3021                     break;
3022                 }
3023             }
3024             if (stp == LIST_END(&clp->lc_olddeleg))
3025                 error = NFSERR_EXPIRED;
3026         } else if (new_stp->ls_flags & (NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) {
3027             /*
3028              * Scan to see that no delegation for this client and file
3029              * doesn't already exist.
3030              * There also shouldn't yet be an Open for this file and
3031              * openowner.
3032              */
3033             LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
3034                 if (stp->ls_clp == clp)
3035                     break;
3036             }
3037             if (stp == LIST_END(&lfp->lf_deleg) && openstp == NULL) {
3038                 /*
3039                  * This is the Claim_Previous case with a delegation
3040                  * type != Delegate_None.
3041                  */
3042                 /*
3043                  * First, add the delegation. (Although we must issue the
3044                  * delegation, we can also ask for an immediate return.)
3045                  */
3046                 new_deleg->ls_stateid.seqid = delegstateidp->seqid = 1;
3047                 new_deleg->ls_stateid.other[0] = delegstateidp->other[0] =
3048                     clp->lc_clientid.lval[0];
3049                 new_deleg->ls_stateid.other[1] = delegstateidp->other[1] =
3050                     clp->lc_clientid.lval[1];
3051                 new_deleg->ls_stateid.other[2] = delegstateidp->other[2] =
3052                     nfsrv_nextstateindex(clp);
3053                 if (new_stp->ls_flags & NFSLCK_DELEGWRITE) {
3054                     new_deleg->ls_flags = (NFSLCK_DELEGWRITE |
3055                         NFSLCK_READACCESS | NFSLCK_WRITEACCESS);
3056                     *rflagsp |= NFSV4OPEN_WRITEDELEGATE;
3057                     nfsrv_writedelegcnt++;
3058                 } else {
3059                     new_deleg->ls_flags = (NFSLCK_DELEGREAD |
3060                         NFSLCK_READACCESS);
3061                     *rflagsp |= NFSV4OPEN_READDELEGATE;
3062                 }
3063                 new_deleg->ls_uid = new_stp->ls_uid;
3064                 new_deleg->ls_lfp = lfp;
3065                 new_deleg->ls_clp = clp;
3066                 new_deleg->ls_filerev = filerev;
3067                 new_deleg->ls_compref = nd->nd_compref;
3068                 LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg, ls_file);
3069                 LIST_INSERT_HEAD(NFSSTATEHASH(clp,
3070                     new_deleg->ls_stateid), new_deleg, ls_hash);
3071                 LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg, ls_list);
3072                 new_deleg = NULL;
3073                 if (delegate == 2 || nfsrv_issuedelegs == 0 ||
3074                     (clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) !=
3075                      LCL_CALLBACKSON ||
3076                     NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt) ||
3077                     !NFSVNO_DELEGOK(vp))
3078                     *rflagsp |= NFSV4OPEN_RECALL;
3079                 nfsstatsv1.srvdelegates++;
3080                 nfsrv_openpluslock++;
3081                 nfsrv_delegatecnt++;
3082
3083                 /*
3084                  * Now, do the associated open.
3085                  */
3086                 new_open->ls_stateid.seqid = 1;
3087                 new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
3088                 new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
3089                 new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
3090                 new_open->ls_flags = (new_stp->ls_flags & NFSLCK_DENYBITS) |
3091                     NFSLCK_OPEN;
3092                 if (new_stp->ls_flags & NFSLCK_DELEGWRITE)
3093                         new_open->ls_flags |= (NFSLCK_READACCESS |
3094                             NFSLCK_WRITEACCESS);
3095                 else
3096                         new_open->ls_flags |= NFSLCK_READACCESS;
3097                 new_open->ls_uid = new_stp->ls_uid;
3098                 new_open->ls_lfp = lfp;
3099                 new_open->ls_clp = clp;
3100                 LIST_INIT(&new_open->ls_open);
3101                 LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
3102                 LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
3103                    new_open, ls_hash);
3104                 /*
3105                  * and handle the open owner
3106                  */
3107                 if (ownerstp) {
3108                     new_open->ls_openowner = ownerstp;
3109                     LIST_INSERT_HEAD(&ownerstp->ls_open, new_open, ls_list);
3110                 } else {
3111                     new_open->ls_openowner = new_stp;
3112                     new_stp->ls_flags = 0;
3113                     nfsrvd_refcache(new_stp->ls_op);
3114                     new_stp->ls_noopens = 0;
3115                     LIST_INIT(&new_stp->ls_open);
3116                     LIST_INSERT_HEAD(&new_stp->ls_open, new_open, ls_list);
3117                     LIST_INSERT_HEAD(&clp->lc_open, new_stp, ls_list);
3118                     *new_stpp = NULL;
3119                     nfsstatsv1.srvopenowners++;
3120                     nfsrv_openpluslock++;
3121                 }
3122                 openstp = new_open;
3123                 new_open = NULL;
3124                 nfsstatsv1.srvopens++;
3125                 nfsrv_openpluslock++;
3126             } else {
3127                 error = NFSERR_RECLAIMCONFLICT;
3128             }
3129         } else if (ownerstp) {
3130                 if (ownerstp->ls_flags & NFSLCK_NEEDSCONFIRM) {
3131                     /* Replace the open */
3132                     if (ownerstp->ls_op)
3133                         nfsrvd_derefcache(ownerstp->ls_op);
3134                     ownerstp->ls_op = new_stp->ls_op;
3135                     nfsrvd_refcache(ownerstp->ls_op);
3136                     ownerstp->ls_seq = new_stp->ls_seq;
3137                     *rflagsp |= NFSV4OPEN_RESULTCONFIRM;
3138                     stp = LIST_FIRST(&ownerstp->ls_open);
3139                     stp->ls_flags = (new_stp->ls_flags & NFSLCK_SHAREBITS) |
3140                         NFSLCK_OPEN;
3141                     stp->ls_stateid.seqid = 1;
3142                     stp->ls_uid = new_stp->ls_uid;
3143                     if (lfp != stp->ls_lfp) {
3144                         LIST_REMOVE(stp, ls_file);
3145                         LIST_INSERT_HEAD(&lfp->lf_open, stp, ls_file);
3146                         stp->ls_lfp = lfp;
3147                     }
3148                     openstp = stp;
3149                 } else if (openstp) {
3150                     openstp->ls_flags |= (new_stp->ls_flags & NFSLCK_SHAREBITS);
3151                     openstp->ls_stateid.seqid++;
3152                     if ((nd->nd_flag & ND_NFSV41) != 0 &&
3153                         openstp->ls_stateid.seqid == 0)
3154                         openstp->ls_stateid.seqid = 1;
3155
3156                     /*
3157                      * This is where we can choose to issue a delegation.
3158                      */
3159                     if ((new_stp->ls_flags & NFSLCK_WANTNODELEG) != 0)
3160                         *rflagsp |= NFSV4OPEN_WDNOTWANTED;
3161                     else if (nfsrv_issuedelegs == 0)
3162                         *rflagsp |= NFSV4OPEN_WDSUPPFTYPE;
3163                     else if (NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt))
3164                         *rflagsp |= NFSV4OPEN_WDRESOURCE;
3165                     else if (delegate == 0 || writedeleg == 0 ||
3166                         NFSVNO_EXRDONLY(exp) || (readonly != 0 &&
3167                         nfsrv_writedelegifpos == 0) ||
3168                         !NFSVNO_DELEGOK(vp) ||
3169                         (new_stp->ls_flags & NFSLCK_WANTRDELEG) != 0 ||
3170                         (clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) !=
3171                          LCL_CALLBACKSON)
3172                         *rflagsp |= NFSV4OPEN_WDCONTENTION;
3173                     else {
3174                         new_deleg->ls_stateid.seqid = delegstateidp->seqid = 1;
3175                         new_deleg->ls_stateid.other[0] = delegstateidp->other[0]
3176                             = clp->lc_clientid.lval[0];
3177                         new_deleg->ls_stateid.other[1] = delegstateidp->other[1]
3178                             = clp->lc_clientid.lval[1];
3179                         new_deleg->ls_stateid.other[2] = delegstateidp->other[2]
3180                             = nfsrv_nextstateindex(clp);
3181                         new_deleg->ls_flags = (NFSLCK_DELEGWRITE |
3182                             NFSLCK_READACCESS | NFSLCK_WRITEACCESS);
3183                         *rflagsp |= NFSV4OPEN_WRITEDELEGATE;
3184                         new_deleg->ls_uid = new_stp->ls_uid;
3185                         new_deleg->ls_lfp = lfp;
3186                         new_deleg->ls_clp = clp;
3187                         new_deleg->ls_filerev = filerev;
3188                         new_deleg->ls_compref = nd->nd_compref;
3189                         nfsrv_writedelegcnt++;
3190                         LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg, ls_file);
3191                         LIST_INSERT_HEAD(NFSSTATEHASH(clp,
3192                             new_deleg->ls_stateid), new_deleg, ls_hash);
3193                         LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg, ls_list);
3194                         new_deleg = NULL;
3195                         nfsstatsv1.srvdelegates++;
3196                         nfsrv_openpluslock++;
3197                         nfsrv_delegatecnt++;
3198                     }
3199                 } else {
3200                     new_open->ls_stateid.seqid = 1;
3201                     new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
3202                     new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
3203                     new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
3204                     new_open->ls_flags = (new_stp->ls_flags & NFSLCK_SHAREBITS)|
3205                         NFSLCK_OPEN;
3206                     new_open->ls_uid = new_stp->ls_uid;
3207                     new_open->ls_openowner = ownerstp;
3208                     new_open->ls_lfp = lfp;
3209                     new_open->ls_clp = clp;
3210                     LIST_INIT(&new_open->ls_open);
3211                     LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
3212                     LIST_INSERT_HEAD(&ownerstp->ls_open, new_open, ls_list);
3213                     LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
3214                         new_open, ls_hash);
3215                     openstp = new_open;
3216                     new_open = NULL;
3217                     nfsstatsv1.srvopens++;
3218                     nfsrv_openpluslock++;
3219
3220                     /*
3221                      * This is where we can choose to issue a delegation.
3222                      */
3223                     if ((new_stp->ls_flags & NFSLCK_WANTNODELEG) != 0)
3224                         *rflagsp |= NFSV4OPEN_WDNOTWANTED;
3225                     else if (nfsrv_issuedelegs == 0)
3226                         *rflagsp |= NFSV4OPEN_WDSUPPFTYPE;
3227                     else if (NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt))
3228                         *rflagsp |= NFSV4OPEN_WDRESOURCE;
3229                     else if (delegate == 0 || (writedeleg == 0 &&
3230                         readonly == 0) || !NFSVNO_DELEGOK(vp) ||
3231                         (clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) !=
3232                          LCL_CALLBACKSON)
3233                         *rflagsp |= NFSV4OPEN_WDCONTENTION;
3234                     else {
3235                         new_deleg->ls_stateid.seqid = delegstateidp->seqid = 1;
3236                         new_deleg->ls_stateid.other[0] = delegstateidp->other[0]
3237                             = clp->lc_clientid.lval[0];
3238                         new_deleg->ls_stateid.other[1] = delegstateidp->other[1]
3239                             = clp->lc_clientid.lval[1];
3240                         new_deleg->ls_stateid.other[2] = delegstateidp->other[2]
3241                             = nfsrv_nextstateindex(clp);
3242                         if (writedeleg && !NFSVNO_EXRDONLY(exp) &&
3243                             (nfsrv_writedelegifpos || !readonly) &&
3244                             (new_stp->ls_flags & NFSLCK_WANTRDELEG) == 0) {
3245                             new_deleg->ls_flags = (NFSLCK_DELEGWRITE |
3246                                 NFSLCK_READACCESS | NFSLCK_WRITEACCESS);
3247                             *rflagsp |= NFSV4OPEN_WRITEDELEGATE;
3248                             nfsrv_writedelegcnt++;
3249                         } else {
3250                             new_deleg->ls_flags = (NFSLCK_DELEGREAD |
3251                                 NFSLCK_READACCESS);
3252                             *rflagsp |= NFSV4OPEN_READDELEGATE;
3253                         }
3254                         new_deleg->ls_uid = new_stp->ls_uid;
3255                         new_deleg->ls_lfp = lfp;
3256                         new_deleg->ls_clp = clp;
3257                         new_deleg->ls_filerev = filerev;
3258                         new_deleg->ls_compref = nd->nd_compref;
3259                         LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg, ls_file);
3260                         LIST_INSERT_HEAD(NFSSTATEHASH(clp,
3261                             new_deleg->ls_stateid), new_deleg, ls_hash);
3262                         LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg, ls_list);
3263                         new_deleg = NULL;
3264                         nfsstatsv1.srvdelegates++;
3265                         nfsrv_openpluslock++;
3266                         nfsrv_delegatecnt++;
3267                     }
3268                 }
3269         } else {
3270                 /*
3271                  * New owner case. Start the open_owner sequence with a
3272                  * Needs confirmation (unless a reclaim) and hang the
3273                  * new open off it.
3274                  */
3275                 new_open->ls_stateid.seqid = 1;
3276                 new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
3277                 new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
3278                 new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
3279                 new_open->ls_flags = (new_stp->ls_flags & NFSLCK_SHAREBITS) |
3280                     NFSLCK_OPEN;
3281                 new_open->ls_uid = new_stp->ls_uid;
3282                 LIST_INIT(&new_open->ls_open);
3283                 new_open->ls_openowner = new_stp;
3284                 new_open->ls_lfp = lfp;
3285                 new_open->ls_clp = clp;
3286                 LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
3287                 if (new_stp->ls_flags & NFSLCK_RECLAIM) {
3288                         new_stp->ls_flags = 0;
3289                 } else if ((nd->nd_flag & ND_NFSV41) != 0) {
3290                         /* NFSv4.1 never needs confirmation. */
3291                         new_stp->ls_flags = 0;
3292
3293                         /*
3294                          * This is where we can choose to issue a delegation.
3295                          */
3296                         if (delegate && nfsrv_issuedelegs &&
3297                             (writedeleg || readonly) &&
3298                             (clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) ==
3299                              LCL_CALLBACKSON &&
3300                             !NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt) &&
3301                             NFSVNO_DELEGOK(vp) &&
3302                             ((nd->nd_flag & ND_NFSV41) == 0 ||
3303                              (new_stp->ls_flags & NFSLCK_WANTNODELEG) == 0)) {
3304                                 new_deleg->ls_stateid.seqid =
3305                                     delegstateidp->seqid = 1;
3306                                 new_deleg->ls_stateid.other[0] =
3307                                     delegstateidp->other[0]
3308                                     = clp->lc_clientid.lval[0];
3309                                 new_deleg->ls_stateid.other[1] =
3310                                     delegstateidp->other[1]
3311                                     = clp->lc_clientid.lval[1];
3312                                 new_deleg->ls_stateid.other[2] =
3313                                     delegstateidp->other[2]
3314                                     = nfsrv_nextstateindex(clp);
3315                                 if (writedeleg && !NFSVNO_EXRDONLY(exp) &&
3316                                     (nfsrv_writedelegifpos || !readonly) &&
3317                                     ((nd->nd_flag & ND_NFSV41) == 0 ||
3318                                      (new_stp->ls_flags & NFSLCK_WANTRDELEG) ==
3319                                      0)) {
3320                                         new_deleg->ls_flags =
3321                                             (NFSLCK_DELEGWRITE |
3322                                              NFSLCK_READACCESS |
3323                                              NFSLCK_WRITEACCESS);
3324                                         *rflagsp |= NFSV4OPEN_WRITEDELEGATE;
3325                                         nfsrv_writedelegcnt++;
3326                                 } else {
3327                                         new_deleg->ls_flags =
3328                                             (NFSLCK_DELEGREAD |
3329                                              NFSLCK_READACCESS);
3330                                         *rflagsp |= NFSV4OPEN_READDELEGATE;
3331                                 }
3332                                 new_deleg->ls_uid = new_stp->ls_uid;
3333                                 new_deleg->ls_lfp = lfp;
3334                                 new_deleg->ls_clp = clp;
3335                                 new_deleg->ls_filerev = filerev;
3336                                 new_deleg->ls_compref = nd->nd_compref;
3337                                 LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg,
3338                                     ls_file);
3339                                 LIST_INSERT_HEAD(NFSSTATEHASH(clp,
3340                                     new_deleg->ls_stateid), new_deleg, ls_hash);
3341                                 LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg,
3342                                     ls_list);
3343                                 new_deleg = NULL;
3344                                 nfsstatsv1.srvdelegates++;
3345                                 nfsrv_openpluslock++;
3346                                 nfsrv_delegatecnt++;
3347                         }
3348                         /*
3349                          * Since NFSv4.1 never does an OpenConfirm, the first
3350                          * open state will be acquired here.
3351                          */
3352                         if (!(clp->lc_flags & LCL_STAMPEDSTABLE)) {
3353                                 clp->lc_flags |= LCL_STAMPEDSTABLE;
3354                                 len = clp->lc_idlen;
3355                                 NFSBCOPY(clp->lc_id, clidp, len);
3356                                 gotstate = 1;
3357                         }
3358                 } else {
3359                         *rflagsp |= NFSV4OPEN_RESULTCONFIRM;
3360                         new_stp->ls_flags = NFSLCK_NEEDSCONFIRM;
3361                 }
3362                 nfsrvd_refcache(new_stp->ls_op);
3363                 new_stp->ls_noopens = 0;
3364                 LIST_INIT(&new_stp->ls_open);
3365                 LIST_INSERT_HEAD(&new_stp->ls_open, new_open, ls_list);
3366                 LIST_INSERT_HEAD(&clp->lc_open, new_stp, ls_list);
3367                 LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
3368                     new_open, ls_hash);
3369                 openstp = new_open;
3370                 new_open = NULL;
3371                 *new_stpp = NULL;
3372                 nfsstatsv1.srvopens++;
3373                 nfsrv_openpluslock++;
3374                 nfsstatsv1.srvopenowners++;
3375                 nfsrv_openpluslock++;
3376         }
3377         if (!error) {
3378                 stateidp->seqid = openstp->ls_stateid.seqid;
3379                 stateidp->other[0] = openstp->ls_stateid.other[0];
3380                 stateidp->other[1] = openstp->ls_stateid.other[1];
3381                 stateidp->other[2] = openstp->ls_stateid.other[2];
3382         }
3383         NFSUNLOCKSTATE();
3384         if (haslock) {
3385                 NFSLOCKV4ROOTMUTEX();
3386                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
3387                 NFSUNLOCKV4ROOTMUTEX();
3388         }
3389         if (new_open)
3390                 free(new_open, M_NFSDSTATE);
3391         if (new_deleg)
3392                 free(new_deleg, M_NFSDSTATE);
3393
3394         /*
3395          * If the NFSv4.1 client just acquired its first open, write a timestamp
3396          * to the stable storage file.
3397          */
3398         if (gotstate != 0) {
3399                 nfsrv_writestable(clidp, len, NFSNST_NEWSTATE, p);
3400                 nfsrv_backupstable();
3401         }
3402
3403 out:
3404         free(clidp, M_TEMP);
3405         NFSEXITCODE2(error, nd);
3406         return (error);
3407 }
3408
3409 /*
3410  * Open update. Does the confirm, downgrade and close.
3411  */
3412 int
3413 nfsrv_openupdate(vnode_t vp, struct nfsstate *new_stp, nfsquad_t clientid,
3414     nfsv4stateid_t *stateidp, struct nfsrv_descript *nd, NFSPROC_T *p,
3415     int *retwriteaccessp)
3416 {
3417         struct nfsstate *stp;
3418         struct nfsclient *clp;
3419         struct nfslockfile *lfp;
3420         u_int32_t bits;
3421         int error = 0, gotstate = 0, len = 0;
3422         u_char *clidp = NULL;
3423
3424         /*
3425          * Check for restart conditions (client and server).
3426          */
3427         error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
3428             &new_stp->ls_stateid, 0);
3429         if (error)
3430                 goto out;
3431
3432         clidp = malloc(NFSV4_OPAQUELIMIT, M_TEMP, M_WAITOK);
3433         NFSLOCKSTATE();
3434         /*
3435          * Get the open structure via clientid and stateid.
3436          */
3437         error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
3438             (nfsquad_t)((u_quad_t)0), 0, nd, p);
3439         if (!error)
3440                 error = nfsrv_getstate(clp, &new_stp->ls_stateid,
3441                     new_stp->ls_flags, &stp);
3442
3443         /*
3444          * Sanity check the open.
3445          */
3446         if (!error && (!(stp->ls_flags & NFSLCK_OPEN) ||
3447                 (!(new_stp->ls_flags & NFSLCK_CONFIRM) &&
3448                  (stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM)) ||
3449                 ((new_stp->ls_flags & NFSLCK_CONFIRM) &&
3450                  (!(stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM)))))
3451                 error = NFSERR_BADSTATEID;
3452
3453         if (!error)
3454                 error = nfsrv_checkseqid(nd, new_stp->ls_seq,
3455                     stp->ls_openowner, new_stp->ls_op);
3456         if (!error && stp->ls_stateid.seqid != new_stp->ls_stateid.seqid &&
3457             (((nd->nd_flag & ND_NFSV41) == 0 &&
3458               !(new_stp->ls_flags & NFSLCK_CONFIRM)) ||
3459              ((nd->nd_flag & ND_NFSV41) != 0 &&
3460               new_stp->ls_stateid.seqid != 0)))
3461                 error = NFSERR_OLDSTATEID;
3462         if (!error && vnode_vtype(vp) != VREG) {
3463                 if (vnode_vtype(vp) == VDIR)
3464                         error = NFSERR_ISDIR;
3465                 else
3466                         error = NFSERR_INVAL;
3467         }
3468
3469         if (error) {
3470                 /*
3471                  * If a client tries to confirm an Open with a bad
3472                  * seqid# and there are no byte range locks or other Opens
3473                  * on the openowner, just throw it away, so the next use of the
3474                  * openowner will start a fresh seq#.
3475                  */
3476                 if (error == NFSERR_BADSEQID &&
3477                     (new_stp->ls_flags & NFSLCK_CONFIRM) &&
3478                     nfsrv_nootherstate(stp))
3479                         nfsrv_freeopenowner(stp->ls_openowner, 0, p);
3480                 NFSUNLOCKSTATE();
3481                 goto out;
3482         }
3483
3484         /*
3485          * Set the return stateid.
3486          */
3487         stateidp->seqid = stp->ls_stateid.seqid + 1;
3488         if ((nd->nd_flag & ND_NFSV41) != 0 && stateidp->seqid == 0)
3489                 stateidp->seqid = 1;
3490         stateidp->other[0] = stp->ls_stateid.other[0];
3491         stateidp->other[1] = stp->ls_stateid.other[1];
3492         stateidp->other[2] = stp->ls_stateid.other[2];
3493         /*
3494          * Now, handle the three cases.
3495          */
3496         if (new_stp->ls_flags & NFSLCK_CONFIRM) {
3497                 /*
3498                  * If the open doesn't need confirmation, it seems to me that
3499                  * there is a client error, but I'll just log it and keep going?
3500                  */
3501                 if (!(stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM))
3502                         printf("Nfsv4d: stray open confirm\n");
3503                 stp->ls_openowner->ls_flags = 0;
3504                 stp->ls_stateid.seqid++;
3505                 if ((nd->nd_flag & ND_NFSV41) != 0 &&
3506                     stp->ls_stateid.seqid == 0)
3507                         stp->ls_stateid.seqid = 1;
3508                 if (!(clp->lc_flags & LCL_STAMPEDSTABLE)) {
3509                         clp->lc_flags |= LCL_STAMPEDSTABLE;
3510                         len = clp->lc_idlen;
3511                         NFSBCOPY(clp->lc_id, clidp, len);
3512                         gotstate = 1;
3513                 }
3514                 NFSUNLOCKSTATE();
3515         } else if (new_stp->ls_flags & NFSLCK_CLOSE) {
3516                 lfp = stp->ls_lfp;
3517                 if (retwriteaccessp != NULL) {
3518                         if ((stp->ls_flags & NFSLCK_WRITEACCESS) != 0)
3519                                 *retwriteaccessp = 1;
3520                         else
3521                                 *retwriteaccessp = 0;
3522                 }
3523                 if (nfsrv_dolocallocks != 0 && !LIST_EMPTY(&stp->ls_open)) {
3524                         /* Get the lf lock */
3525                         nfsrv_locklf(lfp);
3526                         NFSUNLOCKSTATE();
3527                         ASSERT_VOP_ELOCKED(vp, "nfsrv_openupdate");
3528                         NFSVOPUNLOCK(vp, 0);
3529                         if (nfsrv_freeopen(stp, vp, 1, p) == 0) {
3530                                 NFSLOCKSTATE();
3531                                 nfsrv_unlocklf(lfp);
3532                                 NFSUNLOCKSTATE();
3533                         }
3534                         NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
3535                 } else {
3536                         (void) nfsrv_freeopen(stp, NULL, 0, p);
3537                         NFSUNLOCKSTATE();
3538                 }
3539         } else {
3540                 /*
3541                  * Update the share bits, making sure that the new set are a
3542                  * subset of the old ones.
3543                  */
3544                 bits = (new_stp->ls_flags & NFSLCK_SHAREBITS);
3545                 if (~(stp->ls_flags) & bits) {
3546                         NFSUNLOCKSTATE();
3547                         error = NFSERR_INVAL;
3548                         goto out;
3549                 }
3550                 stp->ls_flags = (bits | NFSLCK_OPEN);
3551                 stp->ls_stateid.seqid++;
3552                 if ((nd->nd_flag & ND_NFSV41) != 0 &&
3553                     stp->ls_stateid.seqid == 0)
3554                         stp->ls_stateid.seqid = 1;
3555                 NFSUNLOCKSTATE();
3556         }
3557
3558         /*
3559          * If the client just confirmed its first open, write a timestamp
3560          * to the stable storage file.
3561          */
3562         if (gotstate != 0) {
3563                 nfsrv_writestable(clidp, len, NFSNST_NEWSTATE, p);
3564                 nfsrv_backupstable();
3565         }
3566
3567 out:
3568         free(clidp, M_TEMP);
3569         NFSEXITCODE2(error, nd);
3570         return (error);
3571 }
3572
3573 /*
3574  * Delegation update. Does the purge and return.
3575  */
3576 int
3577 nfsrv_delegupdate(struct nfsrv_descript *nd, nfsquad_t clientid,
3578     nfsv4stateid_t *stateidp, vnode_t vp, int op, struct ucred *cred,
3579     NFSPROC_T *p, int *retwriteaccessp)
3580 {
3581         struct nfsstate *stp;
3582         struct nfsclient *clp;
3583         int error = 0;
3584         fhandle_t fh;
3585
3586         /*
3587          * Do a sanity check against the file handle for DelegReturn.
3588          */
3589         if (vp) {
3590                 error = nfsvno_getfh(vp, &fh, p);
3591                 if (error)
3592                         goto out;
3593         }
3594         /*
3595          * Check for restart conditions (client and server).
3596          */
3597         if (op == NFSV4OP_DELEGRETURN)
3598                 error = nfsrv_checkrestart(clientid, NFSLCK_DELEGRETURN,
3599                         stateidp, 0);
3600         else
3601                 error = nfsrv_checkrestart(clientid, NFSLCK_DELEGPURGE,
3602                         stateidp, 0);
3603
3604         NFSLOCKSTATE();
3605         /*
3606          * Get the open structure via clientid and stateid.
3607          */
3608         if (!error)
3609             error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
3610                 (nfsquad_t)((u_quad_t)0), 0, nd, p);
3611         if (error) {
3612                 if (error == NFSERR_CBPATHDOWN)
3613                         error = 0;
3614                 if (error == NFSERR_STALECLIENTID && op == NFSV4OP_DELEGRETURN)
3615                         error = NFSERR_STALESTATEID;
3616         }
3617         if (!error && op == NFSV4OP_DELEGRETURN) {
3618             error = nfsrv_getstate(clp, stateidp, NFSLCK_DELEGRETURN, &stp);
3619             if (!error && stp->ls_stateid.seqid != stateidp->seqid &&
3620                 ((nd->nd_flag & ND_NFSV41) == 0 || stateidp->seqid != 0))
3621                 error = NFSERR_OLDSTATEID;
3622         }
3623         /*
3624          * NFSERR_EXPIRED means that the state has gone away,
3625          * so Delegations have been purged. Just return ok.
3626          */
3627         if (error == NFSERR_EXPIRED && op == NFSV4OP_DELEGPURGE) {
3628                 NFSUNLOCKSTATE();
3629                 error = 0;
3630                 goto out;
3631         }
3632         if (error) {
3633                 NFSUNLOCKSTATE();
3634                 goto out;
3635         }
3636
3637         if (op == NFSV4OP_DELEGRETURN) {
3638                 if (NFSBCMP((caddr_t)&fh, (caddr_t)&stp->ls_lfp->lf_fh,
3639                     sizeof (fhandle_t))) {
3640                         NFSUNLOCKSTATE();
3641                         error = NFSERR_BADSTATEID;
3642                         goto out;
3643                 }
3644                 if (retwriteaccessp != NULL) {
3645                         if ((stp->ls_flags & NFSLCK_DELEGWRITE) != 0)
3646                                 *retwriteaccessp = 1;
3647                         else
3648                                 *retwriteaccessp = 0;
3649                 }
3650                 nfsrv_freedeleg(stp);
3651         } else {
3652                 nfsrv_freedeleglist(&clp->lc_olddeleg);
3653         }
3654         NFSUNLOCKSTATE();
3655         error = 0;
3656
3657 out:
3658         NFSEXITCODE(error);
3659         return (error);
3660 }
3661
3662 /*
3663  * Release lock owner.
3664  */
3665 int
3666 nfsrv_releaselckown(struct nfsstate *new_stp, nfsquad_t clientid,
3667     NFSPROC_T *p)
3668 {
3669         struct nfsstate *stp, *nstp, *openstp, *ownstp;
3670         struct nfsclient *clp;
3671         int error = 0;
3672
3673         /*
3674          * Check for restart conditions (client and server).
3675          */
3676         error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
3677             &new_stp->ls_stateid, 0);
3678         if (error)
3679                 goto out;
3680
3681         NFSLOCKSTATE();
3682         /*
3683          * Get the lock owner by name.
3684          */
3685         error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
3686             (nfsquad_t)((u_quad_t)0), 0, NULL, p);
3687         if (error) {
3688                 NFSUNLOCKSTATE();
3689                 goto out;
3690         }
3691         LIST_FOREACH(ownstp, &clp->lc_open, ls_list) {
3692             LIST_FOREACH(openstp, &ownstp->ls_open, ls_list) {
3693                 stp = LIST_FIRST(&openstp->ls_open);
3694                 while (stp != LIST_END(&openstp->ls_open)) {
3695                     nstp = LIST_NEXT(stp, ls_list);
3696                     /*
3697                      * If the owner matches, check for locks and
3698                      * then free or return an error.
3699                      */
3700                     if (stp->ls_ownerlen == new_stp->ls_ownerlen &&
3701                         !NFSBCMP(stp->ls_owner, new_stp->ls_owner,
3702                          stp->ls_ownerlen)){
3703                         if (LIST_EMPTY(&stp->ls_lock)) {
3704                             nfsrv_freelockowner(stp, NULL, 0, p);
3705                         } else {
3706                             NFSUNLOCKSTATE();
3707                             error = NFSERR_LOCKSHELD;
3708                             goto out;
3709                         }
3710                     }
3711                     stp = nstp;
3712                 }
3713             }
3714         }
3715         NFSUNLOCKSTATE();
3716
3717 out:
3718         NFSEXITCODE(error);
3719         return (error);
3720 }
3721
3722 /*
3723  * Get the file handle for a lock structure.
3724  */
3725 static int
3726 nfsrv_getlockfh(vnode_t vp, u_short flags, struct nfslockfile *new_lfp,
3727     fhandle_t *nfhp, NFSPROC_T *p)
3728 {
3729         fhandle_t *fhp = NULL;
3730         int error;
3731
3732         /*
3733          * For lock, use the new nfslock structure, otherwise just
3734          * a fhandle_t on the stack.
3735          */
3736         if (flags & NFSLCK_OPEN) {
3737                 KASSERT(new_lfp != NULL, ("nfsrv_getlockfh: new_lfp NULL"));
3738                 fhp = &new_lfp->lf_fh;
3739         } else if (nfhp) {
3740                 fhp = nfhp;
3741         } else {
3742                 panic("nfsrv_getlockfh");
3743         }
3744         error = nfsvno_getfh(vp, fhp, p);
3745         NFSEXITCODE(error);
3746         return (error);
3747 }
3748
3749 /*
3750  * Get an nfs lock structure. Allocate one, as required, and return a
3751  * pointer to it.
3752  * Returns an NFSERR_xxx upon failure or -1 to indicate no current lock.
3753  */
3754 static int
3755 nfsrv_getlockfile(u_short flags, struct nfslockfile **new_lfpp,
3756     struct nfslockfile **lfpp, fhandle_t *nfhp, int lockit)
3757 {
3758         struct nfslockfile *lfp;
3759         fhandle_t *fhp = NULL, *tfhp;
3760         struct nfslockhashhead *hp;
3761         struct nfslockfile *new_lfp = NULL;
3762
3763         /*
3764          * For lock, use the new nfslock structure, otherwise just
3765          * a fhandle_t on the stack.
3766          */
3767         if (flags & NFSLCK_OPEN) {
3768                 new_lfp = *new_lfpp;
3769                 fhp = &new_lfp->lf_fh;
3770         } else if (nfhp) {
3771                 fhp = nfhp;
3772         } else {
3773                 panic("nfsrv_getlockfile");
3774         }
3775
3776         hp = NFSLOCKHASH(fhp);
3777         LIST_FOREACH(lfp, hp, lf_hash) {
3778                 tfhp = &lfp->lf_fh;
3779                 if (NFSVNO_CMPFH(fhp, tfhp)) {
3780                         if (lockit)
3781                                 nfsrv_locklf(lfp);
3782                         *lfpp = lfp;
3783                         return (0);
3784                 }
3785         }
3786         if (!(flags & NFSLCK_OPEN))
3787                 return (-1);
3788
3789         /*
3790          * No match, so chain the new one into the list.
3791          */
3792         LIST_INIT(&new_lfp->lf_open);
3793         LIST_INIT(&new_lfp->lf_lock);
3794         LIST_INIT(&new_lfp->lf_deleg);
3795         LIST_INIT(&new_lfp->lf_locallock);
3796         LIST_INIT(&new_lfp->lf_rollback);
3797         new_lfp->lf_locallock_lck.nfslock_usecnt = 0;
3798         new_lfp->lf_locallock_lck.nfslock_lock = 0;
3799         new_lfp->lf_usecount = 0;
3800         LIST_INSERT_HEAD(hp, new_lfp, lf_hash);
3801         *lfpp = new_lfp;
3802         *new_lfpp = NULL;
3803         return (0);
3804 }
3805
3806 /*
3807  * This function adds a nfslock lock structure to the list for the associated
3808  * nfsstate and nfslockfile structures. It will be inserted after the
3809  * entry pointed at by insert_lop.
3810  */
3811 static void
3812 nfsrv_insertlock(struct nfslock *new_lop, struct nfslock *insert_lop,
3813     struct nfsstate *stp, struct nfslockfile *lfp)
3814 {
3815         struct nfslock *lop, *nlop;
3816
3817         new_lop->lo_stp = stp;
3818         new_lop->lo_lfp = lfp;
3819
3820         if (stp != NULL) {
3821                 /* Insert in increasing lo_first order */
3822                 lop = LIST_FIRST(&lfp->lf_lock);
3823                 if (lop == LIST_END(&lfp->lf_lock) ||
3824                     new_lop->lo_first <= lop->lo_first) {
3825                         LIST_INSERT_HEAD(&lfp->lf_lock, new_lop, lo_lckfile);
3826                 } else {
3827                         nlop = LIST_NEXT(lop, lo_lckfile);
3828                         while (nlop != LIST_END(&lfp->lf_lock) &&
3829                                nlop->lo_first < new_lop->lo_first) {
3830                                 lop = nlop;
3831                                 nlop = LIST_NEXT(lop, lo_lckfile);
3832                         }
3833                         LIST_INSERT_AFTER(lop, new_lop, lo_lckfile);
3834                 }
3835         } else {
3836                 new_lop->lo_lckfile.le_prev = NULL;     /* list not used */
3837         }
3838
3839         /*
3840          * Insert after insert_lop, which is overloaded as stp or lfp for
3841          * an empty list.
3842          */
3843         if (stp == NULL && (struct nfslockfile *)insert_lop == lfp)
3844                 LIST_INSERT_HEAD(&lfp->lf_locallock, new_lop, lo_lckowner);
3845         else if ((struct nfsstate *)insert_lop == stp)
3846                 LIST_INSERT_HEAD(&stp->ls_lock, new_lop, lo_lckowner);
3847         else
3848                 LIST_INSERT_AFTER(insert_lop, new_lop, lo_lckowner);
3849         if (stp != NULL) {
3850                 nfsstatsv1.srvlocks++;
3851                 nfsrv_openpluslock++;
3852         }
3853 }
3854
3855 /*
3856  * This function updates the locking for a lock owner and given file. It
3857  * maintains a list of lock ranges ordered on increasing file offset that
3858  * are NFSLCK_READ or NFSLCK_WRITE and non-overlapping (aka POSIX style).
3859  * It always adds new_lop to the list and sometimes uses the one pointed
3860  * at by other_lopp.
3861  */
3862 static void
3863 nfsrv_updatelock(struct nfsstate *stp, struct nfslock **new_lopp,
3864     struct nfslock **other_lopp, struct nfslockfile *lfp)
3865 {
3866         struct nfslock *new_lop = *new_lopp;
3867         struct nfslock *lop, *tlop, *ilop;
3868         struct nfslock *other_lop = *other_lopp;
3869         int unlock = 0, myfile = 0;
3870         u_int64_t tmp;
3871
3872         /*
3873          * Work down the list until the lock is merged.
3874          */
3875         if (new_lop->lo_flags & NFSLCK_UNLOCK)
3876                 unlock = 1;
3877         if (stp != NULL) {
3878                 ilop = (struct nfslock *)stp;
3879                 lop = LIST_FIRST(&stp->ls_lock);
3880         } else {
3881                 ilop = (struct nfslock *)lfp;
3882                 lop = LIST_FIRST(&lfp->lf_locallock);
3883         }
3884         while (lop != NULL) {
3885             /*
3886              * Only check locks for this file that aren't before the start of
3887              * new lock's range.
3888              */
3889             if (lop->lo_lfp == lfp) {
3890               myfile = 1;
3891               if (lop->lo_end >= new_lop->lo_first) {
3892                 if (new_lop->lo_end < lop->lo_first) {
3893                         /*
3894                          * If the new lock ends before the start of the
3895                          * current lock's range, no merge, just insert
3896                          * the new lock.
3897                          */
3898                         break;
3899                 }
3900                 if (new_lop->lo_flags == lop->lo_flags ||
3901                     (new_lop->lo_first <= lop->lo_first &&
3902                      new_lop->lo_end >= lop->lo_end)) {
3903                         /*
3904                          * This lock can be absorbed by the new lock/unlock.
3905                          * This happens when it covers the entire range
3906                          * of the old lock or is contiguous
3907                          * with the old lock and is of the same type or an
3908                          * unlock.
3909                          */
3910                         if (lop->lo_first < new_lop->lo_first)
3911                                 new_lop->lo_first = lop->lo_first;
3912                         if (lop->lo_end > new_lop->lo_end)
3913                                 new_lop->lo_end = lop->lo_end;
3914                         tlop = lop;
3915                         lop = LIST_NEXT(lop, lo_lckowner);
3916                         nfsrv_freenfslock(tlop);
3917                         continue;
3918                 }
3919
3920                 /*
3921                  * All these cases are for contiguous locks that are not the
3922                  * same type, so they can't be merged.
3923                  */
3924                 if (new_lop->lo_first <= lop->lo_first) {
3925                         /*
3926                          * This case is where the new lock overlaps with the
3927                          * first part of the old lock. Move the start of the
3928                          * old lock to just past the end of the new lock. The
3929                          * new lock will be inserted in front of the old, since
3930                          * ilop hasn't been updated. (We are done now.)
3931                          */
3932                         lop->lo_first = new_lop->lo_end;
3933                         break;
3934                 }
3935                 if (new_lop->lo_end >= lop->lo_end) {
3936                         /*
3937                          * This case is where the new lock overlaps with the
3938                          * end of the old lock's range. Move the old lock's
3939                          * end to just before the new lock's first and insert
3940                          * the new lock after the old lock.
3941                          * Might not be done yet, since the new lock could
3942                          * overlap further locks with higher ranges.
3943                          */
3944                         lop->lo_end = new_lop->lo_first;
3945                         ilop = lop;
3946                         lop = LIST_NEXT(lop, lo_lckowner);
3947                         continue;
3948                 }
3949                 /*
3950                  * The final case is where the new lock's range is in the
3951                  * middle of the current lock's and splits the current lock
3952                  * up. Use *other_lopp to handle the second part of the
3953                  * split old lock range. (We are done now.)
3954                  * For unlock, we use new_lop as other_lop and tmp, since
3955                  * other_lop and new_lop are the same for this case.
3956                  * We noted the unlock case above, so we don't need
3957                  * new_lop->lo_flags any longer.
3958                  */
3959                 tmp = new_lop->lo_first;
3960                 if (other_lop == NULL) {
3961                         if (!unlock)
3962                                 panic("nfsd srv update unlock");
3963                         other_lop = new_lop;
3964                         *new_lopp = NULL;
3965                 }
3966                 other_lop->lo_first = new_lop->lo_end;
3967                 other_lop->lo_end = lop->lo_end;
3968                 other_lop->lo_flags = lop->lo_flags;
3969                 other_lop->lo_stp = stp;
3970                 other_lop->lo_lfp = lfp;
3971                 lop->lo_end = tmp;
3972                 nfsrv_insertlock(other_lop, lop, stp, lfp);
3973                 *other_lopp = NULL;
3974                 ilop = lop;
3975                 break;
3976               }
3977             }
3978             ilop = lop;
3979             lop = LIST_NEXT(lop, lo_lckowner);
3980             if (myfile && (lop == NULL || lop->lo_lfp != lfp))
3981                 break;
3982         }
3983
3984         /*
3985          * Insert the new lock in the list at the appropriate place.
3986          */
3987         if (!unlock) {
3988                 nfsrv_insertlock(new_lop, ilop, stp, lfp);
3989                 *new_lopp = NULL;
3990         }
3991 }
3992
3993 /*
3994  * This function handles sequencing of locks, etc.
3995  * It returns an error that indicates what the caller should do.
3996  */
3997 static int
3998 nfsrv_checkseqid(struct nfsrv_descript *nd, u_int32_t seqid,
3999     struct nfsstate *stp, struct nfsrvcache *op)
4000 {
4001         int error = 0;
4002
4003         if ((nd->nd_flag & ND_NFSV41) != 0)
4004                 /* NFSv4.1 ignores the open_seqid and lock_seqid. */
4005                 goto out;
4006         if (op != nd->nd_rp)
4007                 panic("nfsrvstate checkseqid");
4008         if (!(op->rc_flag & RC_INPROG))
4009                 panic("nfsrvstate not inprog");
4010         if (stp->ls_op && stp->ls_op->rc_refcnt <= 0) {
4011                 printf("refcnt=%d\n", stp->ls_op->rc_refcnt);
4012                 panic("nfsrvstate op refcnt");
4013         }
4014         if ((stp->ls_seq + 1) == seqid) {
4015                 if (stp->ls_op)
4016                         nfsrvd_derefcache(stp->ls_op);
4017                 stp->ls_op = op;
4018                 nfsrvd_refcache(op);
4019                 stp->ls_seq = seqid;
4020                 goto out;
4021         } else if (stp->ls_seq == seqid && stp->ls_op &&
4022                 op->rc_xid == stp->ls_op->rc_xid &&
4023                 op->rc_refcnt == 0 &&
4024                 op->rc_reqlen == stp->ls_op->rc_reqlen &&
4025                 op->rc_cksum == stp->ls_op->rc_cksum) {
4026                 if (stp->ls_op->rc_flag & RC_INPROG) {
4027                         error = NFSERR_DONTREPLY;
4028                         goto out;
4029                 }
4030                 nd->nd_rp = stp->ls_op;
4031                 nd->nd_rp->rc_flag |= RC_INPROG;
4032                 nfsrvd_delcache(op);
4033                 error = NFSERR_REPLYFROMCACHE;
4034                 goto out;
4035         }
4036         error = NFSERR_BADSEQID;
4037
4038 out:
4039         NFSEXITCODE2(error, nd);
4040         return (error);
4041 }
4042
4043 /*
4044  * Get the client ip address for callbacks. If the strings can't be parsed,
4045  * just set lc_program to 0 to indicate no callbacks are possible.
4046  * (For cases where the address can't be parsed or is 0.0.0.0.0.0, set
4047  *  the address to the client's transport address. This won't be used
4048  *  for callbacks, but can be printed out by nfsstats for info.)
4049  * Return error if the xdr can't be parsed, 0 otherwise.
4050  */
4051 int
4052 nfsrv_getclientipaddr(struct nfsrv_descript *nd, struct nfsclient *clp)
4053 {
4054         u_int32_t *tl;
4055         u_char *cp, *cp2;
4056         int i, j, maxalen = 0, minalen = 0;
4057         sa_family_t af;
4058 #ifdef INET
4059         struct sockaddr_in *rin, *sin;
4060 #endif
4061 #ifdef INET6
4062         struct sockaddr_in6 *rin6, *sin6;
4063 #endif
4064         u_char *addr;
4065         int error = 0, cantparse = 0;
4066         union {
4067                 in_addr_t ival;
4068                 u_char cval[4];
4069         } ip;
4070         union {
4071                 in_port_t sval;
4072                 u_char cval[2];
4073         } port;
4074
4075         /* 8 is the maximum length of the port# string. */
4076         addr = malloc(INET6_ADDRSTRLEN + 8, M_TEMP, M_WAITOK);
4077         clp->lc_req.nr_client = NULL;
4078         clp->lc_req.nr_lock = 0;
4079         af = AF_UNSPEC;
4080         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
4081         i = fxdr_unsigned(int, *tl);
4082         if (i >= 3 && i <= 4) {
4083                 error = nfsrv_mtostr(nd, addr, i);
4084                 if (error)
4085                         goto nfsmout;
4086 #ifdef INET
4087                 if (!strcmp(addr, "tcp")) {
4088                         clp->lc_flags |= LCL_TCPCALLBACK;
4089                         clp->lc_req.nr_sotype = SOCK_STREAM;
4090                         clp->lc_req.nr_soproto = IPPROTO_TCP;
4091                         af = AF_INET;
4092                 } else if (!strcmp(addr, "udp")) {
4093                         clp->lc_req.nr_sotype = SOCK_DGRAM;
4094                         clp->lc_req.nr_soproto = IPPROTO_UDP;
4095                         af = AF_INET;
4096                 }
4097 #endif
4098 #ifdef INET6
4099                 if (af == AF_UNSPEC) {
4100                         if (!strcmp(addr, "tcp6")) {
4101                                 clp->lc_flags |= LCL_TCPCALLBACK;
4102                                 clp->lc_req.nr_sotype = SOCK_STREAM;
4103                                 clp->lc_req.nr_soproto = IPPROTO_TCP;
4104                                 af = AF_INET6;
4105                         } else if (!strcmp(addr, "udp6")) {
4106                                 clp->lc_req.nr_sotype = SOCK_DGRAM;
4107                                 clp->lc_req.nr_soproto = IPPROTO_UDP;
4108                                 af = AF_INET6;
4109                         }
4110                 }
4111 #endif
4112                 if (af == AF_UNSPEC) {
4113                         cantparse = 1;
4114                 }
4115         } else {
4116                 cantparse = 1;
4117                 if (i > 0) {
4118                         error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
4119                         if (error)
4120                                 goto nfsmout;
4121                 }
4122         }
4123         /*
4124          * The caller has allocated clp->lc_req.nr_nam to be large enough
4125          * for either AF_INET or AF_INET6 and zeroed out the contents.
4126          * maxalen is set to the maximum length of the host IP address string
4127          * plus 8 for the maximum length of the port#.
4128          * minalen is set to the minimum length of the host IP address string
4129          * plus 4 for the minimum length of the port#.
4130          * These lengths do not include NULL termination,
4131          * so INET[6]_ADDRSTRLEN - 1 is used in the calculations.
4132          */
4133         switch (af) {
4134 #ifdef INET
4135         case AF_INET:
4136                 rin = (struct sockaddr_in *)clp->lc_req.nr_nam;
4137                 rin->sin_family = AF_INET;
4138                 rin->sin_len = sizeof(struct sockaddr_in);
4139                 maxalen = INET_ADDRSTRLEN - 1 + 8;
4140                 minalen = 7 + 4;
4141                 break;
4142 #endif
4143 #ifdef INET6
4144         case AF_INET6:
4145                 rin6 = (struct sockaddr_in6 *)clp->lc_req.nr_nam;
4146                 rin6->sin6_family = AF_INET6;
4147                 rin6->sin6_len = sizeof(struct sockaddr_in6);
4148                 maxalen = INET6_ADDRSTRLEN - 1 + 8;
4149                 minalen = 3 + 4;
4150                 break;
4151 #endif
4152         }
4153         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
4154         i = fxdr_unsigned(int, *tl);
4155         if (i < 0) {
4156                 error = NFSERR_BADXDR;
4157                 goto nfsmout;
4158         } else if (i == 0) {
4159                 cantparse = 1;
4160         } else if (!cantparse && i <= maxalen && i >= minalen) {
4161                 error = nfsrv_mtostr(nd, addr, i);
4162                 if (error)
4163                         goto nfsmout;
4164
4165                 /*
4166                  * Parse out the address fields. We expect 6 decimal numbers
4167                  * separated by '.'s for AF_INET and two decimal numbers
4168                  * preceeded by '.'s for AF_INET6.
4169                  */
4170                 cp = NULL;
4171                 switch (af) {
4172 #ifdef INET6
4173                 /*
4174                  * For AF_INET6, first parse the host address.
4175                  */
4176                 case AF_INET6:
4177                         cp = strchr(addr, '.');
4178                         if (cp != NULL) {
4179                                 *cp++ = '\0';
4180                                 if (inet_pton(af, addr, &rin6->sin6_addr) == 1)
4181                                         i = 4;
4182                                 else {
4183                                         cp = NULL;
4184                                         cantparse = 1;
4185                                 }
4186                         }
4187                         break;
4188 #endif
4189 #ifdef INET
4190                 case AF_INET:
4191                         cp = addr;
4192                         i = 0;
4193                         break;
4194 #endif
4195                 }
4196                 while (cp != NULL && *cp && i < 6) {
4197                         cp2 = cp;
4198                         while (*cp2 && *cp2 != '.')
4199                                 cp2++;
4200                         if (*cp2)
4201                                 *cp2++ = '\0';
4202                         else if (i != 5) {
4203                                 cantparse = 1;
4204                                 break;
4205                         }
4206                         j = nfsrv_getipnumber(cp);
4207                         if (j >= 0) {
4208                                 if (i < 4)
4209                                         ip.cval[3 - i] = j;
4210                                 else
4211                                         port.cval[5 - i] = j;
4212                         } else {
4213                                 cantparse = 1;
4214                                 break;
4215                         }
4216                         cp = cp2;
4217                         i++;
4218                 }
4219                 if (!cantparse) {
4220                         /*
4221                          * The host address INADDR_ANY is (mis)used to indicate
4222                          * "there is no valid callback address".
4223                          */
4224                         switch (af) {
4225 #ifdef INET6
4226                         case AF_INET6:
4227                                 if (!IN6_ARE_ADDR_EQUAL(&rin6->sin6_addr,
4228                                     &in6addr_any))
4229                                         rin6->sin6_port = htons(port.sval);
4230                                 else
4231                                         cantparse = 1;
4232                                 break;
4233 #endif
4234 #ifdef INET
4235                         case AF_INET:
4236                                 if (ip.ival != INADDR_ANY) {
4237                                         rin->sin_addr.s_addr = htonl(ip.ival);
4238                                         rin->sin_port = htons(port.sval);
4239                                 } else {
4240                                         cantparse = 1;
4241                                 }
4242                                 break;
4243 #endif
4244                         }
4245                 }
4246         } else {
4247                 cantparse = 1;
4248                 if (i > 0) {
4249                         error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
4250                         if (error)
4251                                 goto nfsmout;
4252                 }
4253         }
4254         if (cantparse) {
4255                 switch (nd->nd_nam->sa_family) {
4256 #ifdef INET
4257                 case AF_INET:
4258                         sin = (struct sockaddr_in *)nd->nd_nam;
4259                         rin = (struct sockaddr_in *)clp->lc_req.nr_nam;
4260                         rin->sin_family = AF_INET;
4261                         rin->sin_len = sizeof(struct sockaddr_in);
4262                         rin->sin_addr.s_addr = sin->sin_addr.s_addr;
4263                         rin->sin_port = 0x0;
4264                         break;
4265 #endif
4266 #ifdef INET6
4267                 case AF_INET6:
4268                         sin6 = (struct sockaddr_in6 *)nd->nd_nam;
4269                         rin6 = (struct sockaddr_in6 *)clp->lc_req.nr_nam;
4270                         rin6->sin6_family = AF_INET6;
4271                         rin6->sin6_len = sizeof(struct sockaddr_in6);
4272                         rin6->sin6_addr = sin6->sin6_addr;
4273                         rin6->sin6_port = 0x0;
4274                         break;
4275 #endif
4276                 }
4277                 clp->lc_program = 0;
4278         }
4279 nfsmout:
4280         free(addr, M_TEMP);
4281         NFSEXITCODE2(error, nd);
4282         return (error);
4283 }
4284
4285 /*
4286  * Turn a string of up to three decimal digits into a number. Return -1 upon
4287  * error.
4288  */
4289 static int
4290 nfsrv_getipnumber(u_char *cp)
4291 {
4292         int i = 0, j = 0;
4293
4294         while (*cp) {
4295                 if (j > 2 || *cp < '0' || *cp > '9')
4296                         return (-1);
4297                 i *= 10;
4298                 i += (*cp - '0');
4299                 cp++;
4300                 j++;
4301         }
4302         if (i < 256)
4303                 return (i);
4304         return (-1);
4305 }
4306
4307 /*
4308  * This function checks for restart conditions.
4309  */
4310 static int
4311 nfsrv_checkrestart(nfsquad_t clientid, u_int32_t flags,
4312     nfsv4stateid_t *stateidp, int specialid)
4313 {
4314         int ret = 0;
4315
4316         /*
4317          * First check for a server restart. Open, LockT, ReleaseLockOwner
4318          * and DelegPurge have a clientid, the rest a stateid.
4319          */
4320         if (flags &
4321             (NFSLCK_OPEN | NFSLCK_TEST | NFSLCK_RELEASE | NFSLCK_DELEGPURGE)) {
4322                 if (clientid.lval[0] != nfsrvboottime) {
4323                         ret = NFSERR_STALECLIENTID;
4324                         goto out;
4325                 }
4326         } else if (stateidp->other[0] != nfsrvboottime &&
4327                 specialid == 0) {
4328                 ret = NFSERR_STALESTATEID;
4329                 goto out;
4330         }
4331
4332         /*
4333          * Read, Write, Setattr and LockT can return NFSERR_GRACE and do
4334          * not use a lock/open owner seqid#, so the check can be done now.
4335          * (The others will be checked, as required, later.)
4336          */
4337         if (!(flags & (NFSLCK_CHECK | NFSLCK_TEST)))
4338                 goto out;
4339
4340         NFSLOCKSTATE();
4341         ret = nfsrv_checkgrace(NULL, NULL, flags);
4342         NFSUNLOCKSTATE();
4343
4344 out:
4345         NFSEXITCODE(ret);
4346         return (ret);
4347 }
4348
4349 /*
4350  * Check for grace.
4351  */
4352 static int
4353 nfsrv_checkgrace(struct nfsrv_descript *nd, struct nfsclient *clp,
4354     u_int32_t flags)
4355 {
4356         int error = 0, notreclaimed;
4357         struct nfsrv_stable *sp;
4358
4359         if ((nfsrv_stablefirst.nsf_flags & (NFSNSF_UPDATEDONE |
4360              NFSNSF_GRACEOVER)) == 0) {
4361                 /*
4362                  * First, check to see if all of the clients have done a
4363                  * ReclaimComplete.  If so, grace can end now.
4364                  */
4365                 notreclaimed = 0;
4366                 LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
4367                         if ((sp->nst_flag & NFSNST_RECLAIMED) == 0) {
4368                                 notreclaimed = 1;
4369                                 break;
4370                         }
4371                 }
4372                 if (notreclaimed == 0)
4373                         nfsrv_stablefirst.nsf_flags |= (NFSNSF_GRACEOVER |
4374                             NFSNSF_NEEDLOCK);
4375         }
4376
4377         if ((nfsrv_stablefirst.nsf_flags & NFSNSF_GRACEOVER) != 0) {
4378                 if (flags & NFSLCK_RECLAIM) {
4379                         error = NFSERR_NOGRACE;
4380                         goto out;
4381                 }
4382         } else {
4383                 if (!(flags & NFSLCK_RECLAIM)) {
4384                         error = NFSERR_GRACE;
4385                         goto out;
4386                 }
4387                 if (nd != NULL && clp != NULL &&
4388                     (nd->nd_flag & ND_NFSV41) != 0 &&
4389                     (clp->lc_flags & LCL_RECLAIMCOMPLETE) != 0) {
4390                         error = NFSERR_NOGRACE;
4391                         goto out;
4392                 }
4393
4394                 /*
4395                  * If grace is almost over and we are still getting Reclaims,
4396                  * extend grace a bit.
4397                  */
4398                 if ((NFSD_MONOSEC + NFSRV_LEASEDELTA) >
4399                     nfsrv_stablefirst.nsf_eograce)
4400                         nfsrv_stablefirst.nsf_eograce = NFSD_MONOSEC +
4401                                 NFSRV_LEASEDELTA;
4402         }
4403
4404 out:
4405         NFSEXITCODE(error);
4406         return (error);
4407 }
4408
4409 /*
4410  * Do a server callback.
4411  * The "trunc" argument is slightly overloaded and refers to different
4412  * boolean arguments for CBRECALL and CBLAYOUTRECALL.
4413  */
4414 static int
4415 nfsrv_docallback(struct nfsclient *clp, int procnum, nfsv4stateid_t *stateidp,
4416     int trunc, fhandle_t *fhp, struct nfsvattr *nap, nfsattrbit_t *attrbitp,
4417     int laytype, NFSPROC_T *p)
4418 {
4419         mbuf_t m;
4420         u_int32_t *tl;
4421         struct nfsrv_descript *nd;
4422         struct ucred *cred;
4423         int error = 0;
4424         u_int32_t callback;
4425         struct nfsdsession *sep = NULL;
4426         uint64_t tval;
4427
4428         nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
4429         cred = newnfs_getcred();
4430         NFSLOCKSTATE(); /* mostly for lc_cbref++ */
4431         if (clp->lc_flags & LCL_NEEDSCONFIRM) {
4432                 NFSUNLOCKSTATE();
4433                 panic("docallb");
4434         }
4435         clp->lc_cbref++;
4436
4437         /*
4438          * Fill the callback program# and version into the request
4439          * structure for newnfs_connect() to use.
4440          */
4441         clp->lc_req.nr_prog = clp->lc_program;
4442 #ifdef notnow
4443         if ((clp->lc_flags & LCL_NFSV41) != 0)
4444                 clp->lc_req.nr_vers = NFSV41_CBVERS;
4445         else
4446 #endif
4447                 clp->lc_req.nr_vers = NFSV4_CBVERS;
4448
4449         /*
4450          * First, fill in some of the fields of nd and cr.
4451          */
4452         nd->nd_flag = ND_NFSV4;
4453         if (clp->lc_flags & LCL_GSS)
4454                 nd->nd_flag |= ND_KERBV;
4455         if ((clp->lc_flags & LCL_NFSV41) != 0)
4456                 nd->nd_flag |= ND_NFSV41;
4457         nd->nd_repstat = 0;
4458         cred->cr_uid = clp->lc_uid;
4459         cred->cr_gid = clp->lc_gid;
4460         callback = clp->lc_callback;
4461         NFSUNLOCKSTATE();
4462         cred->cr_ngroups = 1;
4463
4464         /*
4465          * Get the first mbuf for the request.
4466          */
4467         MGET(m, M_WAITOK, MT_DATA);
4468         mbuf_setlen(m, 0);
4469         nd->nd_mreq = nd->nd_mb = m;
4470         nd->nd_bpos = NFSMTOD(m, caddr_t);
4471         
4472         /*
4473          * and build the callback request.
4474          */
4475         if (procnum == NFSV4OP_CBGETATTR) {
4476                 nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
4477                 error = nfsrv_cbcallargs(nd, clp, callback, NFSV4OP_CBGETATTR,
4478                     "CB Getattr", &sep);
4479                 if (error != 0) {
4480                         mbuf_freem(nd->nd_mreq);
4481                         goto errout;
4482                 }
4483                 (void)nfsm_fhtom(nd, (u_int8_t *)fhp, NFSX_MYFH, 0);
4484                 (void)nfsrv_putattrbit(nd, attrbitp);
4485         } else if (procnum == NFSV4OP_CBRECALL) {
4486                 nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
4487                 error = nfsrv_cbcallargs(nd, clp, callback, NFSV4OP_CBRECALL,
4488                     "CB Recall", &sep);
4489                 if (error != 0) {
4490                         mbuf_freem(nd->nd_mreq);
4491                         goto errout;
4492                 }
4493                 NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED + NFSX_STATEID);
4494                 *tl++ = txdr_unsigned(stateidp->seqid);
4495                 NFSBCOPY((caddr_t)stateidp->other, (caddr_t)tl,
4496                     NFSX_STATEIDOTHER);
4497                 tl += (NFSX_STATEIDOTHER / NFSX_UNSIGNED);
4498                 if (trunc)
4499                         *tl = newnfs_true;
4500                 else
4501                         *tl = newnfs_false;
4502                 (void)nfsm_fhtom(nd, (u_int8_t *)fhp, NFSX_MYFH, 0);
4503         } else if (procnum == NFSV4OP_CBLAYOUTRECALL) {
4504                 NFSD_DEBUG(4, "docallback layout recall\n");
4505                 nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
4506                 error = nfsrv_cbcallargs(nd, clp, callback,
4507                     NFSV4OP_CBLAYOUTRECALL, "CB Reclayout", &sep);
4508                 NFSD_DEBUG(4, "aft cbcallargs=%d\n", error);
4509                 if (error != 0) {
4510                         mbuf_freem(nd->nd_mreq);
4511                         goto errout;
4512                 }
4513                 NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
4514                 *tl++ = txdr_unsigned(laytype);
4515                 *tl++ = txdr_unsigned(NFSLAYOUTIOMODE_ANY);
4516                 if (trunc)
4517                         *tl++ = newnfs_true;
4518                 else
4519                         *tl++ = newnfs_false;
4520                 *tl = txdr_unsigned(NFSV4LAYOUTRET_FILE);
4521                 nfsm_fhtom(nd, (uint8_t *)fhp, NFSX_MYFH, 0);
4522                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_HYPER + NFSX_STATEID);
4523                 tval = 0;
4524                 txdr_hyper(tval, tl); tl += 2;
4525                 tval = UINT64_MAX;
4526                 txdr_hyper(tval, tl); tl += 2;
4527                 *tl++ = txdr_unsigned(stateidp->seqid);
4528                 NFSBCOPY(stateidp->other, tl, NFSX_STATEIDOTHER);
4529                 tl += (NFSX_STATEIDOTHER / NFSX_UNSIGNED);
4530                 NFSD_DEBUG(4, "aft args\n");
4531         } else if (procnum == NFSV4PROC_CBNULL) {
4532                 nd->nd_procnum = NFSV4PROC_CBNULL;
4533                 if ((clp->lc_flags & LCL_NFSV41) != 0) {
4534                         error = nfsv4_getcbsession(clp, &sep);
4535                         if (error != 0) {
4536                                 mbuf_freem(nd->nd_mreq);
4537                                 goto errout;
4538                         }
4539                 }
4540         } else {
4541                 error = NFSERR_SERVERFAULT;
4542                 mbuf_freem(nd->nd_mreq);
4543                 goto errout;
4544         }
4545
4546         /*
4547          * Call newnfs_connect(), as required, and then newnfs_request().
4548          */
4549         (void) newnfs_sndlock(&clp->lc_req.nr_lock);
4550         if (clp->lc_req.nr_client == NULL) {
4551                 if ((clp->lc_flags & LCL_NFSV41) != 0) {
4552                         error = ECONNREFUSED;
4553                         nfsrv_freesession(sep, NULL);
4554                 } else if (nd->nd_procnum == NFSV4PROC_CBNULL)
4555                         error = newnfs_connect(NULL, &clp->lc_req, cred,
4556                             NULL, 1);
4557                 else
4558                         error = newnfs_connect(NULL, &clp->lc_req, cred,
4559                             NULL, 3);
4560         }
4561         newnfs_sndunlock(&clp->lc_req.nr_lock);
4562         NFSD_DEBUG(4, "aft sndunlock=%d\n", error);
4563         if (!error) {
4564                 if ((nd->nd_flag & ND_NFSV41) != 0) {
4565                         KASSERT(sep != NULL, ("sep NULL"));
4566                         if (sep->sess_cbsess.nfsess_xprt != NULL)
4567                                 error = newnfs_request(nd, NULL, clp,
4568                                     &clp->lc_req, NULL, NULL, cred,
4569                                     clp->lc_program, clp->lc_req.nr_vers, NULL,
4570                                     1, NULL, &sep->sess_cbsess);
4571                         else {
4572                                 /*
4573                                  * This should probably never occur, but if a
4574                                  * client somehow does an RPC without a
4575                                  * SequenceID Op that causes a callback just
4576                                  * after the nfsd threads have been terminated
4577                                  * and restared we could conceivably get here
4578                                  * without a backchannel xprt.
4579                                  */
4580                                 printf("nfsrv_docallback: no xprt\n");
4581                                 error = ECONNREFUSED;
4582                         }
4583                         NFSD_DEBUG(4, "aft newnfs_request=%d\n", error);
4584                         nfsrv_freesession(sep, NULL);
4585                 } else
4586                         error = newnfs_request(nd, NULL, clp, &clp->lc_req,
4587                             NULL, NULL, cred, clp->lc_program,
4588                             clp->lc_req.nr_vers, NULL, 1, NULL, NULL);
4589         }
4590 errout:
4591         NFSFREECRED(cred);
4592
4593         /*
4594          * If error is set here, the Callback path isn't working
4595          * properly, so twiddle the appropriate LCL_ flags.
4596          * (nd_repstat != 0 indicates the Callback path is working,
4597          *  but the callback failed on the client.)
4598          */
4599         if (error) {
4600                 /*
4601                  * Mark the callback pathway down, which disabled issuing
4602                  * of delegations and gets Renew to return NFSERR_CBPATHDOWN.
4603                  */
4604                 NFSLOCKSTATE();
4605                 clp->lc_flags |= LCL_CBDOWN;
4606                 NFSUNLOCKSTATE();
4607         } else {
4608                 /*
4609                  * Callback worked. If the callback path was down, disable
4610                  * callbacks, so no more delegations will be issued. (This
4611                  * is done on the assumption that the callback pathway is
4612                  * flakey.)
4613                  */
4614                 NFSLOCKSTATE();
4615                 if (clp->lc_flags & LCL_CBDOWN)
4616                         clp->lc_flags &= ~(LCL_CBDOWN | LCL_CALLBACKSON);
4617                 NFSUNLOCKSTATE();
4618                 if (nd->nd_repstat) {
4619                         error = nd->nd_repstat;
4620                         NFSD_DEBUG(1, "nfsrv_docallback op=%d err=%d\n",
4621                             procnum, error);
4622                 } else if (error == 0 && procnum == NFSV4OP_CBGETATTR)
4623                         error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0,
4624                             NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL,
4625                             p, NULL);
4626                 mbuf_freem(nd->nd_mrep);
4627         }
4628         NFSLOCKSTATE();
4629         clp->lc_cbref--;
4630         if ((clp->lc_flags & LCL_WAKEUPWANTED) && clp->lc_cbref == 0) {
4631                 clp->lc_flags &= ~LCL_WAKEUPWANTED;
4632                 wakeup(clp);
4633         }
4634         NFSUNLOCKSTATE();
4635
4636         free(nd, M_TEMP);
4637         NFSEXITCODE(error);
4638         return (error);
4639 }
4640
4641 /*
4642  * Set up the compound RPC for the callback.
4643  */
4644 static int
4645 nfsrv_cbcallargs(struct nfsrv_descript *nd, struct nfsclient *clp,
4646     uint32_t callback, int op, const char *optag, struct nfsdsession **sepp)
4647 {
4648         uint32_t *tl;
4649         int error, len;
4650
4651         len = strlen(optag);
4652         (void)nfsm_strtom(nd, optag, len);
4653         NFSM_BUILD(tl, uint32_t *, 4 * NFSX_UNSIGNED);
4654         if ((nd->nd_flag & ND_NFSV41) != 0) {
4655                 *tl++ = txdr_unsigned(NFSV41_MINORVERSION);
4656                 *tl++ = txdr_unsigned(callback);
4657                 *tl++ = txdr_unsigned(2);
4658                 *tl = txdr_unsigned(NFSV4OP_CBSEQUENCE);
4659                 error = nfsv4_setcbsequence(nd, clp, 1, sepp);
4660                 if (error != 0)
4661                         return (error);
4662                 NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
4663                 *tl = txdr_unsigned(op);
4664         } else {
4665                 *tl++ = txdr_unsigned(NFSV4_MINORVERSION);
4666                 *tl++ = txdr_unsigned(callback);
4667                 *tl++ = txdr_unsigned(1);
4668                 *tl = txdr_unsigned(op);
4669         }
4670         return (0);
4671 }
4672
4673 /*
4674  * Return the next index# for a clientid. Mostly just increment and return
4675  * the next one, but... if the 32bit unsigned does actually wrap around,
4676  * it should be rebooted.
4677  * At an average rate of one new client per second, it will wrap around in
4678  * approximately 136 years. (I think the server will have been shut
4679  * down or rebooted before then.)
4680  */
4681 static u_int32_t
4682 nfsrv_nextclientindex(void)
4683 {
4684         static u_int32_t client_index = 0;
4685
4686         client_index++;
4687         if (client_index != 0)
4688                 return (client_index);
4689
4690         printf("%s: out of clientids\n", __func__);
4691         return (client_index);
4692 }
4693
4694 /*
4695  * Return the next index# for a stateid. Mostly just increment and return
4696  * the next one, but... if the 32bit unsigned does actually wrap around
4697  * (will a BSD server stay up that long?), find
4698  * new start and end values.
4699  */
4700 static u_int32_t
4701 nfsrv_nextstateindex(struct nfsclient *clp)
4702 {
4703         struct nfsstate *stp;
4704         int i;
4705         u_int32_t canuse, min_index, max_index;
4706
4707         if (!(clp->lc_flags & LCL_INDEXNOTOK)) {
4708                 clp->lc_stateindex++;
4709                 if (clp->lc_stateindex != clp->lc_statemaxindex)
4710                         return (clp->lc_stateindex);
4711         }
4712
4713         /*
4714          * Yuck, we've hit the end.
4715          * Look for a new min and max.
4716          */
4717         min_index = 0;
4718         max_index = 0xffffffff;
4719         for (i = 0; i < nfsrv_statehashsize; i++) {
4720             LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
4721                 if (stp->ls_stateid.other[2] > 0x80000000) {
4722                     if (stp->ls_stateid.other[2] < max_index)
4723                         max_index = stp->ls_stateid.other[2];
4724                 } else {
4725                     if (stp->ls_stateid.other[2] > min_index)
4726                         min_index = stp->ls_stateid.other[2];
4727                 }
4728             }
4729         }
4730
4731         /*
4732          * Yikes, highly unlikely, but I'll handle it anyhow.
4733          */
4734         if (min_index == 0x80000000 && max_index == 0x80000001) {
4735             canuse = 0;
4736             /*
4737              * Loop around until we find an unused entry. Return that
4738              * and set LCL_INDEXNOTOK, so the search will continue next time.
4739              * (This is one of those rare cases where a goto is the
4740              *  cleanest way to code the loop.)
4741              */
4742 tryagain:
4743             for (i = 0; i < nfsrv_statehashsize; i++) {
4744                 LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
4745                     if (stp->ls_stateid.other[2] == canuse) {
4746                         canuse++;
4747                         goto tryagain;
4748                     }
4749                 }
4750             }
4751             clp->lc_flags |= LCL_INDEXNOTOK;
4752             return (canuse);
4753         }
4754
4755         /*
4756          * Ok to start again from min + 1.
4757          */
4758         clp->lc_stateindex = min_index + 1;
4759         clp->lc_statemaxindex = max_index;
4760         clp->lc_flags &= ~LCL_INDEXNOTOK;
4761         return (clp->lc_stateindex);
4762 }
4763
4764 /*
4765  * The following functions handle the stable storage file that deals with
4766  * the edge conditions described in RFC3530 Sec. 8.6.3.
4767  * The file is as follows:
4768  * - a single record at the beginning that has the lease time of the
4769  *   previous server instance (before the last reboot) and the nfsrvboottime
4770  *   values for the previous server boots.
4771  *   These previous boot times are used to ensure that the current
4772  *   nfsrvboottime does not, somehow, get set to a previous one.
4773  *   (This is important so that Stale ClientIDs and StateIDs can
4774  *    be recognized.)
4775  *   The number of previous nfsvrboottime values precedes the list.
4776  * - followed by some number of appended records with:
4777  *   - client id string
4778  *   - flag that indicates it is a record revoking state via lease
4779  *     expiration or similar
4780  *     OR has successfully acquired state.
4781  * These structures vary in length, with the client string at the end, up
4782  * to NFSV4_OPAQUELIMIT in size.
4783  *
4784  * At the end of the grace period, the file is truncated, the first
4785  * record is rewritten with updated information and any acquired state
4786  * records for successful reclaims of state are written.
4787  *
4788  * Subsequent records are appended when the first state is issued to
4789  * a client and when state is revoked for a client.
4790  *
4791  * When reading the file in, state issued records that come later in
4792  * the file override older ones, since the append log is in cronological order.
4793  * If, for some reason, the file can't be read, the grace period is
4794  * immediately terminated and all reclaims get NFSERR_NOGRACE.
4795  */
4796
4797 /*
4798  * Read in the stable storage file. Called by nfssvc() before the nfsd
4799  * processes start servicing requests.
4800  */
4801 void
4802 nfsrv_setupstable(NFSPROC_T *p)
4803 {
4804         struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
4805         struct nfsrv_stable *sp, *nsp;
4806         struct nfst_rec *tsp;
4807         int error, i, tryagain;
4808         off_t off = 0;
4809         ssize_t aresid, len;
4810
4811         /*
4812          * If NFSNSF_UPDATEDONE is set, this is a restart of the nfsds without
4813          * a reboot, so state has not been lost.
4814          */
4815         if (sf->nsf_flags & NFSNSF_UPDATEDONE)
4816                 return;
4817         /*
4818          * Set Grace over just until the file reads successfully.
4819          */
4820         nfsrvboottime = time_second;
4821         LIST_INIT(&sf->nsf_head);
4822         sf->nsf_flags = (NFSNSF_GRACEOVER | NFSNSF_NEEDLOCK);
4823         sf->nsf_eograce = NFSD_MONOSEC + NFSRV_LEASEDELTA;
4824         if (sf->nsf_fp == NULL)
4825                 return;
4826         error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
4827             (caddr_t)&sf->nsf_rec, sizeof (struct nfsf_rec), off, UIO_SYSSPACE,
4828             0, NFSFPCRED(sf->nsf_fp), &aresid, p);
4829         if (error || aresid || sf->nsf_numboots == 0 ||
4830                 sf->nsf_numboots > NFSNSF_MAXNUMBOOTS)
4831                 return;
4832
4833         /*
4834          * Now, read in the boottimes.
4835          */
4836         sf->nsf_bootvals = (time_t *)malloc((sf->nsf_numboots + 1) *
4837                 sizeof (time_t), M_TEMP, M_WAITOK);
4838         off = sizeof (struct nfsf_rec);
4839         error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
4840             (caddr_t)sf->nsf_bootvals, sf->nsf_numboots * sizeof (time_t), off,
4841             UIO_SYSSPACE, 0, NFSFPCRED(sf->nsf_fp), &aresid, p);
4842         if (error || aresid) {
4843                 free(sf->nsf_bootvals, M_TEMP);
4844                 sf->nsf_bootvals = NULL;
4845                 return;
4846         }
4847
4848         /*
4849          * Make sure this nfsrvboottime is different from all recorded
4850          * previous ones.
4851          */
4852         do {
4853                 tryagain = 0;
4854                 for (i = 0; i < sf->nsf_numboots; i++) {
4855                         if (nfsrvboottime == sf->nsf_bootvals[i]) {
4856                                 nfsrvboottime++;
4857                                 tryagain = 1;
4858                                 break;
4859                         }
4860                 }
4861         } while (tryagain);
4862
4863         sf->nsf_flags |= NFSNSF_OK;
4864         off += (sf->nsf_numboots * sizeof (time_t));
4865
4866         /*
4867          * Read through the file, building a list of records for grace
4868          * checking.
4869          * Each record is between sizeof (struct nfst_rec) and
4870          * sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1
4871          * and is actually sizeof (struct nfst_rec) + nst_len - 1.
4872          */
4873         tsp = (struct nfst_rec *)malloc(sizeof (struct nfst_rec) +
4874                 NFSV4_OPAQUELIMIT - 1, M_TEMP, M_WAITOK);
4875         do {
4876             error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
4877                 (caddr_t)tsp, sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1,
4878                 off, UIO_SYSSPACE, 0, NFSFPCRED(sf->nsf_fp), &aresid, p);
4879             len = (sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1) - aresid;
4880             if (error || (len > 0 && (len < sizeof (struct nfst_rec) ||
4881                 len < (sizeof (struct nfst_rec) + tsp->len - 1)))) {
4882                 /*
4883                  * Yuck, the file has been corrupted, so just return
4884                  * after clearing out any restart state, so the grace period
4885                  * is over.
4886                  */
4887                 LIST_FOREACH_SAFE(sp, &sf->nsf_head, nst_list, nsp) {
4888                         LIST_REMOVE(sp, nst_list);
4889                         free(sp, M_TEMP);
4890                 }
4891                 free(tsp, M_TEMP);
4892                 sf->nsf_flags &= ~NFSNSF_OK;
4893                 free(sf->nsf_bootvals, M_TEMP);
4894                 sf->nsf_bootvals = NULL;
4895                 return;
4896             }
4897             if (len > 0) {
4898                 off += sizeof (struct nfst_rec) + tsp->len - 1;
4899                 /*
4900                  * Search the list for a matching client.
4901                  */
4902                 LIST_FOREACH(sp, &sf->nsf_head, nst_list) {
4903                         if (tsp->len == sp->nst_len &&
4904                             !NFSBCMP(tsp->client, sp->nst_client, tsp->len))
4905                                 break;
4906                 }
4907                 if (sp == LIST_END(&sf->nsf_head)) {
4908                         sp = (struct nfsrv_stable *)malloc(tsp->len +
4909                                 sizeof (struct nfsrv_stable) - 1, M_TEMP,
4910                                 M_WAITOK);
4911                         NFSBCOPY((caddr_t)tsp, (caddr_t)&sp->nst_rec,
4912                                 sizeof (struct nfst_rec) + tsp->len - 1);
4913                         LIST_INSERT_HEAD(&sf->nsf_head, sp, nst_list);
4914                 } else {
4915                         if (tsp->flag == NFSNST_REVOKE)
4916                                 sp->nst_flag |= NFSNST_REVOKE;
4917                         else
4918                                 /*
4919                                  * A subsequent timestamp indicates the client
4920                                  * did a setclientid/confirm and any previous
4921                                  * revoke is no longer relevant.
4922                                  */
4923                                 sp->nst_flag &= ~NFSNST_REVOKE;
4924                 }
4925             }
4926         } while (len > 0);
4927         free(tsp, M_TEMP);
4928         sf->nsf_flags = NFSNSF_OK;
4929         sf->nsf_eograce = NFSD_MONOSEC + sf->nsf_lease +
4930                 NFSRV_LEASEDELTA;
4931 }
4932
4933 /*
4934  * Update the stable storage file, now that the grace period is over.
4935  */
4936 void
4937 nfsrv_updatestable(NFSPROC_T *p)
4938 {
4939         struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
4940         struct nfsrv_stable *sp, *nsp;
4941         int i;
4942         struct nfsvattr nva;
4943         vnode_t vp;
4944 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 500000)
4945         mount_t mp = NULL;
4946 #endif
4947         int error;
4948
4949         if (sf->nsf_fp == NULL || (sf->nsf_flags & NFSNSF_UPDATEDONE))
4950                 return;
4951         sf->nsf_flags |= NFSNSF_UPDATEDONE;
4952         /*
4953          * Ok, we need to rewrite the stable storage file.
4954          * - truncate to 0 length
4955          * - write the new first structure
4956          * - loop through the data structures, writing out any that
4957          *   have timestamps older than the old boot
4958          */
4959         if (sf->nsf_bootvals) {
4960                 sf->nsf_numboots++;
4961                 for (i = sf->nsf_numboots - 2; i >= 0; i--)
4962                         sf->nsf_bootvals[i + 1] = sf->nsf_bootvals[i];
4963         } else {
4964                 sf->nsf_numboots = 1;
4965                 sf->nsf_bootvals = (time_t *)malloc(sizeof (time_t),
4966                         M_TEMP, M_WAITOK);
4967         }
4968         sf->nsf_bootvals[0] = nfsrvboottime;
4969         sf->nsf_lease = nfsrv_lease;
4970         NFSVNO_ATTRINIT(&nva);
4971         NFSVNO_SETATTRVAL(&nva, size, 0);
4972         vp = NFSFPVNODE(sf->nsf_fp);
4973         vn_start_write(vp, &mp, V_WAIT);
4974         if (NFSVOPLOCK(vp, LK_EXCLUSIVE) == 0) {
4975                 error = nfsvno_setattr(vp, &nva, NFSFPCRED(sf->nsf_fp), p,
4976                     NULL);
4977                 NFSVOPUNLOCK(vp, 0);
4978         } else
4979                 error = EPERM;
4980         vn_finished_write(mp);
4981         if (!error)
4982             error = NFSD_RDWR(UIO_WRITE, vp,
4983                 (caddr_t)&sf->nsf_rec, sizeof (struct nfsf_rec), (off_t)0,
4984                 UIO_SYSSPACE, IO_SYNC, NFSFPCRED(sf->nsf_fp), NULL, p);
4985         if (!error)
4986             error = NFSD_RDWR(UIO_WRITE, vp,
4987                 (caddr_t)sf->nsf_bootvals,
4988                 sf->nsf_numboots * sizeof (time_t),
4989                 (off_t)(sizeof (struct nfsf_rec)),
4990                 UIO_SYSSPACE, IO_SYNC, NFSFPCRED(sf->nsf_fp), NULL, p);
4991         free(sf->nsf_bootvals, M_TEMP);
4992         sf->nsf_bootvals = NULL;
4993         if (error) {
4994                 sf->nsf_flags &= ~NFSNSF_OK;
4995                 printf("EEK! Can't write NfsV4 stable storage file\n");
4996                 return;
4997         }
4998         sf->nsf_flags |= NFSNSF_OK;
4999
5000         /*
5001          * Loop through the list and write out timestamp records for
5002          * any clients that successfully reclaimed state.
5003          */
5004         LIST_FOREACH_SAFE(sp, &sf->nsf_head, nst_list, nsp) {
5005                 if (sp->nst_flag & NFSNST_GOTSTATE) {
5006                         nfsrv_writestable(sp->nst_client, sp->nst_len,
5007                                 NFSNST_NEWSTATE, p);
5008                         sp->nst_clp->lc_flags |= LCL_STAMPEDSTABLE;
5009                 }
5010                 LIST_REMOVE(sp, nst_list);
5011                 free(sp, M_TEMP);
5012         }
5013         nfsrv_backupstable();
5014 }
5015
5016 /*
5017  * Append a record to the stable storage file.
5018  */
5019 void
5020 nfsrv_writestable(u_char *client, int len, int flag, NFSPROC_T *p)
5021 {
5022         struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
5023         struct nfst_rec *sp;
5024         int error;
5025
5026         if (!(sf->nsf_flags & NFSNSF_OK) || sf->nsf_fp == NULL)
5027                 return;
5028         sp = (struct nfst_rec *)malloc(sizeof (struct nfst_rec) +
5029                 len - 1, M_TEMP, M_WAITOK);
5030         sp->len = len;
5031         NFSBCOPY(client, sp->client, len);
5032         sp->flag = flag;
5033         error = NFSD_RDWR(UIO_WRITE, NFSFPVNODE(sf->nsf_fp),
5034             (caddr_t)sp, sizeof (struct nfst_rec) + len - 1, (off_t)0,
5035             UIO_SYSSPACE, (IO_SYNC | IO_APPEND), NFSFPCRED(sf->nsf_fp), NULL, p);
5036         free(sp, M_TEMP);
5037         if (error) {
5038                 sf->nsf_flags &= ~NFSNSF_OK;
5039                 printf("EEK! Can't write NfsV4 stable storage file\n");
5040         }
5041 }
5042
5043 /*
5044  * This function is called during the grace period to mark a client
5045  * that successfully reclaimed state.
5046  */
5047 static void
5048 nfsrv_markstable(struct nfsclient *clp)
5049 {
5050         struct nfsrv_stable *sp;
5051
5052         /*
5053          * First find the client structure.
5054          */
5055         LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
5056                 if (sp->nst_len == clp->lc_idlen &&
5057                     !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
5058                         break;
5059         }
5060         if (sp == LIST_END(&nfsrv_stablefirst.nsf_head))
5061                 return;
5062
5063         /*
5064          * Now, just mark it and set the nfsclient back pointer.
5065          */
5066         sp->nst_flag |= NFSNST_GOTSTATE;
5067         sp->nst_clp = clp;
5068 }
5069
5070 /*
5071  * This function is called when a NFSv4.1 client does a ReclaimComplete.
5072  * Very similar to nfsrv_markstable(), except for the flag being set.
5073  */
5074 static void
5075 nfsrv_markreclaim(struct nfsclient *clp)
5076 {
5077         struct nfsrv_stable *sp;
5078
5079         /*
5080          * First find the client structure.
5081          */
5082         LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
5083                 if (sp->nst_len == clp->lc_idlen &&
5084                     !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
5085                         break;
5086         }
5087         if (sp == LIST_END(&nfsrv_stablefirst.nsf_head))
5088                 return;
5089
5090         /*
5091          * Now, just set the flag.
5092          */
5093         sp->nst_flag |= NFSNST_RECLAIMED;
5094 }
5095
5096 /*
5097  * This function is called for a reclaim, to see if it gets grace.
5098  * It returns 0 if a reclaim is allowed, 1 otherwise.
5099  */
5100 static int
5101 nfsrv_checkstable(struct nfsclient *clp)
5102 {
5103         struct nfsrv_stable *sp;
5104
5105         /*
5106          * First, find the entry for the client.
5107          */
5108         LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
5109                 if (sp->nst_len == clp->lc_idlen &&
5110                     !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
5111                         break;
5112         }
5113
5114         /*
5115          * If not in the list, state was revoked or no state was issued
5116          * since the previous reboot, a reclaim is denied.
5117          */
5118         if (sp == LIST_END(&nfsrv_stablefirst.nsf_head) ||
5119             (sp->nst_flag & NFSNST_REVOKE) ||
5120             !(nfsrv_stablefirst.nsf_flags & NFSNSF_OK))
5121                 return (1);
5122         return (0);
5123 }
5124
5125 /*
5126  * Test for and try to clear out a conflicting client. This is called by
5127  * nfsrv_lockctrl() and nfsrv_openctrl() when conflicts with other clients
5128  * a found.
5129  * The trick here is that it can't revoke a conflicting client with an
5130  * expired lease unless it holds the v4root lock, so...
5131  * If no v4root lock, get the lock and return 1 to indicate "try again".
5132  * Return 0 to indicate the conflict can't be revoked and 1 to indicate
5133  * the revocation worked and the conflicting client is "bye, bye", so it
5134  * can be tried again.
5135  * Return 2 to indicate that the vnode is VI_DOOMED after NFSVOPLOCK().
5136  * Unlocks State before a non-zero value is returned.
5137  */
5138 static int
5139 nfsrv_clientconflict(struct nfsclient *clp, int *haslockp, vnode_t vp,
5140     NFSPROC_T *p)
5141 {
5142         int gotlock, lktype = 0;
5143
5144         /*
5145          * If lease hasn't expired, we can't fix it.
5146          */
5147         if (clp->lc_expiry >= NFSD_MONOSEC ||
5148             !(nfsrv_stablefirst.nsf_flags & NFSNSF_UPDATEDONE))
5149                 return (0);
5150         if (*haslockp == 0) {
5151                 NFSUNLOCKSTATE();
5152                 if (vp != NULL) {
5153                         lktype = NFSVOPISLOCKED(vp);
5154                         NFSVOPUNLOCK(vp, 0);
5155                 }
5156                 NFSLOCKV4ROOTMUTEX();
5157                 nfsv4_relref(&nfsv4rootfs_lock);
5158                 do {
5159                         gotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
5160                             NFSV4ROOTLOCKMUTEXPTR, NULL);
5161                 } while (!gotlock);
5162                 NFSUNLOCKV4ROOTMUTEX();
5163                 *haslockp = 1;
5164                 if (vp != NULL) {
5165                         NFSVOPLOCK(vp, lktype | LK_RETRY);
5166                         if ((vp->v_iflag & VI_DOOMED) != 0)
5167                                 return (2);
5168                 }
5169                 return (1);
5170         }
5171         NFSUNLOCKSTATE();
5172
5173         /*
5174          * Ok, we can expire the conflicting client.
5175          */
5176         nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
5177         nfsrv_backupstable();
5178         nfsrv_cleanclient(clp, p);
5179         nfsrv_freedeleglist(&clp->lc_deleg);
5180         nfsrv_freedeleglist(&clp->lc_olddeleg);
5181         LIST_REMOVE(clp, lc_hash);
5182         nfsrv_zapclient(clp, p);
5183         return (1);
5184 }
5185
5186 /*
5187  * Resolve a delegation conflict.
5188  * Returns 0 to indicate the conflict was resolved without sleeping.
5189  * Return -1 to indicate that the caller should check for conflicts again.
5190  * Return > 0 for an error that should be returned, normally NFSERR_DELAY.
5191  *
5192  * Also, manipulate the nfsv4root_lock, as required. It isn't changed
5193  * for a return of 0, since there was no sleep and it could be required
5194  * later. It is released for a return of NFSERR_DELAY, since the caller
5195  * will return that error. It is released when a sleep was done waiting
5196  * for the delegation to be returned or expire (so that other nfsds can
5197  * handle ops). Then, it must be acquired for the write to stable storage.
5198  * (This function is somewhat similar to nfsrv_clientconflict(), but
5199  *  the semantics differ in a couple of subtle ways. The return of 0
5200  *  indicates the conflict was resolved without sleeping here, not
5201  *  that the conflict can't be resolved and the handling of nfsv4root_lock
5202  *  differs, as noted above.)
5203  * Unlocks State before returning a non-zero value.
5204  */
5205 static int
5206 nfsrv_delegconflict(struct nfsstate *stp, int *haslockp, NFSPROC_T *p,
5207     vnode_t vp)
5208 {
5209         struct nfsclient *clp = stp->ls_clp;
5210         int gotlock, error, lktype = 0, retrycnt, zapped_clp;
5211         nfsv4stateid_t tstateid;
5212         fhandle_t tfh;
5213
5214         /*
5215          * If the conflict is with an old delegation...
5216          */
5217         if (stp->ls_flags & NFSLCK_OLDDELEG) {
5218                 /*
5219                  * You can delete it, if it has expired.
5220                  */
5221                 if (clp->lc_delegtime < NFSD_MONOSEC) {
5222                         nfsrv_freedeleg(stp);
5223                         NFSUNLOCKSTATE();
5224                         error = -1;
5225                         goto out;
5226                 }
5227                 NFSUNLOCKSTATE();
5228                 /*
5229                  * During this delay, the old delegation could expire or it
5230                  * could be recovered by the client via an Open with
5231                  * CLAIM_DELEGATE_PREV.
5232                  * Release the nfsv4root_lock, if held.
5233                  */
5234                 if (*haslockp) {
5235                         *haslockp = 0;
5236                         NFSLOCKV4ROOTMUTEX();
5237                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
5238                         NFSUNLOCKV4ROOTMUTEX();
5239                 }
5240                 error = NFSERR_DELAY;
5241                 goto out;
5242         }
5243
5244         /*
5245          * It's a current delegation, so:
5246          * - check to see if the delegation has expired
5247          *   - if so, get the v4root lock and then expire it
5248          */
5249         if (!(stp->ls_flags & NFSLCK_DELEGRECALL)) {
5250                 /*
5251                  * - do a recall callback, since not yet done
5252                  * For now, never allow truncate to be set. To use
5253                  * truncate safely, it must be guaranteed that the
5254                  * Remove, Rename or Setattr with size of 0 will
5255                  * succeed and that would require major changes to
5256                  * the VFS/Vnode OPs.
5257                  * Set the expiry time large enough so that it won't expire
5258                  * until after the callback, then set it correctly, once
5259                  * the callback is done. (The delegation will now time
5260                  * out whether or not the Recall worked ok. The timeout
5261                  * will be extended when ops are done on the delegation
5262                  * stateid, up to the timelimit.)
5263                  */
5264                 stp->ls_delegtime = NFSD_MONOSEC + (2 * nfsrv_lease) +
5265                     NFSRV_LEASEDELTA;
5266                 stp->ls_delegtimelimit = NFSD_MONOSEC + (6 * nfsrv_lease) +
5267                     NFSRV_LEASEDELTA;
5268                 stp->ls_flags |= NFSLCK_DELEGRECALL;
5269
5270                 /*
5271                  * Loop NFSRV_CBRETRYCNT times while the CBRecall replies
5272                  * NFSERR_BADSTATEID or NFSERR_BADHANDLE. This is done
5273                  * in order to try and avoid a race that could happen
5274                  * when a CBRecall request passed the Open reply with
5275                  * the delegation in it when transitting the network.
5276                  * Since nfsrv_docallback will sleep, don't use stp after
5277                  * the call.
5278                  */
5279                 NFSBCOPY((caddr_t)&stp->ls_stateid, (caddr_t)&tstateid,
5280                     sizeof (tstateid));
5281                 NFSBCOPY((caddr_t)&stp->ls_lfp->lf_fh, (caddr_t)&tfh,
5282                     sizeof (tfh));
5283                 NFSUNLOCKSTATE();
5284                 if (*haslockp) {
5285                         *haslockp = 0;
5286                         NFSLOCKV4ROOTMUTEX();
5287                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
5288                         NFSUNLOCKV4ROOTMUTEX();
5289                 }
5290                 retrycnt = 0;
5291                 do {
5292                     error = nfsrv_docallback(clp, NFSV4OP_CBRECALL,
5293                         &tstateid, 0, &tfh, NULL, NULL, 0, p);
5294                     retrycnt++;
5295                 } while ((error == NFSERR_BADSTATEID ||
5296                     error == NFSERR_BADHANDLE) && retrycnt < NFSV4_CBRETRYCNT);
5297                 error = NFSERR_DELAY;
5298                 goto out;
5299         }
5300
5301         if (clp->lc_expiry >= NFSD_MONOSEC &&
5302             stp->ls_delegtime >= NFSD_MONOSEC) {
5303                 NFSUNLOCKSTATE();
5304                 /*
5305                  * A recall has been done, but it has not yet expired.
5306                  * So, RETURN_DELAY.
5307                  */
5308                 if (*haslockp) {
5309                         *haslockp = 0;
5310                         NFSLOCKV4ROOTMUTEX();
5311                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
5312                         NFSUNLOCKV4ROOTMUTEX();
5313                 }
5314                 error = NFSERR_DELAY;
5315                 goto out;
5316         }
5317
5318         /*
5319          * If we don't yet have the lock, just get it and then return,
5320          * since we need that before deleting expired state, such as
5321          * this delegation.
5322          * When getting the lock, unlock the vnode, so other nfsds that
5323          * are in progress, won't get stuck waiting for the vnode lock.
5324          */
5325         if (*haslockp == 0) {
5326                 NFSUNLOCKSTATE();
5327                 if (vp != NULL) {
5328                         lktype = NFSVOPISLOCKED(vp);
5329                         NFSVOPUNLOCK(vp, 0);
5330                 }
5331                 NFSLOCKV4ROOTMUTEX();
5332                 nfsv4_relref(&nfsv4rootfs_lock);
5333                 do {
5334                         gotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
5335                             NFSV4ROOTLOCKMUTEXPTR, NULL);
5336                 } while (!gotlock);
5337                 NFSUNLOCKV4ROOTMUTEX();
5338                 *haslockp = 1;
5339                 if (vp != NULL) {
5340                         NFSVOPLOCK(vp, lktype | LK_RETRY);
5341                         if ((vp->v_iflag & VI_DOOMED) != 0) {
5342                                 *haslockp = 0;
5343                                 NFSLOCKV4ROOTMUTEX();
5344                                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
5345                                 NFSUNLOCKV4ROOTMUTEX();
5346                                 error = NFSERR_PERM;
5347                                 goto out;
5348                         }
5349                 }
5350                 error = -1;
5351                 goto out;
5352         }
5353
5354         NFSUNLOCKSTATE();
5355         /*
5356          * Ok, we can delete the expired delegation.
5357          * First, write the Revoke record to stable storage and then
5358          * clear out the conflict.
5359          * Since all other nfsd threads are now blocked, we can safely
5360          * sleep without the state changing.
5361          */
5362         nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
5363         nfsrv_backupstable();
5364         if (clp->lc_expiry < NFSD_MONOSEC) {
5365                 nfsrv_cleanclient(clp, p);
5366                 nfsrv_freedeleglist(&clp->lc_deleg);
5367                 nfsrv_freedeleglist(&clp->lc_olddeleg);
5368                 LIST_REMOVE(clp, lc_hash);
5369                 zapped_clp = 1;
5370         } else {
5371                 nfsrv_freedeleg(stp);
5372                 zapped_clp = 0;
5373         }
5374         if (zapped_clp)
5375                 nfsrv_zapclient(clp, p);
5376         error = -1;
5377
5378 out:
5379         NFSEXITCODE(error);
5380         return (error);
5381 }
5382
5383 /*
5384  * Check for a remove allowed, if remove is set to 1 and get rid of
5385  * delegations.
5386  */
5387 int
5388 nfsrv_checkremove(vnode_t vp, int remove, NFSPROC_T *p)
5389 {
5390         struct nfsstate *stp;
5391         struct nfslockfile *lfp;
5392         int error, haslock = 0;
5393         fhandle_t nfh;
5394
5395         /*
5396          * First, get the lock file structure.
5397          * (A return of -1 means no associated state, so remove ok.)
5398          */
5399         error = nfsrv_getlockfh(vp, NFSLCK_CHECK, NULL, &nfh, p);
5400 tryagain:
5401         NFSLOCKSTATE();
5402         if (!error)
5403                 error = nfsrv_getlockfile(NFSLCK_CHECK, NULL, &lfp, &nfh, 0);
5404         if (error) {
5405                 NFSUNLOCKSTATE();
5406                 if (haslock) {
5407                         NFSLOCKV4ROOTMUTEX();
5408                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
5409                         NFSUNLOCKV4ROOTMUTEX();
5410                 }
5411                 if (error == -1)
5412                         error = 0;
5413                 goto out;
5414         }
5415
5416         /*
5417          * Now, we must Recall any delegations.
5418          */
5419         error = nfsrv_cleandeleg(vp, lfp, NULL, &haslock, p);
5420         if (error) {
5421                 /*
5422                  * nfsrv_cleandeleg() unlocks state for non-zero
5423                  * return.
5424                  */
5425                 if (error == -1)
5426                         goto tryagain;
5427                 if (haslock) {
5428                         NFSLOCKV4ROOTMUTEX();
5429                         nfsv4_unlock(&nfsv4rootfs_lock, 1);
5430                         NFSUNLOCKV4ROOTMUTEX();
5431                 }
5432                 goto out;
5433         }
5434
5435         /*
5436          * Now, look for a conflicting open share.
5437          */
5438         if (remove) {
5439                 /*
5440                  * If the entry in the directory was the last reference to the
5441                  * corresponding filesystem object, the object can be destroyed
5442                  * */
5443                 if(lfp->lf_usecount>1)
5444                         LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
5445                                 if (stp->ls_flags & NFSLCK_WRITEDENY) {
5446                                         error = NFSERR_FILEOPEN;
5447                                         break;
5448                                 }
5449                         }
5450         }
5451
5452         NFSUNLOCKSTATE();
5453         if (haslock) {
5454                 NFSLOCKV4ROOTMUTEX();
5455                 nfsv4_unlock(&nfsv4rootfs_lock, 1);
5456                 NFSUNLOCKV4ROOTMUTEX();
5457         }
5458
5459 out:
5460         NFSEXITCODE(error);
5461         return (error);
5462 }
5463
5464 /*
5465  * Clear out all delegations for the file referred to by lfp.
5466  * May return NFSERR_DELAY, if there will be a delay waiting for
5467  * delegations to expire.
5468  * Returns -1 to indicate it slept while recalling a delegation.
5469  * This function has the side effect of deleting the nfslockfile structure,
5470  * if it no longer has associated state and didn't have to sleep.
5471  * Unlocks State before a non-zero value is returned.
5472  */
5473 static int
5474 nfsrv_cleandeleg(vnode_t vp, struct nfslockfile *lfp,
5475     struct nfsclient *clp, int *haslockp, NFSPROC_T *p)
5476 {
5477         struct nfsstate *stp, *nstp;
5478         int ret = 0;
5479
5480         stp = LIST_FIRST(&lfp->lf_deleg);
5481         while (stp != LIST_END(&lfp->lf_deleg)) {
5482                 nstp = LIST_NEXT(stp, ls_file);
5483                 if (stp->ls_clp != clp) {
5484                         ret = nfsrv_delegconflict(stp, haslockp, p, vp);
5485                         if (ret) {
5486                                 /*
5487                                  * nfsrv_delegconflict() unlocks state
5488                                  * when it returns non-zero.
5489                                  */
5490                                 goto out;
5491                         }
5492                 }
5493                 stp = nstp;
5494         }
5495 out:
5496         NFSEXITCODE(ret);
5497         return (ret);
5498 }
5499
5500 /*
5501  * There are certain operations that, when being done outside of NFSv4,
5502  * require that any NFSv4 delegation for the file be recalled.
5503  * This function is to be called for those cases:
5504  * VOP_RENAME() - When a delegation is being recalled for any reason,
5505  *      the client may have to do Opens against the server, using the file's
5506  *      final component name. If the file has been renamed on the server,
5507  *      that component name will be incorrect and the Open will fail.
5508  * VOP_REMOVE() - Theoretically, a client could Open a file after it has
5509  *      been removed on the server, if there is a delegation issued to
5510  *      that client for the file. I say "theoretically" since clients
5511  *      normally do an Access Op before the Open and that Access Op will
5512  *      fail with ESTALE. Note that NFSv2 and 3 don't even do Opens, so
5513  *      they will detect the file's removal in the same manner. (There is
5514  *      one case where RFC3530 allows a client to do an Open without first
5515  *      doing an Access Op, which is passage of a check against the ACE
5516  *      returned with a Write delegation, but current practice is to ignore
5517  *      the ACE and always do an Access Op.)
5518  *      Since the functions can only be called with an unlocked vnode, this
5519  *      can't be done at this time.
5520  * VOP_ADVLOCK() - When a client holds a delegation, it can issue byte range
5521  *      locks locally in the client, which are not visible to the server. To
5522  *      deal with this, issuing of delegations for a vnode must be disabled
5523  *      and all delegations for the vnode recalled. This is done via the
5524  *      second function, using the VV_DISABLEDELEG vflag on the vnode.
5525  */
5526 void
5527 nfsd_recalldelegation(vnode_t vp, NFSPROC_T *p)
5528 {
5529         time_t starttime;
5530         int error;
5531
5532         /*
5533          * First, check to see if the server is currently running and it has
5534          * been called for a regular file when issuing delegations.
5535          */
5536         if (newnfs_numnfsd == 0 || vp->v_type != VREG ||
5537             nfsrv_issuedelegs == 0)
5538                 return;
5539
5540         KASSERT((NFSVOPISLOCKED(vp) != LK_EXCLUSIVE), ("vp %p is locked", vp));
5541         /*
5542          * First, get a reference on the nfsv4rootfs_lock so that an
5543          * exclusive lock cannot be acquired by another thread.
5544          */
5545         NFSLOCKV4ROOTMUTEX();
5546         nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
5547         NFSUNLOCKV4ROOTMUTEX();
5548
5549         /*
5550          * Now, call nfsrv_checkremove() in a loop while it returns
5551          * NFSERR_DELAY. Return upon any other error or when timed out.
5552          */
5553         starttime = NFSD_MONOSEC;
5554         do {
5555                 if (NFSVOPLOCK(vp, LK_EXCLUSIVE) == 0) {
5556                         error = nfsrv_checkremove(vp, 0, p);
5557                         NFSVOPUNLOCK(vp, 0);
5558                 } else
5559                         error = EPERM;
5560                 if (error == NFSERR_DELAY) {
5561                         if (NFSD_MONOSEC - starttime > NFS_REMOVETIMEO)
5562                                 break;
5563                         /* Sleep for a short period of time */
5564                         (void) nfs_catnap(PZERO, 0, "nfsremove");
5565                 }
5566         } while (error == NFSERR_DELAY);
5567         NFSLOCKV4ROOTMUTEX();
5568         nfsv4_relref(&nfsv4rootfs_lock);
5569         NFSUNLOCKV4ROOTMUTEX();
5570 }
5571
5572 void
5573 nfsd_disabledelegation(vnode_t vp, NFSPROC_T *p)
5574 {
5575
5576 #ifdef VV_DISABLEDELEG
5577         /*
5578          * First, flag issuance of delegations disabled.
5579          */
5580         atomic_set_long(&vp->v_vflag, VV_DISABLEDELEG);
5581 #endif
5582
5583         /*
5584          * Then call nfsd_recalldelegation() to get rid of all extant
5585          * delegations.
5586          */
5587         nfsd_recalldelegation(vp, p);
5588 }
5589
5590 /*
5591  * Check for conflicting locks, etc. and then get rid of delegations.
5592  * (At one point I thought that I should get rid of delegations for any
5593  *  Setattr, since it could potentially disallow the I/O op (read or write)
5594  *  allowed by the delegation. However, Setattr Ops that aren't changing
5595  *  the size get a stateid of all 0s, so you can't tell if it is a delegation
5596  *  for the same client or a different one, so I decided to only get rid
5597  *  of delegations for other clients when the size is being changed.)
5598  * In general, a Setattr can disable NFS I/O Ops that are outstanding, such
5599  * as Write backs, even if there is no delegation, so it really isn't any
5600  * different?)
5601  */
5602 int
5603 nfsrv_checksetattr(vnode_t vp, struct nfsrv_descript *nd,
5604     nfsv4stateid_t *stateidp, struct nfsvattr *nvap, nfsattrbit_t *attrbitp,
5605     struct nfsexstuff *exp, NFSPROC_T *p)
5606 {
5607         struct nfsstate st, *stp = &st;
5608         struct nfslock lo, *lop = &lo;
5609         int error = 0;
5610         nfsquad_t clientid;
5611
5612         if (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SIZE)) {
5613                 stp->ls_flags = (NFSLCK_CHECK | NFSLCK_WRITEACCESS);
5614                 lop->lo_first = nvap->na_size;
5615         } else {
5616                 stp->ls_flags = 0;
5617                 lop->lo_first = 0;
5618         }
5619         if (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_OWNER) ||
5620             NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_OWNERGROUP) ||
5621             NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_MODE) ||
5622             NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_ACL))
5623                 stp->ls_flags |= NFSLCK_SETATTR;
5624         if (stp->ls_flags == 0)
5625                 goto out;
5626         lop->lo_end = NFS64BITSSET;
5627         lop->lo_flags = NFSLCK_WRITE;
5628         stp->ls_ownerlen = 0;
5629         stp->ls_op = NULL;
5630         stp->ls_uid = nd->nd_cred->cr_uid;
5631         stp->ls_stateid.seqid = stateidp->seqid;
5632         clientid.lval[0] = stp->ls_stateid.other[0] = stateidp->other[0];
5633         clientid.lval[1] = stp->ls_stateid.other[1] = stateidp->other[1];
5634         stp->ls_stateid.other[2] = stateidp->other[2];
5635         error = nfsrv_lockctrl(vp, &stp, &lop, NULL, clientid,
5636             stateidp, exp, nd, p);
5637
5638 out:
5639         NFSEXITCODE2(error, nd);
5640         return (error);
5641 }
5642
5643 /*
5644  * Check for a write delegation and do a CBGETATTR if there is one, updating
5645  * the attributes, as required.
5646  * Should I return an error if I can't get the attributes? (For now, I'll
5647  * just return ok.
5648  */
5649 int
5650 nfsrv_checkgetattr(struct nfsrv_descript *nd, vnode_t vp,
5651     struct nfsvattr *nvap, nfsattrbit_t *attrbitp, NFSPROC_T *p)
5652 {
5653         struct nfsstate *stp;
5654         struct nfslockfile *lfp;
5655         struct nfsclient *clp;
5656         struct nfsvattr nva;
5657         fhandle_t nfh;
5658         int error = 0;
5659         nfsattrbit_t cbbits;
5660         u_quad_t delegfilerev;
5661
5662         NFSCBGETATTR_ATTRBIT(attrbitp, &cbbits);
5663         if (!NFSNONZERO_ATTRBIT(&cbbits))
5664                 goto out;
5665         if (nfsrv_writedelegcnt == 0)
5666                 goto out;
5667
5668         /*
5669          * Get the lock file structure.
5670          * (A return of -1 means no associated state, so return ok.)
5671          */
5672         error = nfsrv_getlockfh(vp, NFSLCK_CHECK, NULL, &nfh, p);
5673         NFSLOCKSTATE();
5674         if (!error)
5675                 error = nfsrv_getlockfile(NFSLCK_CHECK, NULL, &lfp, &nfh, 0);
5676         if (error) {
5677                 NFSUNLOCKSTATE();
5678                 if (error == -1)
5679                         error = 0;
5680                 goto out;
5681         }
5682
5683         /*
5684          * Now, look for a write delegation.
5685          */
5686         LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
5687                 if (stp->ls_flags & NFSLCK_DELEGWRITE)
5688                         break;
5689         }
5690         if (stp == LIST_END(&lfp->lf_deleg)) {
5691                 NFSUNLOCKSTATE();
5692                 goto out;
5693         }
5694         clp = stp->ls_clp;
5695
5696         /* If the clientid is not confirmed, ignore the delegation. */
5697         if (clp->lc_flags & LCL_NEEDSCONFIRM) {
5698                 NFSUNLOCKSTATE();
5699                 goto out;
5700         }
5701
5702         delegfilerev = stp->ls_filerev;
5703         /*
5704          * If the Write delegation was issued as a part of this Compound RPC
5705          * or if we have an Implied Clientid (used in a previous Op in this
5706          * compound) and it is the client the delegation was issued to,
5707          * just return ok.
5708          * I also assume that it is from the same client iff the network
5709          * host IP address is the same as the callback address. (Not
5710          * exactly correct by the RFC, but avoids a lot of Getattr
5711          * callbacks.)
5712          */
5713         if (nd->nd_compref == stp->ls_compref ||
5714             ((nd->nd_flag & ND_IMPLIEDCLID) &&
5715              clp->lc_clientid.qval == nd->nd_clientid.qval) ||
5716              nfsaddr2_match(clp->lc_req.nr_nam, nd->nd_nam)) {
5717                 NFSUNLOCKSTATE();
5718                 goto out;
5719         }
5720
5721         /*
5722          * We are now done with the delegation state structure,
5723          * so the statelock can be released and we can now tsleep().
5724          */
5725
5726         /*
5727          * Now, we must do the CB Getattr callback, to see if Change or Size
5728          * has changed.
5729          */
5730         if (clp->lc_expiry >= NFSD_MONOSEC) {
5731                 NFSUNLOCKSTATE();
5732                 NFSVNO_ATTRINIT(&nva);
5733                 nva.na_filerev = NFS64BITSSET;
5734                 error = nfsrv_docallback(clp, NFSV4OP_CBGETATTR, NULL,
5735                     0, &nfh, &nva, &cbbits, 0, p);
5736                 if (!error) {
5737                         if ((nva.na_filerev != NFS64BITSSET &&
5738                             nva.na_filerev > delegfilerev) ||
5739                             (NFSVNO_ISSETSIZE(&nva) &&
5740                              nva.na_size != nvap->na_size)) {
5741                                 error = nfsvno_updfilerev(vp, nvap, nd, p);
5742                                 if (NFSVNO_ISSETSIZE(&nva))
5743                                         nvap->na_size = nva.na_size;
5744                         }
5745                 } else
5746                         error = 0;      /* Ignore callback errors for now. */
5747         } else {
5748                 NFSUNLOCKSTATE();
5749         }
5750
5751 out:
5752         NFSEXITCODE2(error, nd);
5753         return (error);
5754 }
5755
5756 /*
5757  * This function looks for openowners that haven't had any opens for
5758  * a while and throws them away. Called by an nfsd when NFSNSF_NOOPENS
5759  * is set.
5760  */
5761 void
5762 nfsrv_throwawayopens(NFSPROC_T *p)
5763 {
5764         struct nfsclient *clp, *nclp;
5765         struct nfsstate *stp, *nstp;
5766         int i;
5767
5768         NFSLOCKSTATE();
5769         nfsrv_stablefirst.nsf_flags &= ~NFSNSF_NOOPENS;
5770         /*
5771          * For each client...
5772          */
5773         for (i = 0; i < nfsrv_clienthashsize; i++) {
5774             LIST_FOREACH_SAFE(clp, &nfsclienthash[i], lc_hash, nclp) {
5775                 LIST_FOREACH_SAFE(stp, &clp->lc_open, ls_list, nstp) {
5776                         if (LIST_EMPTY(&stp->ls_open) &&
5777                             (stp->ls_noopens > NFSNOOPEN ||
5778                              (nfsrv_openpluslock * 2) >
5779                              nfsrv_v4statelimit))
5780                                 nfsrv_freeopenowner(stp, 0, p);
5781                 }
5782             }
5783         }
5784         NFSUNLOCKSTATE();
5785 }
5786
5787 /*
5788  * This function checks to see if the credentials are the same.
5789  * Returns 1 for not same, 0 otherwise.
5790  */
5791 static int
5792 nfsrv_notsamecredname(struct nfsrv_descript *nd, struct nfsclient *clp)
5793 {
5794
5795         if (nd->nd_flag & ND_GSS) {
5796                 if (!(clp->lc_flags & LCL_GSS))
5797                         return (1);
5798                 if (clp->lc_flags & LCL_NAME) {
5799                         if (nd->nd_princlen != clp->lc_namelen ||
5800                             NFSBCMP(nd->nd_principal, clp->lc_name,
5801                                 clp->lc_namelen))
5802                                 return (1);
5803                         else
5804                                 return (0);
5805                 }
5806                 if (nd->nd_cred->cr_uid == clp->lc_uid)
5807                         return (0);
5808                 else
5809                         return (1);
5810         } else if (clp->lc_flags & LCL_GSS)
5811                 return (1);
5812         /*
5813          * For AUTH_SYS, allow the same uid or root. (This is underspecified
5814          * in RFC3530, which talks about principals, but doesn't say anything
5815          * about uids for AUTH_SYS.)
5816          */
5817         if (nd->nd_cred->cr_uid == clp->lc_uid || nd->nd_cred->cr_uid == 0)
5818                 return (0);
5819         else
5820                 return (1);
5821 }
5822
5823 /*
5824  * Calculate the lease expiry time.
5825  */
5826 static time_t
5827 nfsrv_leaseexpiry(void)
5828 {
5829
5830         if (nfsrv_stablefirst.nsf_eograce > NFSD_MONOSEC)
5831                 return (NFSD_MONOSEC + 2 * (nfsrv_lease + NFSRV_LEASEDELTA));
5832         return (NFSD_MONOSEC + nfsrv_lease + NFSRV_LEASEDELTA);
5833 }
5834
5835 /*
5836  * Delay the delegation timeout as far as ls_delegtimelimit, as required.
5837  */
5838 static void
5839 nfsrv_delaydelegtimeout(struct nfsstate *stp)
5840 {
5841
5842         if ((stp->ls_flags & NFSLCK_DELEGRECALL) == 0)
5843                 return;
5844
5845         if ((stp->ls_delegtime + 15) > NFSD_MONOSEC &&
5846             stp->ls_delegtime < stp->ls_delegtimelimit) {
5847                 stp->ls_delegtime += nfsrv_lease;
5848                 if (stp->ls_delegtime > stp->ls_delegtimelimit)
5849                         stp->ls_delegtime = stp->ls_delegtimelimit;
5850         }
5851 }
5852
5853 /*
5854  * This function checks to see if there is any other state associated
5855  * with the openowner for this Open.
5856  * It returns 1 if there is no other state, 0 otherwise.
5857  */
5858 static int
5859 nfsrv_nootherstate(struct nfsstate *stp)
5860 {
5861         struct nfsstate *tstp;
5862
5863         LIST_FOREACH(tstp, &stp->ls_openowner->ls_open, ls_list) {
5864                 if (tstp != stp || !LIST_EMPTY(&tstp->ls_lock))
5865                         return (0);
5866         }
5867         return (1);
5868 }
5869
5870 /*
5871  * Create a list of lock deltas (changes to local byte range locking
5872  * that can be rolled back using the list) and apply the changes via
5873  * nfsvno_advlock(). Optionally, lock the list. It is expected that either
5874  * the rollback or update function will be called after this.
5875  * It returns an error (and rolls back, as required), if any nfsvno_advlock()
5876  * call fails. If it returns an error, it will unlock the list.
5877  */
5878 static int
5879 nfsrv_locallock(vnode_t vp, struct nfslockfile *lfp, int flags,
5880     uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p)
5881 {
5882         struct nfslock *lop, *nlop;
5883         int error = 0;
5884
5885         /* Loop through the list of locks. */
5886         lop = LIST_FIRST(&lfp->lf_locallock);
5887         while (first < end && lop != NULL) {
5888                 nlop = LIST_NEXT(lop, lo_lckowner);
5889                 if (first >= lop->lo_end) {
5890                         /* not there yet */
5891                         lop = nlop;
5892                 } else if (first < lop->lo_first) {
5893                         /* new one starts before entry in list */
5894                         if (end <= lop->lo_first) {
5895                                 /* no overlap between old and new */
5896                                 error = nfsrv_dolocal(vp, lfp, flags,
5897                                     NFSLCK_UNLOCK, first, end, cfp, p);
5898                                 if (error != 0)
5899                                         break;
5900                                 first = end;
5901                         } else {
5902                                 /* handle fragment overlapped with new one */
5903                                 error = nfsrv_dolocal(vp, lfp, flags,
5904                                     NFSLCK_UNLOCK, first, lop->lo_first, cfp,
5905                                     p);
5906                                 if (error != 0)
5907                                         break;
5908                                 first = lop->lo_first;
5909                         }
5910                 } else {
5911                         /* new one overlaps this entry in list */
5912                         if (end <= lop->lo_end) {
5913                                 /* overlaps all of new one */
5914                                 error = nfsrv_dolocal(vp, lfp, flags,
5915                                     lop->lo_flags, first, end, cfp, p);
5916                                 if (error != 0)
5917                                         break;
5918                                 first = end;
5919                         } else {
5920                                 /* handle fragment overlapped with new one */
5921                                 error = nfsrv_dolocal(vp, lfp, flags,
5922                                     lop->lo_flags, first, lop->lo_end, cfp, p);
5923                                 if (error != 0)
5924                                         break;
5925                                 first = lop->lo_end;
5926                                 lop = nlop;
5927                         }
5928                 }
5929         }
5930         if (first < end && error == 0)
5931                 /* handle fragment past end of list */
5932                 error = nfsrv_dolocal(vp, lfp, flags, NFSLCK_UNLOCK, first,
5933                     end, cfp, p);
5934
5935         NFSEXITCODE(error);
5936         return (error);
5937 }
5938
5939 /*
5940  * Local lock unlock. Unlock all byte ranges that are no longer locked
5941  * by NFSv4. To do this, unlock any subranges of first-->end that
5942  * do not overlap with the byte ranges of any lock in the lfp->lf_lock
5943  * list. This list has all locks for the file held by other
5944  * <clientid, lockowner> tuples. The list is ordered by increasing
5945  * lo_first value, but may have entries that overlap each other, for
5946  * the case of read locks.
5947  */
5948 static void
5949 nfsrv_localunlock(vnode_t vp, struct nfslockfile *lfp, uint64_t init_first,
5950     uint64_t init_end, NFSPROC_T *p)
5951 {
5952         struct nfslock *lop;
5953         uint64_t first, end, prevfirst __unused;
5954
5955         first = init_first;
5956         end = init_end;
5957         while (first < init_end) {
5958                 /* Loop through all nfs locks, adjusting first and end */
5959                 prevfirst = 0;
5960                 LIST_FOREACH(lop, &lfp->lf_lock, lo_lckfile) {
5961                         KASSERT(prevfirst <= lop->lo_first,
5962                             ("nfsv4 locks out of order"));
5963                         KASSERT(lop->lo_first < lop->lo_end,
5964                             ("nfsv4 bogus lock"));
5965                         prevfirst = lop->lo_first;
5966                         if (first >= lop->lo_first &&
5967                             first < lop->lo_end)
5968                                 /*
5969                                  * Overlaps with initial part, so trim
5970                                  * off that initial part by moving first past
5971                                  * it.
5972                                  */
5973                                 first = lop->lo_end;
5974                         else if (end > lop->lo_first &&
5975                             lop->lo_first > first) {
5976                                 /*
5977                                  * This lock defines the end of the
5978                                  * segment to unlock, so set end to the
5979                                  * start of it and break out of the loop.
5980                                  */
5981                                 end = lop->lo_first;
5982                                 break;
5983                         }
5984                         if (first >= end)
5985                                 /*
5986                                  * There is no segment left to do, so
5987                                  * break out of this loop and then exit
5988                                  * the outer while() since first will be set
5989                                  * to end, which must equal init_end here.
5990                                  */
5991                                 break;
5992                 }
5993                 if (first < end) {
5994                         /* Unlock this segment */
5995                         (void) nfsrv_dolocal(vp, lfp, NFSLCK_UNLOCK,
5996                             NFSLCK_READ, first, end, NULL, p);
5997                         nfsrv_locallock_commit(lfp, NFSLCK_UNLOCK,
5998                             first, end);
5999                 }
6000                 /*
6001                  * Now move past this segment and look for any further
6002                  * segment in the range, if there is one.
6003                  */
6004                 first = end;
6005                 end = init_end;
6006         }
6007 }
6008
6009 /*
6010  * Do the local lock operation and update the rollback list, as required.
6011  * Perform the rollback and return the error if nfsvno_advlock() fails.
6012  */
6013 static int
6014 nfsrv_dolocal(vnode_t vp, struct nfslockfile *lfp, int flags, int oldflags,
6015     uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p)
6016 {
6017         struct nfsrollback *rlp;
6018         int error = 0, ltype, oldltype;
6019
6020         if (flags & NFSLCK_WRITE)
6021                 ltype = F_WRLCK;
6022         else if (flags & NFSLCK_READ)
6023                 ltype = F_RDLCK;
6024         else
6025                 ltype = F_UNLCK;
6026         if (oldflags & NFSLCK_WRITE)
6027                 oldltype = F_WRLCK;
6028         else if (oldflags & NFSLCK_READ)
6029                 oldltype = F_RDLCK;
6030         else
6031                 oldltype = F_UNLCK;
6032         if (ltype == oldltype || (oldltype == F_WRLCK && ltype == F_RDLCK))
6033                 /* nothing to do */
6034                 goto out;
6035         error = nfsvno_advlock(vp, ltype, first, end, p);
6036         if (error != 0) {
6037                 if (cfp != NULL) {
6038                         cfp->cl_clientid.lval[0] = 0;
6039                         cfp->cl_clientid.lval[1] = 0;
6040                         cfp->cl_first = 0;
6041                         cfp->cl_end = NFS64BITSSET;
6042                         cfp->cl_flags = NFSLCK_WRITE;
6043                         cfp->cl_ownerlen = 5;
6044                         NFSBCOPY("LOCAL", cfp->cl_owner, 5);
6045                 }
6046                 nfsrv_locallock_rollback(vp, lfp, p);
6047         } else if (ltype != F_UNLCK) {
6048                 rlp = malloc(sizeof (struct nfsrollback), M_NFSDROLLBACK,
6049                     M_WAITOK);
6050                 rlp->rlck_first = first;
6051                 rlp->rlck_end = end;
6052                 rlp->rlck_type = oldltype;
6053                 LIST_INSERT_HEAD(&lfp->lf_rollback, rlp, rlck_list);
6054         }
6055
6056 out:
6057         NFSEXITCODE(error);
6058         return (error);
6059 }
6060
6061 /*
6062  * Roll back local lock changes and free up the rollback list.
6063  */
6064 static void
6065 nfsrv_locallock_rollback(vnode_t vp, struct nfslockfile *lfp, NFSPROC_T *p)
6066 {
6067         struct nfsrollback *rlp, *nrlp;
6068
6069         LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list, nrlp) {
6070                 (void) nfsvno_advlock(vp, rlp->rlck_type, rlp->rlck_first,
6071                     rlp->rlck_end, p);
6072                 free(rlp, M_NFSDROLLBACK);
6073         }
6074         LIST_INIT(&lfp->lf_rollback);
6075 }
6076
6077 /*
6078  * Update local lock list and delete rollback list (ie now committed to the
6079  * local locks). Most of the work is done by the internal function.
6080  */
6081 static void
6082 nfsrv_locallock_commit(struct nfslockfile *lfp, int flags, uint64_t first,
6083     uint64_t end)
6084 {
6085         struct nfsrollback *rlp, *nrlp;
6086         struct nfslock *new_lop, *other_lop;
6087
6088         new_lop = malloc(sizeof (struct nfslock), M_NFSDLOCK, M_WAITOK);
6089         if (flags & (NFSLCK_READ | NFSLCK_WRITE))
6090                 other_lop = malloc(sizeof (struct nfslock), M_NFSDLOCK,
6091                     M_WAITOK);
6092         else
6093                 other_lop = NULL;
6094         new_lop->lo_flags = flags;
6095         new_lop->lo_first = first;
6096         new_lop->lo_end = end;
6097         nfsrv_updatelock(NULL, &new_lop, &other_lop, lfp);
6098         if (new_lop != NULL)
6099                 free(new_lop, M_NFSDLOCK);
6100         if (other_lop != NULL)
6101                 free(other_lop, M_NFSDLOCK);
6102
6103         /* and get rid of the rollback list */
6104         LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list, nrlp)
6105                 free(rlp, M_NFSDROLLBACK);
6106         LIST_INIT(&lfp->lf_rollback);
6107 }
6108
6109 /*
6110  * Lock the struct nfslockfile for local lock updating.
6111  */
6112 static void
6113 nfsrv_locklf(struct nfslockfile *lfp)
6114 {
6115         int gotlock;
6116
6117         /* lf_usecount ensures *lfp won't be free'd */
6118         lfp->lf_usecount++;
6119         do {
6120                 gotlock = nfsv4_lock(&lfp->lf_locallock_lck, 1, NULL,
6121                     NFSSTATEMUTEXPTR, NULL);
6122         } while (gotlock == 0);
6123         lfp->lf_usecount--;
6124 }
6125
6126 /*
6127  * Unlock the struct nfslockfile after local lock updating.
6128  */
6129 static void
6130 nfsrv_unlocklf(struct nfslockfile *lfp)
6131 {
6132
6133         nfsv4_unlock(&lfp->lf_locallock_lck, 0);
6134 }
6135
6136 /*
6137  * Clear out all state for the NFSv4 server.
6138  * Must be called by a thread that can sleep when no nfsds are running.
6139  */
6140 void
6141 nfsrv_throwawayallstate(NFSPROC_T *p)
6142 {
6143         struct nfsclient *clp, *nclp;
6144         struct nfslockfile *lfp, *nlfp;
6145         int i;
6146
6147         /*
6148          * For each client, clean out the state and then free the structure.
6149          */
6150         for (i = 0; i < nfsrv_clienthashsize; i++) {
6151                 LIST_FOREACH_SAFE(clp, &nfsclienthash[i], lc_hash, nclp) {
6152                         nfsrv_cleanclient(clp, p);
6153                         nfsrv_freedeleglist(&clp->lc_deleg);
6154                         nfsrv_freedeleglist(&clp->lc_olddeleg);
6155                         free(clp->lc_stateid, M_NFSDCLIENT);
6156                         free(clp, M_NFSDCLIENT);
6157                 }
6158         }
6159
6160         /*
6161          * Also, free up any remaining lock file structures.
6162          */
6163         for (i = 0; i < nfsrv_lockhashsize; i++) {
6164                 LIST_FOREACH_SAFE(lfp, &nfslockhash[i], lf_hash, nlfp) {
6165                         printf("nfsd unload: fnd a lock file struct\n");
6166                         nfsrv_freenfslockfile(lfp);
6167                 }
6168         }
6169
6170         /* And get rid of the deviceid structures and layouts. */
6171         nfsrv_freealllayoutsanddevids();
6172 }
6173
6174 /*
6175  * Check the sequence# for the session and slot provided as an argument.
6176  * Also, renew the lease if the session will return NFS_OK.
6177  */
6178 int
6179 nfsrv_checksequence(struct nfsrv_descript *nd, uint32_t sequenceid,
6180     uint32_t *highest_slotidp, uint32_t *target_highest_slotidp, int cache_this,
6181     uint32_t *sflagsp, NFSPROC_T *p)
6182 {
6183         struct nfsdsession *sep;
6184         struct nfssessionhash *shp;
6185         int error;
6186         SVCXPRT *savxprt;
6187
6188         shp = NFSSESSIONHASH(nd->nd_sessionid);
6189         NFSLOCKSESSION(shp);
6190         sep = nfsrv_findsession(nd->nd_sessionid);
6191         if (sep == NULL) {
6192                 NFSUNLOCKSESSION(shp);
6193                 return (NFSERR_BADSESSION);
6194         }
6195         error = nfsv4_seqsession(sequenceid, nd->nd_slotid, *highest_slotidp,
6196             sep->sess_slots, NULL, NFSV4_SLOTS - 1);
6197         if (error != 0) {
6198                 NFSUNLOCKSESSION(shp);
6199                 return (error);
6200         }
6201         if (cache_this != 0)
6202                 nd->nd_flag |= ND_SAVEREPLY;
6203         /* Renew the lease. */
6204         sep->sess_clp->lc_expiry = nfsrv_leaseexpiry();
6205         nd->nd_clientid.qval = sep->sess_clp->lc_clientid.qval;
6206         nd->nd_flag |= ND_IMPLIEDCLID;
6207
6208         /*
6209          * If this session handles the backchannel, save the nd_xprt for this
6210          * RPC, since this is the one being used.
6211          * RFC-5661 specifies that the fore channel will be implicitly
6212          * bound by a Sequence operation.  However, since some NFSv4.1 clients
6213          * erroneously assumed that the back channel would be implicitly
6214          * bound as well, do the implicit binding unless a
6215          * BindConnectiontoSession has already been done on the session.
6216          */
6217         savxprt = NULL;
6218         if (sep->sess_clp->lc_req.nr_client != NULL &&
6219             sep->sess_cbsess.nfsess_xprt != nd->nd_xprt &&
6220             (sep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN) != 0 &&
6221             (sep->sess_clp->lc_flags & LCL_DONEBINDCONN) == 0) {
6222                 NFSD_DEBUG(2,
6223                     "nfsrv_checksequence: implicit back channel bind\n");
6224                 savxprt = sep->sess_cbsess.nfsess_xprt;
6225                 SVC_ACQUIRE(nd->nd_xprt);
6226                 nd->nd_xprt->xp_p2 =
6227                     sep->sess_clp->lc_req.nr_client->cl_private;
6228                 nd->nd_xprt->xp_idletimeout = 0;        /* Disable timeout. */
6229                 sep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
6230         }
6231
6232         *sflagsp = 0;
6233         if (sep->sess_clp->lc_req.nr_client == NULL)
6234                 *sflagsp |= NFSV4SEQ_CBPATHDOWN;
6235         NFSUNLOCKSESSION(shp);
6236         if (savxprt != NULL)
6237                 SVC_RELEASE(savxprt);
6238         if (error == NFSERR_EXPIRED) {
6239                 *sflagsp |= NFSV4SEQ_EXPIREDALLSTATEREVOKED;
6240                 error = 0;
6241         } else if (error == NFSERR_ADMINREVOKED) {
6242                 *sflagsp |= NFSV4SEQ_ADMINSTATEREVOKED;
6243                 error = 0;
6244         }
6245         *highest_slotidp = *target_highest_slotidp = NFSV4_SLOTS - 1;
6246         return (0);
6247 }
6248
6249 /*
6250  * Check/set reclaim complete for this session/clientid.
6251  */
6252 int
6253 nfsrv_checkreclaimcomplete(struct nfsrv_descript *nd, int onefs)
6254 {
6255         struct nfsdsession *sep;
6256         struct nfssessionhash *shp;
6257         int error = 0;
6258
6259         shp = NFSSESSIONHASH(nd->nd_sessionid);
6260         NFSLOCKSTATE();
6261         NFSLOCKSESSION(shp);
6262         sep = nfsrv_findsession(nd->nd_sessionid);
6263         if (sep == NULL) {
6264                 NFSUNLOCKSESSION(shp);
6265                 NFSUNLOCKSTATE();
6266                 return (NFSERR_BADSESSION);
6267         }
6268
6269         if (onefs != 0)
6270                 sep->sess_clp->lc_flags |= LCL_RECLAIMONEFS;
6271                 /* Check to see if reclaim complete has already happened. */
6272         else if ((sep->sess_clp->lc_flags & LCL_RECLAIMCOMPLETE) != 0)
6273                 error = NFSERR_COMPLETEALREADY;
6274         else {
6275                 sep->sess_clp->lc_flags |= LCL_RECLAIMCOMPLETE;
6276                 nfsrv_markreclaim(sep->sess_clp);
6277         }
6278         NFSUNLOCKSESSION(shp);
6279         NFSUNLOCKSTATE();
6280         return (error);
6281 }
6282
6283 /*
6284  * Cache the reply in a session slot.
6285  */
6286 void
6287 nfsrv_cache_session(struct nfsrv_descript *nd, struct mbuf **m)
6288 {
6289         struct nfsdsession *sep;
6290         struct nfssessionhash *shp;
6291         char *buf, *cp;
6292 #ifdef INET
6293         struct sockaddr_in *sin;
6294 #endif
6295 #ifdef INET6
6296         struct sockaddr_in6 *sin6;
6297 #endif
6298
6299         shp = NFSSESSIONHASH(nd->nd_sessionid);
6300         NFSLOCKSESSION(shp);
6301         sep = nfsrv_findsession(nd->nd_sessionid);
6302         if (sep == NULL) {
6303                 NFSUNLOCKSESSION(shp);
6304                 if ((nfsrv_stablefirst.nsf_flags & NFSNSF_GRACEOVER) != 0) {
6305                         buf = malloc(INET6_ADDRSTRLEN, M_TEMP, M_WAITOK);
6306                         switch (nd->nd_nam->sa_family) {
6307 #ifdef INET
6308                         case AF_INET:
6309                                 sin = (struct sockaddr_in *)nd->nd_nam;
6310                                 cp = inet_ntop(sin->sin_family,
6311                                     &sin->sin_addr.s_addr, buf,
6312                                     INET6_ADDRSTRLEN);
6313                                 break;
6314 #endif
6315 #ifdef INET6
6316                         case AF_INET6:
6317                                 sin6 = (struct sockaddr_in6 *)nd->nd_nam;
6318                                 cp = inet_ntop(sin6->sin6_family,
6319                                     &sin6->sin6_addr, buf, INET6_ADDRSTRLEN);
6320                                 break;
6321 #endif
6322                         default:
6323                                 cp = NULL;
6324                         }
6325                         if (cp != NULL)
6326                                 printf("nfsrv_cache_session: no session "
6327                                     "IPaddr=%s\n", cp);
6328                         else
6329                                 printf("nfsrv_cache_session: no session\n");
6330                         free(buf, M_TEMP);
6331                 }
6332                 m_freem(*m);
6333                 return;
6334         }
6335         nfsv4_seqsess_cacherep(nd->nd_slotid, sep->sess_slots, nd->nd_repstat,
6336             m);
6337         NFSUNLOCKSESSION(shp);
6338 }
6339
6340 /*
6341  * Search for a session that matches the sessionid.
6342  */
6343 static struct nfsdsession *
6344 nfsrv_findsession(uint8_t *sessionid)
6345 {
6346         struct nfsdsession *sep;
6347         struct nfssessionhash *shp;
6348
6349         shp = NFSSESSIONHASH(sessionid);
6350         LIST_FOREACH(sep, &shp->list, sess_hash) {
6351                 if (!NFSBCMP(sessionid, sep->sess_sessionid, NFSX_V4SESSIONID))
6352                         break;
6353         }
6354         return (sep);
6355 }
6356
6357 /*
6358  * Destroy a session.
6359  */
6360 int
6361 nfsrv_destroysession(struct nfsrv_descript *nd, uint8_t *sessionid)
6362 {
6363         int error, igotlock, samesess;
6364
6365         samesess = 0;
6366         if (!NFSBCMP(sessionid, nd->nd_sessionid, NFSX_V4SESSIONID) &&
6367             (nd->nd_flag & ND_HASSEQUENCE) != 0) {
6368                 samesess = 1;
6369                 if ((nd->nd_flag & ND_LASTOP) == 0)
6370                         return (NFSERR_BADSESSION);
6371         }
6372
6373         /* Lock out other nfsd threads */
6374         NFSLOCKV4ROOTMUTEX();
6375         nfsv4_relref(&nfsv4rootfs_lock);
6376         do {
6377                 igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
6378                     NFSV4ROOTLOCKMUTEXPTR, NULL);
6379         } while (igotlock == 0);
6380         NFSUNLOCKV4ROOTMUTEX();
6381
6382         error = nfsrv_freesession(NULL, sessionid);
6383         if (error == 0 && samesess != 0)
6384                 nd->nd_flag &= ~ND_HASSEQUENCE;
6385
6386         NFSLOCKV4ROOTMUTEX();
6387         nfsv4_unlock(&nfsv4rootfs_lock, 1);
6388         NFSUNLOCKV4ROOTMUTEX();
6389         return (error);
6390 }
6391
6392 /*
6393  * Bind a connection to a session.
6394  * For now, only certain variants are supported, since the current session
6395  * structure can only handle a single backchannel entry, which will be
6396  * applied to all connections if it is set.
6397  */
6398 int
6399 nfsrv_bindconnsess(struct nfsrv_descript *nd, uint8_t *sessionid, int *foreaftp)
6400 {
6401         struct nfssessionhash *shp;
6402         struct nfsdsession *sep;
6403         struct nfsclient *clp;
6404         SVCXPRT *savxprt;
6405         int error;
6406
6407         error = 0;
6408         savxprt = NULL;
6409         shp = NFSSESSIONHASH(sessionid);
6410         NFSLOCKSTATE();
6411         NFSLOCKSESSION(shp);
6412         sep = nfsrv_findsession(sessionid);
6413         if (sep != NULL) {
6414                 clp = sep->sess_clp;
6415                 if (*foreaftp == NFSCDFC4_BACK ||
6416                     *foreaftp == NFSCDFC4_BACK_OR_BOTH ||
6417                     *foreaftp == NFSCDFC4_FORE_OR_BOTH) {
6418                         /* Try to set up a backchannel. */
6419                         if (clp->lc_req.nr_client == NULL) {
6420                                 NFSD_DEBUG(2, "nfsrv_bindconnsess: acquire "
6421                                     "backchannel\n");
6422                                 clp->lc_req.nr_client = (struct __rpc_client *)
6423                                     clnt_bck_create(nd->nd_xprt->xp_socket,
6424                                     sep->sess_cbprogram, NFSV4_CBVERS);
6425                         }
6426                         if (clp->lc_req.nr_client != NULL) {
6427                                 NFSD_DEBUG(2, "nfsrv_bindconnsess: set up "
6428                                     "backchannel\n");
6429                                 savxprt = sep->sess_cbsess.nfsess_xprt;
6430                                 SVC_ACQUIRE(nd->nd_xprt);
6431                                 nd->nd_xprt->xp_p2 =
6432                                     clp->lc_req.nr_client->cl_private;
6433                                 /* Disable idle timeout. */
6434                                 nd->nd_xprt->xp_idletimeout = 0;
6435                                 sep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
6436                                 sep->sess_crflags |= NFSV4CRSESS_CONNBACKCHAN;
6437                                 clp->lc_flags |= LCL_DONEBINDCONN;
6438                                 if (*foreaftp == NFSCDFS4_BACK)
6439                                         *foreaftp = NFSCDFS4_BACK;
6440                                 else
6441                                         *foreaftp = NFSCDFS4_BOTH;
6442                         } else if (*foreaftp != NFSCDFC4_BACK) {
6443                                 NFSD_DEBUG(2, "nfsrv_bindconnsess: can't set "
6444                                     "up backchannel\n");
6445                                 sep->sess_crflags &= ~NFSV4CRSESS_CONNBACKCHAN;
6446                                 clp->lc_flags |= LCL_DONEBINDCONN;
6447                                 *foreaftp = NFSCDFS4_FORE;
6448                         } else {
6449                                 error = NFSERR_NOTSUPP;
6450                                 printf("nfsrv_bindconnsess: Can't add "
6451                                     "backchannel\n");
6452                         }
6453                 } else {
6454                         NFSD_DEBUG(2, "nfsrv_bindconnsess: Set forechannel\n");
6455                         clp->lc_flags |= LCL_DONEBINDCONN;
6456                         *foreaftp = NFSCDFS4_FORE;
6457                 }
6458         } else
6459                 error = NFSERR_BADSESSION;
6460         NFSUNLOCKSESSION(shp);
6461         NFSUNLOCKSTATE();
6462         if (savxprt != NULL)
6463                 SVC_RELEASE(savxprt);
6464         return (error);
6465 }
6466
6467 /*
6468  * Free up a session structure.
6469  */
6470 static int
6471 nfsrv_freesession(struct nfsdsession *sep, uint8_t *sessionid)
6472 {
6473         struct nfssessionhash *shp;
6474         int i;
6475
6476         NFSLOCKSTATE();
6477         if (sep == NULL) {
6478                 shp = NFSSESSIONHASH(sessionid);
6479                 NFSLOCKSESSION(shp);
6480                 sep = nfsrv_findsession(sessionid);
6481         } else {
6482                 shp = NFSSESSIONHASH(sep->sess_sessionid);
6483                 NFSLOCKSESSION(shp);
6484         }
6485         if (sep != NULL) {
6486                 sep->sess_refcnt--;
6487                 if (sep->sess_refcnt > 0) {
6488                         NFSUNLOCKSESSION(shp);
6489                         NFSUNLOCKSTATE();
6490                         return (NFSERR_BACKCHANBUSY);
6491                 }
6492                 LIST_REMOVE(sep, sess_hash);
6493                 LIST_REMOVE(sep, sess_list);
6494         }
6495         NFSUNLOCKSESSION(shp);
6496         NFSUNLOCKSTATE();
6497         if (sep == NULL)
6498                 return (NFSERR_BADSESSION);
6499         for (i = 0; i < NFSV4_SLOTS; i++)
6500                 if (sep->sess_slots[i].nfssl_reply != NULL)
6501                         m_freem(sep->sess_slots[i].nfssl_reply);
6502         if (sep->sess_cbsess.nfsess_xprt != NULL)
6503                 SVC_RELEASE(sep->sess_cbsess.nfsess_xprt);
6504         free(sep, M_NFSDSESSION);
6505         return (0);
6506 }
6507
6508 /*
6509  * Free a stateid.
6510  * RFC5661 says that it should fail when there are associated opens, locks
6511  * or delegations. Since stateids represent opens, I don't see how you can
6512  * free an open stateid (it will be free'd when closed), so this function
6513  * only works for lock stateids (freeing the lock_owner) or delegations.
6514  */
6515 int
6516 nfsrv_freestateid(struct nfsrv_descript *nd, nfsv4stateid_t *stateidp,
6517     NFSPROC_T *p)
6518 {
6519         struct nfsclient *clp;
6520         struct nfsstate *stp;
6521         int error;
6522
6523         NFSLOCKSTATE();
6524         /*
6525          * Look up the stateid
6526          */
6527         error = nfsrv_getclient((nfsquad_t)((u_quad_t)0), CLOPS_RENEW, &clp,
6528             NULL, (nfsquad_t)((u_quad_t)0), 0, nd, p);
6529         if (error == 0) {
6530                 /* First, check for a delegation. */
6531                 LIST_FOREACH(stp, &clp->lc_deleg, ls_list) {
6532                         if (!NFSBCMP(stp->ls_stateid.other, stateidp->other,
6533                             NFSX_STATEIDOTHER))
6534                                 break;
6535                 }
6536                 if (stp != NULL) {
6537                         nfsrv_freedeleg(stp);
6538                         NFSUNLOCKSTATE();
6539                         return (error);
6540                 }
6541         }
6542         /* Not a delegation, try for a lock_owner. */
6543         if (error == 0)
6544                 error = nfsrv_getstate(clp, stateidp, 0, &stp);
6545         if (error == 0 && ((stp->ls_flags & (NFSLCK_OPEN | NFSLCK_DELEGREAD |
6546             NFSLCK_DELEGWRITE)) != 0 || (stp->ls_flags & NFSLCK_LOCK) == 0))
6547                 /* Not a lock_owner stateid. */
6548                 error = NFSERR_LOCKSHELD;
6549         if (error == 0 && !LIST_EMPTY(&stp->ls_lock))
6550                 error = NFSERR_LOCKSHELD;
6551         if (error == 0)
6552                 nfsrv_freelockowner(stp, NULL, 0, p);
6553         NFSUNLOCKSTATE();
6554         return (error);
6555 }
6556
6557 /*
6558  * Test a stateid.
6559  */
6560 int
6561 nfsrv_teststateid(struct nfsrv_descript *nd, nfsv4stateid_t *stateidp,
6562     NFSPROC_T *p)
6563 {
6564         struct nfsclient *clp;
6565         struct nfsstate *stp;
6566         int error;
6567
6568         NFSLOCKSTATE();
6569         /*
6570          * Look up the stateid
6571          */
6572         error = nfsrv_getclient((nfsquad_t)((u_quad_t)0), CLOPS_RENEW, &clp,
6573             NULL, (nfsquad_t)((u_quad_t)0), 0, nd, p);
6574         if (error == 0)
6575                 error = nfsrv_getstate(clp, stateidp, 0, &stp);
6576         if (error == 0 && stateidp->seqid != 0 &&
6577             SEQ_LT(stateidp->seqid, stp->ls_stateid.seqid))
6578                 error = NFSERR_OLDSTATEID;
6579         NFSUNLOCKSTATE();
6580         return (error);
6581 }
6582
6583 /*
6584  * Generate the xdr for an NFSv4.1 CBSequence Operation.
6585  */
6586 static int
6587 nfsv4_setcbsequence(struct nfsrv_descript *nd, struct nfsclient *clp,
6588     int dont_replycache, struct nfsdsession **sepp)
6589 {
6590         struct nfsdsession *sep;
6591         uint32_t *tl, slotseq = 0;
6592         int maxslot, slotpos;
6593         uint8_t sessionid[NFSX_V4SESSIONID];
6594         int error;
6595
6596         error = nfsv4_getcbsession(clp, sepp);
6597         if (error != 0)
6598                 return (error);
6599         sep = *sepp;
6600         (void)nfsv4_sequencelookup(NULL, &sep->sess_cbsess, &slotpos, &maxslot,
6601             &slotseq, sessionid);
6602         KASSERT(maxslot >= 0, ("nfsv4_setcbsequence neg maxslot"));
6603
6604         /* Build the Sequence arguments. */
6605         NFSM_BUILD(tl, uint32_t *, NFSX_V4SESSIONID + 5 * NFSX_UNSIGNED);
6606         bcopy(sessionid, tl, NFSX_V4SESSIONID);
6607         tl += NFSX_V4SESSIONID / NFSX_UNSIGNED;
6608         nd->nd_slotseq = tl;
6609         *tl++ = txdr_unsigned(slotseq);
6610         *tl++ = txdr_unsigned(slotpos);
6611         *tl++ = txdr_unsigned(maxslot);
6612         if (dont_replycache == 0)
6613                 *tl++ = newnfs_true;
6614         else
6615                 *tl++ = newnfs_false;
6616         *tl = 0;                        /* No referring call list, for now. */
6617         nd->nd_flag |= ND_HASSEQUENCE;
6618         return (0);
6619 }
6620
6621 /*
6622  * Get a session for the callback.
6623  */
6624 static int
6625 nfsv4_getcbsession(struct nfsclient *clp, struct nfsdsession **sepp)
6626 {
6627         struct nfsdsession *sep;
6628
6629         NFSLOCKSTATE();
6630         LIST_FOREACH(sep, &clp->lc_session, sess_list) {
6631                 if ((sep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN) != 0)
6632                         break;
6633         }
6634         if (sep == NULL) {
6635                 NFSUNLOCKSTATE();
6636                 return (NFSERR_BADSESSION);
6637         }
6638         sep->sess_refcnt++;
6639         *sepp = sep;
6640         NFSUNLOCKSTATE();
6641         return (0);
6642 }
6643
6644 /*
6645  * Free up all backchannel xprts.  This needs to be done when the nfsd threads
6646  * exit, since those transports will all be going away.
6647  * This is only called after all the nfsd threads are done performing RPCs,
6648  * so locking shouldn't be an issue.
6649  */
6650 void
6651 nfsrv_freeallbackchannel_xprts(void)
6652 {
6653         struct nfsdsession *sep;
6654         struct nfsclient *clp;
6655         SVCXPRT *xprt;
6656         int i;
6657
6658         for (i = 0; i < nfsrv_clienthashsize; i++) {
6659                 LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
6660                         LIST_FOREACH(sep, &clp->lc_session, sess_list) {
6661                                 xprt = sep->sess_cbsess.nfsess_xprt;
6662                                 sep->sess_cbsess.nfsess_xprt = NULL;
6663                                 if (xprt != NULL)
6664                                         SVC_RELEASE(xprt);
6665                         }
6666                 }
6667         }
6668 }
6669
6670 /*
6671  * Do a layout commit.  Actually just call nfsrv_updatemdsattr().
6672  * I have no idea if the rest of these arguments will ever be useful?
6673  */
6674 int
6675 nfsrv_layoutcommit(struct nfsrv_descript *nd, vnode_t vp, int layouttype,
6676     int hasnewoff, uint64_t newoff, uint64_t offset, uint64_t len,
6677     int hasnewmtime, struct timespec *newmtimep, int reclaim,
6678     nfsv4stateid_t *stateidp, int maxcnt, char *layp, int *hasnewsizep,
6679     uint64_t *newsizep, struct ucred *cred, NFSPROC_T *p)
6680 {
6681         struct nfsvattr na;
6682         int error;
6683
6684         error = nfsrv_updatemdsattr(vp, &na, p);
6685         if (error == 0) {
6686                 *hasnewsizep = 1;
6687                 *newsizep = na.na_size;
6688         }
6689         return (error);
6690 }
6691
6692 /*
6693  * Try and get a layout.
6694  */
6695 int
6696 nfsrv_layoutget(struct nfsrv_descript *nd, vnode_t vp, struct nfsexstuff *exp,
6697     int layouttype, int *iomode, uint64_t *offset, uint64_t *len,
6698     uint64_t minlen, nfsv4stateid_t *stateidp, int maxcnt, int *retonclose,
6699     int *layoutlenp, char *layp, struct ucred *cred, NFSPROC_T *p)
6700 {
6701         struct nfslayouthash *lhyp;
6702         struct nfslayout *lyp;
6703         char *devid;
6704         fhandle_t fh, *dsfhp;
6705         int error, mirrorcnt;
6706
6707         if (nfsrv_devidcnt == 0)
6708                 return (NFSERR_UNKNLAYOUTTYPE);
6709
6710         if (*offset != 0)
6711                 printf("nfsrv_layoutget: off=%ju len=%ju\n", (uintmax_t)*offset,
6712                     (uintmax_t)*len);
6713         error = nfsvno_getfh(vp, &fh, p);
6714         NFSD_DEBUG(4, "layoutget getfh=%d\n", error);
6715         if (error != 0)
6716                 return (error);
6717
6718         /*
6719          * For now, all layouts are for entire files.
6720          * Only issue Read/Write layouts if requested for a non-readonly fs.
6721          */
6722         if (NFSVNO_EXRDONLY(exp)) {
6723                 if (*iomode == NFSLAYOUTIOMODE_RW)
6724                         return (NFSERR_LAYOUTTRYLATER);
6725                 *iomode = NFSLAYOUTIOMODE_READ;
6726         }
6727         if (*iomode != NFSLAYOUTIOMODE_RW)
6728                 *iomode = NFSLAYOUTIOMODE_READ;
6729
6730         /*
6731          * Check to see if a write layout can be issued for this file.
6732          * This is used during mirror recovery to avoid RW layouts being
6733          * issued for a file while it is being copied to the recovered
6734          * mirror.
6735          */
6736         if (*iomode == NFSLAYOUTIOMODE_RW && nfsrv_dontlayout(&fh) != 0)
6737                 return (NFSERR_LAYOUTTRYLATER);
6738
6739         *retonclose = 0;
6740         *offset = 0;
6741         *len = UINT64_MAX;
6742
6743         /* First, see if a layout already exists and return if found. */
6744         lhyp = NFSLAYOUTHASH(&fh);
6745         NFSLOCKLAYOUT(lhyp);
6746         error = nfsrv_findlayout(&nd->nd_clientid, &fh, layouttype, p, &lyp);
6747         NFSD_DEBUG(4, "layoutget findlay=%d\n", error);
6748         /*
6749          * Not sure if the seqid must be the same, so I won't check it.
6750          */
6751         if (error == 0 && (stateidp->other[0] != lyp->lay_stateid.other[0] ||
6752             stateidp->other[1] != lyp->lay_stateid.other[1] ||
6753             stateidp->other[2] != lyp->lay_stateid.other[2])) {
6754                 if ((lyp->lay_flags & NFSLAY_CALLB) == 0) {
6755                         NFSUNLOCKLAYOUT(lhyp);
6756                         NFSD_DEBUG(1, "ret bad stateid\n");
6757                         return (NFSERR_BADSTATEID);
6758                 }
6759                 /*
6760                  * I believe we get here because there is a race between
6761                  * the client processing the CBLAYOUTRECALL and the layout
6762                  * being deleted here on the server.
6763                  * The client has now done a LayoutGet with a non-layout
6764                  * stateid, as it would when there is no layout.
6765                  * As such, free this layout and set error == NFSERR_BADSTATEID
6766                  * so the code below will create a new layout structure as
6767                  * would happen if no layout was found.
6768                  * "lyp" will be set before being used below, but set it NULL
6769                  * as a safety belt.
6770                  */
6771                 nfsrv_freelayout(&lhyp->list, lyp);
6772                 lyp = NULL;
6773                 error = NFSERR_BADSTATEID;
6774         }
6775         if (error == 0) {
6776                 if (lyp->lay_layoutlen > maxcnt) {
6777                         NFSUNLOCKLAYOUT(lhyp);
6778                         NFSD_DEBUG(1, "ret layout too small\n");
6779                         return (NFSERR_TOOSMALL);
6780                 }
6781                 if (*iomode == NFSLAYOUTIOMODE_RW)
6782                         lyp->lay_flags |= NFSLAY_RW;
6783                 else
6784                         lyp->lay_flags |= NFSLAY_READ;
6785                 NFSBCOPY(lyp->lay_xdr, layp, lyp->lay_layoutlen);
6786                 *layoutlenp = lyp->lay_layoutlen;
6787                 if (++lyp->lay_stateid.seqid == 0)
6788                         lyp->lay_stateid.seqid = 1;
6789                 stateidp->seqid = lyp->lay_stateid.seqid;
6790                 NFSUNLOCKLAYOUT(lhyp);
6791                 NFSD_DEBUG(4, "ret fnd layout\n");
6792                 return (0);
6793         }
6794         NFSUNLOCKLAYOUT(lhyp);
6795
6796         /* Find the device id and file handle. */
6797         dsfhp = malloc(sizeof(fhandle_t) * NFSDEV_MAXMIRRORS, M_TEMP, M_WAITOK);
6798         devid = malloc(NFSX_V4DEVICEID * NFSDEV_MAXMIRRORS, M_TEMP, M_WAITOK);
6799         error = nfsrv_dsgetdevandfh(vp, p, &mirrorcnt, dsfhp, devid);
6800         NFSD_DEBUG(4, "layoutget devandfh=%d\n", error);
6801         if (error == 0) {
6802                 if (layouttype == NFSLAYOUT_NFSV4_1_FILES) {
6803                         if (NFSX_V4FILELAYOUT > maxcnt)
6804                                 error = NFSERR_TOOSMALL;
6805                         else
6806                                 lyp = nfsrv_filelayout(nd, *iomode, &fh, dsfhp,
6807                                     devid, vp->v_mount->mnt_stat.f_fsid);
6808                 } else {
6809                         if (NFSX_V4FLEXLAYOUT(mirrorcnt) > maxcnt)
6810                                 error = NFSERR_TOOSMALL;
6811                         else
6812                                 lyp = nfsrv_flexlayout(nd, *iomode, mirrorcnt,
6813                                     &fh, dsfhp, devid,
6814                                     vp->v_mount->mnt_stat.f_fsid);
6815                 }
6816         }
6817         free(dsfhp, M_TEMP);
6818         free(devid, M_TEMP);
6819         if (error != 0)
6820                 return (error);
6821
6822         /*
6823          * Now, add this layout to the list.
6824          */
6825         error = nfsrv_addlayout(nd, &lyp, stateidp, layp, layoutlenp, p);
6826         NFSD_DEBUG(4, "layoutget addl=%d\n", error);
6827         /*
6828          * The lyp will be set to NULL by nfsrv_addlayout() if it
6829          * linked the new structure into the lists.
6830          */
6831         free(lyp, M_NFSDSTATE);
6832         return (error);
6833 }
6834
6835 /*
6836  * Generate a File Layout.
6837  */
6838 static struct nfslayout *
6839 nfsrv_filelayout(struct nfsrv_descript *nd, int iomode, fhandle_t *fhp,
6840     fhandle_t *dsfhp, char *devid, fsid_t fs)
6841 {
6842         uint32_t *tl;
6843         struct nfslayout *lyp;
6844         uint64_t pattern_offset;
6845
6846         lyp = malloc(sizeof(struct nfslayout) + NFSX_V4FILELAYOUT, M_NFSDSTATE,
6847             M_WAITOK | M_ZERO);
6848         lyp->lay_type = NFSLAYOUT_NFSV4_1_FILES;
6849         if (iomode == NFSLAYOUTIOMODE_RW)
6850                 lyp->lay_flags = NFSLAY_RW;
6851         else
6852                 lyp->lay_flags = NFSLAY_READ;
6853         NFSBCOPY(fhp, &lyp->lay_fh, sizeof(*fhp));
6854         lyp->lay_clientid.qval = nd->nd_clientid.qval;
6855         lyp->lay_fsid = fs;
6856
6857         /* Fill in the xdr for the files layout. */
6858         tl = (uint32_t *)lyp->lay_xdr;
6859         NFSBCOPY(devid, tl, NFSX_V4DEVICEID);           /* Device ID. */
6860         tl += (NFSX_V4DEVICEID / NFSX_UNSIGNED);
6861
6862         /*
6863          * Make the stripe size as many 64K blocks as will fit in the stripe
6864          * mask. Since there is only one stripe, the stripe size doesn't really
6865          * matter, except that the Linux client will only handle an exact
6866          * multiple of their PAGE_SIZE (usually 4K).  I chose 64K as a value
6867          * that should cover most/all arches w.r.t. PAGE_SIZE.
6868          */
6869         *tl++ = txdr_unsigned(NFSFLAYUTIL_STRIPE_MASK & ~0xffff);
6870         *tl++ = 0;                                      /* 1st stripe index. */
6871         pattern_offset = 0;
6872         txdr_hyper(pattern_offset, tl); tl += 2;        /* Pattern offset. */
6873         *tl++ = txdr_unsigned(1);                       /* 1 file handle. */
6874         *tl++ = txdr_unsigned(NFSX_V4PNFSFH);
6875         NFSBCOPY(dsfhp, tl, sizeof(*dsfhp));
6876         lyp->lay_layoutlen = NFSX_V4FILELAYOUT;
6877         return (lyp);
6878 }
6879
6880 #define FLEX_OWNERID    "999"
6881 #define FLEX_UID0       "0"
6882 /*
6883  * Generate a Flex File Layout.
6884  * The FLEX_OWNERID can be any string of 3 decimal digits. Although this
6885  * string goes on the wire, it isn't supposed to be used by the client,
6886  * since this server uses tight coupling.
6887  * Although not recommended by the spec., if vfs.nfsd.flexlinuxhack=1 use
6888  * a string of "0". This works around the Linux Flex File Layout driver bug
6889  * which uses the synthetic uid/gid strings for the "tightly coupled" case.
6890  */
6891 static struct nfslayout *
6892 nfsrv_flexlayout(struct nfsrv_descript *nd, int iomode, int mirrorcnt,
6893     fhandle_t *fhp, fhandle_t *dsfhp, char *devid, fsid_t fs)
6894 {
6895         uint32_t *tl;
6896         struct nfslayout *lyp;
6897         uint64_t lenval;
6898         int i;
6899
6900         lyp = malloc(sizeof(struct nfslayout) + NFSX_V4FLEXLAYOUT(mirrorcnt),
6901             M_NFSDSTATE, M_WAITOK | M_ZERO);
6902         lyp->lay_type = NFSLAYOUT_FLEXFILE;
6903         if (iomode == NFSLAYOUTIOMODE_RW)
6904                 lyp->lay_flags = NFSLAY_RW;
6905         else
6906                 lyp->lay_flags = NFSLAY_READ;
6907         NFSBCOPY(fhp, &lyp->lay_fh, sizeof(*fhp));
6908         lyp->lay_clientid.qval = nd->nd_clientid.qval;
6909         lyp->lay_fsid = fs;
6910         lyp->lay_mirrorcnt = mirrorcnt;
6911
6912         /* Fill in the xdr for the files layout. */
6913         tl = (uint32_t *)lyp->lay_xdr;
6914         lenval = 0;
6915         txdr_hyper(lenval, tl); tl += 2;                /* Stripe unit. */
6916         *tl++ = txdr_unsigned(mirrorcnt);               /* # of mirrors. */
6917         for (i = 0; i < mirrorcnt; i++) {
6918                 *tl++ = txdr_unsigned(1);               /* One stripe. */
6919                 NFSBCOPY(devid, tl, NFSX_V4DEVICEID);   /* Device ID. */
6920                 tl += (NFSX_V4DEVICEID / NFSX_UNSIGNED);
6921                 devid += NFSX_V4DEVICEID;
6922                 *tl++ = txdr_unsigned(1);               /* Efficiency. */
6923                 *tl++ = 0;                              /* Proxy Stateid. */
6924                 *tl++ = 0x55555555;
6925                 *tl++ = 0x55555555;
6926                 *tl++ = 0x55555555;
6927                 *tl++ = txdr_unsigned(1);               /* 1 file handle. */
6928                 *tl++ = txdr_unsigned(NFSX_V4PNFSFH);
6929                 NFSBCOPY(dsfhp, tl, sizeof(*dsfhp));
6930                 tl += (NFSM_RNDUP(NFSX_V4PNFSFH) / NFSX_UNSIGNED);
6931                 dsfhp++;
6932                 if (nfsrv_flexlinuxhack != 0) {
6933                         *tl++ = txdr_unsigned(strlen(FLEX_UID0));
6934                         *tl = 0;                /* 0 pad string. */
6935                         NFSBCOPY(FLEX_UID0, tl++, strlen(FLEX_UID0));
6936                         *tl++ = txdr_unsigned(strlen(FLEX_UID0));
6937                         *tl = 0;                /* 0 pad string. */
6938                         NFSBCOPY(FLEX_UID0, tl++, strlen(FLEX_UID0));
6939                 } else {
6940                         *tl++ = txdr_unsigned(strlen(FLEX_OWNERID));
6941                         NFSBCOPY(FLEX_OWNERID, tl++, NFSX_UNSIGNED);
6942                         *tl++ = txdr_unsigned(strlen(FLEX_OWNERID));
6943                         NFSBCOPY(FLEX_OWNERID, tl++, NFSX_UNSIGNED);
6944                 }
6945         }
6946         *tl++ = txdr_unsigned(0);               /* ff_flags. */
6947         *tl = txdr_unsigned(60);                /* Status interval hint. */
6948         lyp->lay_layoutlen = NFSX_V4FLEXLAYOUT(mirrorcnt);
6949         return (lyp);
6950 }
6951
6952 /*
6953  * Parse and process Flex File errors returned via LayoutReturn.
6954  */
6955 static void
6956 nfsrv_flexlayouterr(struct nfsrv_descript *nd, uint32_t *layp, int maxcnt,
6957     NFSPROC_T *p)
6958 {
6959         uint32_t *tl;
6960         int cnt, errcnt, i, j, opnum, stat;
6961         char devid[NFSX_V4DEVICEID];
6962
6963         tl = layp;
6964         cnt = fxdr_unsigned(int, *tl++);
6965         NFSD_DEBUG(4, "flexlayouterr cnt=%d\n", cnt);
6966         for (i = 0; i < cnt; i++) {
6967                 /* Skip offset, length and stateid for now. */
6968                 tl += (4 + NFSX_STATEID / NFSX_UNSIGNED);
6969                 errcnt = fxdr_unsigned(int, *tl++);
6970                 NFSD_DEBUG(4, "flexlayouterr errcnt=%d\n", errcnt);
6971                 for (j = 0; j < errcnt; j++) {
6972                         NFSBCOPY(tl, devid, NFSX_V4DEVICEID);
6973                         tl += (NFSX_V4DEVICEID / NFSX_UNSIGNED);
6974                         stat = fxdr_unsigned(int, *tl++);
6975                         opnum = fxdr_unsigned(int, *tl++);
6976                         NFSD_DEBUG(4, "flexlayouterr op=%d stat=%d\n", opnum,
6977                             stat);
6978                         /*
6979                          * Except for NFSERR_ACCES and NFSERR_STALE errors,
6980                          * disable the mirror.
6981                          */
6982                         if (stat != NFSERR_ACCES && stat != NFSERR_STALE)
6983                                 nfsrv_delds(devid, p);
6984                 }
6985         }
6986 }
6987
6988 /*
6989  * This function removes all flex file layouts which has a mirror with
6990  * a device id that matches the argument.
6991  * Called when the DS represented by the device id has failed.
6992  */
6993 void
6994 nfsrv_flexmirrordel(char *devid, NFSPROC_T *p)
6995 {
6996         uint32_t *tl;
6997         struct nfslayout *lyp, *nlyp;
6998         struct nfslayouthash *lhyp;
6999         struct nfslayouthead loclyp;
7000         int i, j;
7001
7002         NFSD_DEBUG(4, "flexmirrordel\n");
7003         /* Move all layouts found onto a local list. */
7004         TAILQ_INIT(&loclyp);
7005         for (i = 0; i < nfsrv_layouthashsize; i++) {
7006                 lhyp = &nfslayouthash[i];
7007                 NFSLOCKLAYOUT(lhyp);
7008                 TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
7009                         if (lyp->lay_type == NFSLAYOUT_FLEXFILE &&
7010                             lyp->lay_mirrorcnt > 1) {
7011                                 NFSD_DEBUG(4, "possible match\n");
7012                                 tl = lyp->lay_xdr;
7013                                 tl += 3;
7014                                 for (j = 0; j < lyp->lay_mirrorcnt; j++) {
7015                                         tl++;
7016                                         if (NFSBCMP(devid, tl, NFSX_V4DEVICEID)
7017                                             == 0) {
7018                                                 /* Found one. */
7019                                                 NFSD_DEBUG(4, "fnd one\n");
7020                                                 TAILQ_REMOVE(&lhyp->list, lyp,
7021                                                     lay_list);
7022                                                 TAILQ_INSERT_HEAD(&loclyp, lyp,
7023                                                     lay_list);
7024                                                 break;
7025                                         }
7026                                         tl += (NFSX_V4DEVICEID / NFSX_UNSIGNED +
7027                                             NFSM_RNDUP(NFSX_V4PNFSFH) /
7028                                             NFSX_UNSIGNED + 11 * NFSX_UNSIGNED);
7029                                 }
7030                         }
7031                 }
7032                 NFSUNLOCKLAYOUT(lhyp);
7033         }
7034
7035         /* Now, try to do a Layout recall for each one found. */
7036         TAILQ_FOREACH_SAFE(lyp, &loclyp, lay_list, nlyp) {
7037                 NFSD_DEBUG(4, "do layout recall\n");
7038                 /*
7039                  * The layout stateid.seqid needs to be incremented
7040                  * before doing a LAYOUT_RECALL callback.
7041                  */
7042                 if (++lyp->lay_stateid.seqid == 0)
7043                         lyp->lay_stateid.seqid = 1;
7044                 nfsrv_recalllayout(lyp->lay_clientid, &lyp->lay_stateid,
7045                     &lyp->lay_fh, lyp, 1, lyp->lay_type, p);
7046                 nfsrv_freelayout(&loclyp, lyp);
7047         }
7048 }
7049
7050 /*
7051  * Do a recall callback to the client for this layout.
7052  */
7053 static int
7054 nfsrv_recalllayout(nfsquad_t clid, nfsv4stateid_t *stateidp, fhandle_t *fhp,
7055     struct nfslayout *lyp, int changed, int laytype, NFSPROC_T *p)
7056 {
7057         struct nfsclient *clp;
7058         int error;
7059
7060         NFSD_DEBUG(4, "nfsrv_recalllayout\n");
7061         error = nfsrv_getclient(clid, 0, &clp, NULL, (nfsquad_t)((u_quad_t)0),
7062             0, NULL, p);
7063         NFSD_DEBUG(4, "aft nfsrv_getclient=%d\n", error);
7064         if (error != 0) {
7065                 printf("nfsrv_recalllayout: getclient err=%d\n", error);
7066                 return (error);
7067         }
7068         if ((clp->lc_flags & LCL_NFSV41) != 0) {
7069                 error = nfsrv_docallback(clp, NFSV4OP_CBLAYOUTRECALL,
7070                     stateidp, changed, fhp, NULL, NULL, laytype, p);
7071                 /* If lyp != NULL, handle an error return here. */
7072                 if (error != 0 && lyp != NULL) {
7073                         NFSDRECALLLOCK();
7074                         /*
7075                          * Mark it returned, since no layout recall
7076                          * has been done.
7077                          * All errors seem to be non-recoverable, although
7078                          * NFSERR_NOMATCHLAYOUT is a normal event.
7079                          */
7080                         if ((lyp->lay_flags & NFSLAY_RECALL) != 0) {
7081                                 lyp->lay_flags |= NFSLAY_RETURNED;
7082                                 wakeup(lyp);
7083                         }
7084                         NFSDRECALLUNLOCK();
7085                         if (error != NFSERR_NOMATCHLAYOUT)
7086                                 printf("nfsrv_recalllayout: err=%d\n", error);
7087                 }
7088         } else
7089                 printf("nfsrv_recalllayout: clp not NFSv4.1\n");
7090         return (error);
7091 }
7092
7093 /*
7094  * Find a layout to recall when we exceed our high water mark.
7095  */
7096 void
7097 nfsrv_recalloldlayout(NFSPROC_T *p)
7098 {
7099         struct nfslayouthash *lhyp;
7100         struct nfslayout *lyp;
7101         nfsquad_t clientid;
7102         nfsv4stateid_t stateid;
7103         fhandle_t fh;
7104         int error, laytype, ret;
7105
7106         lhyp = &nfslayouthash[arc4random() % nfsrv_layouthashsize];
7107         NFSLOCKLAYOUT(lhyp);
7108         TAILQ_FOREACH_REVERSE(lyp, &lhyp->list, nfslayouthead, lay_list) {
7109                 if ((lyp->lay_flags & NFSLAY_CALLB) == 0) {
7110                         lyp->lay_flags |= NFSLAY_CALLB;
7111                         /*
7112                          * The layout stateid.seqid needs to be incremented
7113                          * before doing a LAYOUT_RECALL callback.
7114                          */
7115                         if (++lyp->lay_stateid.seqid == 0)
7116                                 lyp->lay_stateid.seqid = 1;
7117                         clientid = lyp->lay_clientid;
7118                         stateid = lyp->lay_stateid;
7119                         NFSBCOPY(&lyp->lay_fh, &fh, sizeof(fh));
7120                         laytype = lyp->lay_type;
7121                         break;
7122                 }
7123         }
7124         NFSUNLOCKLAYOUT(lhyp);
7125         if (lyp != NULL) {
7126                 error = nfsrv_recalllayout(clientid, &stateid, &fh, NULL, 0,
7127                     laytype, p);
7128                 if (error != 0 && error != NFSERR_NOMATCHLAYOUT)
7129                         NFSD_DEBUG(4, "recallold=%d\n", error);
7130                 if (error != 0) {
7131                         NFSLOCKLAYOUT(lhyp);
7132                         /*
7133                          * Since the hash list was unlocked, we need to
7134                          * find it again.
7135                          */
7136                         ret = nfsrv_findlayout(&clientid, &fh, laytype, p,
7137                             &lyp);
7138                         if (ret == 0 &&
7139                             (lyp->lay_flags & NFSLAY_CALLB) != 0 &&
7140                             lyp->lay_stateid.other[0] == stateid.other[0] &&
7141                             lyp->lay_stateid.other[1] == stateid.other[1] &&
7142                             lyp->lay_stateid.other[2] == stateid.other[2]) {
7143                                 /*
7144                                  * The client no longer knows this layout, so
7145                                  * it can be free'd now.
7146                                  */
7147                                 if (error == NFSERR_NOMATCHLAYOUT)
7148                                         nfsrv_freelayout(&lhyp->list, lyp);
7149                                 else {
7150                                         /*
7151                                          * Leave it to be tried later by
7152                                          * clearing NFSLAY_CALLB and moving
7153                                          * it to the head of the list, so it
7154                                          * won't be tried again for a while.
7155                                          */
7156                                         lyp->lay_flags &= ~NFSLAY_CALLB;
7157                                         TAILQ_REMOVE(&lhyp->list, lyp,
7158                                             lay_list);
7159                                         TAILQ_INSERT_HEAD(&lhyp->list, lyp,
7160                                             lay_list);
7161                                 }
7162                         }
7163                         NFSUNLOCKLAYOUT(lhyp);
7164                 }
7165         }
7166 }
7167
7168 /*
7169  * Try and return layout(s).
7170  */
7171 int
7172 nfsrv_layoutreturn(struct nfsrv_descript *nd, vnode_t vp,
7173     int layouttype, int iomode, uint64_t offset, uint64_t len, int reclaim,
7174     int kind, nfsv4stateid_t *stateidp, int maxcnt, uint32_t *layp, int *fndp,
7175     struct ucred *cred, NFSPROC_T *p)
7176 {
7177         struct nfsvattr na;
7178         struct nfslayouthash *lhyp;
7179         struct nfslayout *lyp;
7180         fhandle_t fh;
7181         int error = 0;
7182
7183         *fndp = 0;
7184         if (kind == NFSV4LAYOUTRET_FILE) {
7185                 error = nfsvno_getfh(vp, &fh, p);
7186                 if (error == 0) {
7187                         error = nfsrv_updatemdsattr(vp, &na, p);
7188                         if (error != 0)
7189                                 printf("nfsrv_layoutreturn: updatemdsattr"
7190                                     " failed=%d\n", error);
7191                 }
7192                 if (error == 0) {
7193                         if (reclaim == newnfs_true) {
7194                                 error = nfsrv_checkgrace(NULL, NULL,
7195                                     NFSLCK_RECLAIM);
7196                                 if (error != NFSERR_NOGRACE)
7197                                         error = 0;
7198                                 return (error);
7199                         }
7200                         lhyp = NFSLAYOUTHASH(&fh);
7201                         NFSDRECALLLOCK();
7202                         NFSLOCKLAYOUT(lhyp);
7203                         error = nfsrv_findlayout(&nd->nd_clientid, &fh,
7204                             layouttype, p, &lyp);
7205                         NFSD_DEBUG(4, "layoutret findlay=%d\n", error);
7206                         if (error == 0 &&
7207                             stateidp->other[0] == lyp->lay_stateid.other[0] &&
7208                             stateidp->other[1] == lyp->lay_stateid.other[1] &&
7209                             stateidp->other[2] == lyp->lay_stateid.other[2]) {
7210                                 NFSD_DEBUG(4, "nfsrv_layoutreturn: stateid %d"
7211                                     " %x %x %x laystateid %d %x %x %x"
7212                                     " off=%ju len=%ju flgs=0x%x\n",
7213                                     stateidp->seqid, stateidp->other[0],
7214                                     stateidp->other[1], stateidp->other[2],
7215                                     lyp->lay_stateid.seqid,
7216                                     lyp->lay_stateid.other[0],
7217                                     lyp->lay_stateid.other[1],
7218                                     lyp->lay_stateid.other[2],
7219                                     (uintmax_t)offset, (uintmax_t)len,
7220                                     lyp->lay_flags);
7221                                 if (++lyp->lay_stateid.seqid == 0)
7222                                         lyp->lay_stateid.seqid = 1;
7223                                 stateidp->seqid = lyp->lay_stateid.seqid;
7224                                 if (offset == 0 && len == UINT64_MAX) {
7225                                         if ((iomode & NFSLAYOUTIOMODE_READ) !=
7226                                             0)
7227                                                 lyp->lay_flags &= ~NFSLAY_READ;
7228                                         if ((iomode & NFSLAYOUTIOMODE_RW) != 0)
7229                                                 lyp->lay_flags &= ~NFSLAY_RW;
7230                                         if ((lyp->lay_flags & (NFSLAY_READ |
7231                                             NFSLAY_RW)) == 0)
7232                                                 nfsrv_freelayout(&lhyp->list,
7233                                                     lyp);
7234                                         else
7235                                                 *fndp = 1;
7236                                 } else
7237                                         *fndp = 1;
7238                         }
7239                         NFSUNLOCKLAYOUT(lhyp);
7240                         /* Search the nfsrv_recalllist for a match. */
7241                         TAILQ_FOREACH(lyp, &nfsrv_recalllisthead, lay_list) {
7242                                 if (NFSBCMP(&lyp->lay_fh, &fh,
7243                                     sizeof(fh)) == 0 &&
7244                                     lyp->lay_clientid.qval ==
7245                                     nd->nd_clientid.qval &&
7246                                     stateidp->other[0] ==
7247                                     lyp->lay_stateid.other[0] &&
7248                                     stateidp->other[1] ==
7249                                     lyp->lay_stateid.other[1] &&
7250                                     stateidp->other[2] ==
7251                                     lyp->lay_stateid.other[2]) {
7252                                         lyp->lay_flags |= NFSLAY_RETURNED;
7253                                         wakeup(lyp);
7254                                         error = 0;
7255                                 }
7256                         }
7257                         NFSDRECALLUNLOCK();
7258                 }
7259                 if (layouttype == NFSLAYOUT_FLEXFILE)
7260                         nfsrv_flexlayouterr(nd, layp, maxcnt, p);
7261         } else if (kind == NFSV4LAYOUTRET_FSID)
7262                 nfsrv_freelayouts(&nd->nd_clientid,
7263                     &vp->v_mount->mnt_stat.f_fsid, layouttype, iomode);
7264         else if (kind == NFSV4LAYOUTRET_ALL)
7265                 nfsrv_freelayouts(&nd->nd_clientid, NULL, layouttype, iomode);
7266         else
7267                 error = NFSERR_INVAL;
7268         if (error == -1)
7269                 error = 0;
7270         return (error);
7271 }
7272
7273 /*
7274  * Look for an existing layout.
7275  */
7276 static int
7277 nfsrv_findlayout(nfsquad_t *clientidp, fhandle_t *fhp, int laytype,
7278     NFSPROC_T *p, struct nfslayout **lypp)
7279 {
7280         struct nfslayouthash *lhyp;
7281         struct nfslayout *lyp;
7282         int ret;
7283
7284         *lypp = NULL;
7285         ret = 0;
7286         lhyp = NFSLAYOUTHASH(fhp);
7287         TAILQ_FOREACH(lyp, &lhyp->list, lay_list) {
7288                 if (NFSBCMP(&lyp->lay_fh, fhp, sizeof(*fhp)) == 0 &&
7289                     lyp->lay_clientid.qval == clientidp->qval &&
7290                     lyp->lay_type == laytype)
7291                         break;
7292         }
7293         if (lyp != NULL)
7294                 *lypp = lyp;
7295         else
7296                 ret = -1;
7297         return (ret);
7298 }
7299
7300 /*
7301  * Add the new layout, as required.
7302  */
7303 static int
7304 nfsrv_addlayout(struct nfsrv_descript *nd, struct nfslayout **lypp,
7305     nfsv4stateid_t *stateidp, char *layp, int *layoutlenp, NFSPROC_T *p)
7306 {
7307         struct nfsclient *clp;
7308         struct nfslayouthash *lhyp;
7309         struct nfslayout *lyp, *nlyp;
7310         fhandle_t *fhp;
7311         int error;
7312
7313         KASSERT((nd->nd_flag & ND_IMPLIEDCLID) != 0,
7314             ("nfsrv_layoutget: no nd_clientid\n"));
7315         lyp = *lypp;
7316         fhp = &lyp->lay_fh;
7317         NFSLOCKSTATE();
7318         error = nfsrv_getclient((nfsquad_t)((u_quad_t)0), CLOPS_RENEW, &clp,
7319             NULL, (nfsquad_t)((u_quad_t)0), 0, nd, p);
7320         if (error != 0) {
7321                 NFSUNLOCKSTATE();
7322                 return (error);
7323         }
7324         lyp->lay_stateid.seqid = stateidp->seqid = 1;
7325         lyp->lay_stateid.other[0] = stateidp->other[0] =
7326             clp->lc_clientid.lval[0];
7327         lyp->lay_stateid.other[1] = stateidp->other[1] =
7328             clp->lc_clientid.lval[1];
7329         lyp->lay_stateid.other[2] = stateidp->other[2] =
7330             nfsrv_nextstateindex(clp);
7331         NFSUNLOCKSTATE();
7332
7333         lhyp = NFSLAYOUTHASH(fhp);
7334         NFSLOCKLAYOUT(lhyp);
7335         TAILQ_FOREACH(nlyp, &lhyp->list, lay_list) {
7336                 if (NFSBCMP(&nlyp->lay_fh, fhp, sizeof(*fhp)) == 0 &&
7337                     nlyp->lay_clientid.qval == nd->nd_clientid.qval)
7338                         break;
7339         }
7340         if (nlyp != NULL) {
7341                 /* A layout already exists, so use it. */
7342                 nlyp->lay_flags |= (lyp->lay_flags & (NFSLAY_READ | NFSLAY_RW));
7343                 NFSBCOPY(nlyp->lay_xdr, layp, nlyp->lay_layoutlen);
7344                 *layoutlenp = nlyp->lay_layoutlen;
7345                 if (++nlyp->lay_stateid.seqid == 0)
7346                         nlyp->lay_stateid.seqid = 1;
7347                 stateidp->seqid = nlyp->lay_stateid.seqid;
7348                 stateidp->other[0] = nlyp->lay_stateid.other[0];
7349                 stateidp->other[1] = nlyp->lay_stateid.other[1];
7350                 stateidp->other[2] = nlyp->lay_stateid.other[2];
7351                 NFSUNLOCKLAYOUT(lhyp);
7352                 return (0);
7353         }
7354
7355         /* Insert the new layout in the lists. */
7356         *lypp = NULL;
7357         atomic_add_int(&nfsrv_layoutcnt, 1);
7358         NFSBCOPY(lyp->lay_xdr, layp, lyp->lay_layoutlen);
7359         *layoutlenp = lyp->lay_layoutlen;
7360         TAILQ_INSERT_HEAD(&lhyp->list, lyp, lay_list);
7361         NFSUNLOCKLAYOUT(lhyp);
7362         return (0);
7363 }
7364
7365 /*
7366  * Get the devinfo for a deviceid.
7367  */
7368 int
7369 nfsrv_getdevinfo(char *devid, int layouttype, uint32_t *maxcnt,
7370     uint32_t *notify, int *devaddrlen, char **devaddr)
7371 {
7372         struct nfsdevice *ds;
7373
7374         if ((layouttype != NFSLAYOUT_NFSV4_1_FILES && layouttype !=
7375              NFSLAYOUT_FLEXFILE) ||
7376             (nfsrv_maxpnfsmirror > 1 && layouttype == NFSLAYOUT_NFSV4_1_FILES))
7377                 return (NFSERR_UNKNLAYOUTTYPE);
7378
7379         /*
7380          * Now, search for the device id.  Note that the structures won't go
7381          * away, but the order changes in the list.  As such, the lock only
7382          * needs to be held during the search through the list.
7383          */
7384         NFSDDSLOCK();
7385         TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
7386                 if (NFSBCMP(devid, ds->nfsdev_deviceid, NFSX_V4DEVICEID) == 0 &&
7387                     ds->nfsdev_nmp != NULL)
7388                         break;
7389         }
7390         NFSDDSUNLOCK();
7391         if (ds == NULL)
7392                 return (NFSERR_NOENT);
7393
7394         /* If the correct nfsdev_XXXXaddrlen is > 0, we have the device info. */
7395         *devaddrlen = 0;
7396         if (layouttype == NFSLAYOUT_NFSV4_1_FILES) {
7397                 *devaddrlen = ds->nfsdev_fileaddrlen;
7398                 *devaddr = ds->nfsdev_fileaddr;
7399         } else if (layouttype == NFSLAYOUT_FLEXFILE) {
7400                 *devaddrlen = ds->nfsdev_flexaddrlen;
7401                 *devaddr = ds->nfsdev_flexaddr;
7402         }
7403         if (*devaddrlen == 0)
7404                 return (NFSERR_UNKNLAYOUTTYPE);
7405
7406         /*
7407          * The XDR overhead is 3 unsigned values: layout_type,
7408          * length_of_address and notify bitmap.
7409          * If the notify array is changed to not all zeros, the
7410          * count of unsigned values must be increased.
7411          */
7412         if (*maxcnt > 0 && *maxcnt < NFSM_RNDUP(*devaddrlen) +
7413             3 * NFSX_UNSIGNED) {
7414                 *maxcnt = NFSM_RNDUP(*devaddrlen) + 3 * NFSX_UNSIGNED;
7415                 return (NFSERR_TOOSMALL);
7416         }
7417         return (0);
7418 }
7419
7420 /*
7421  * Free a list of layout state structures.
7422  */
7423 static void
7424 nfsrv_freelayoutlist(nfsquad_t clientid)
7425 {
7426         struct nfslayouthash *lhyp;
7427         struct nfslayout *lyp, *nlyp;
7428         int i;
7429
7430         for (i = 0; i < nfsrv_layouthashsize; i++) {
7431                 lhyp = &nfslayouthash[i];
7432                 NFSLOCKLAYOUT(lhyp);
7433                 TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
7434                         if (lyp->lay_clientid.qval == clientid.qval)
7435                                 nfsrv_freelayout(&lhyp->list, lyp);
7436                 }
7437                 NFSUNLOCKLAYOUT(lhyp);
7438         }
7439 }
7440
7441 /*
7442  * Free up a layout.
7443  */
7444 static void
7445 nfsrv_freelayout(struct nfslayouthead *lhp, struct nfslayout *lyp)
7446 {
7447
7448         NFSD_DEBUG(4, "Freelayout=%p\n", lyp);
7449         atomic_add_int(&nfsrv_layoutcnt, -1);
7450         TAILQ_REMOVE(lhp, lyp, lay_list);
7451         free(lyp, M_NFSDSTATE);
7452 }
7453
7454 /*
7455  * Free up a device id.
7456  */
7457 void
7458 nfsrv_freeonedevid(struct nfsdevice *ds)
7459 {
7460         int i;
7461
7462         atomic_add_int(&nfsrv_devidcnt, -1);
7463         vrele(ds->nfsdev_dvp);
7464         for (i = 0; i < nfsrv_dsdirsize; i++)
7465                 if (ds->nfsdev_dsdir[i] != NULL)
7466                         vrele(ds->nfsdev_dsdir[i]);
7467         free(ds->nfsdev_fileaddr, M_NFSDSTATE);
7468         free(ds->nfsdev_flexaddr, M_NFSDSTATE);
7469         free(ds->nfsdev_host, M_NFSDSTATE);
7470         free(ds, M_NFSDSTATE);
7471 }
7472
7473 /*
7474  * Free up a device id and its mirrors.
7475  */
7476 static void
7477 nfsrv_freedevid(struct nfsdevice *ds)
7478 {
7479
7480         TAILQ_REMOVE(&nfsrv_devidhead, ds, nfsdev_list);
7481         nfsrv_freeonedevid(ds);
7482 }
7483
7484 /*
7485  * Free all layouts and device ids.
7486  * Done when the nfsd threads are shut down since there may be a new
7487  * modified device id list created when the nfsd is restarted.
7488  */
7489 void
7490 nfsrv_freealllayoutsanddevids(void)
7491 {
7492         struct nfsdontlist *mrp, *nmrp;
7493         struct nfslayout *lyp, *nlyp;
7494
7495         /* Get rid of the deviceid structures. */
7496         nfsrv_freealldevids();
7497         TAILQ_INIT(&nfsrv_devidhead);
7498         nfsrv_devidcnt = 0;
7499
7500         /* Get rid of all layouts. */
7501         nfsrv_freealllayouts();
7502
7503         /* Get rid of any nfsdontlist entries. */
7504         LIST_FOREACH_SAFE(mrp, &nfsrv_dontlisthead, nfsmr_list, nmrp)
7505                 free(mrp, M_NFSDSTATE);
7506         LIST_INIT(&nfsrv_dontlisthead);
7507         nfsrv_dontlistlen = 0;
7508
7509         /* Free layouts in the recall list. */
7510         TAILQ_FOREACH_SAFE(lyp, &nfsrv_recalllisthead, lay_list, nlyp)
7511                 nfsrv_freelayout(&nfsrv_recalllisthead, lyp);
7512         TAILQ_INIT(&nfsrv_recalllisthead);
7513 }
7514
7515 /*
7516  * Free layouts that match the arguments.
7517  */
7518 static void
7519 nfsrv_freelayouts(nfsquad_t *clid, fsid_t *fs, int laytype, int iomode)
7520 {
7521         struct nfslayouthash *lhyp;
7522         struct nfslayout *lyp, *nlyp;
7523         int i;
7524
7525         for (i = 0; i < nfsrv_layouthashsize; i++) {
7526                 lhyp = &nfslayouthash[i];
7527                 NFSLOCKLAYOUT(lhyp);
7528                 TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
7529                         if (clid->qval != lyp->lay_clientid.qval)
7530                                 continue;
7531                         if (fs != NULL && fsidcmp(fs, &lyp->lay_fsid) != 0)
7532                                 continue;
7533                         if (laytype != lyp->lay_type)
7534                                 continue;
7535                         if ((iomode & NFSLAYOUTIOMODE_READ) != 0)
7536                                 lyp->lay_flags &= ~NFSLAY_READ;
7537                         if ((iomode & NFSLAYOUTIOMODE_RW) != 0)
7538                                 lyp->lay_flags &= ~NFSLAY_RW;
7539                         if ((lyp->lay_flags & (NFSLAY_READ | NFSLAY_RW)) == 0)
7540                                 nfsrv_freelayout(&lhyp->list, lyp);
7541                 }
7542                 NFSUNLOCKLAYOUT(lhyp);
7543         }
7544 }
7545
7546 /*
7547  * Free all layouts for the argument file.
7548  */
7549 void
7550 nfsrv_freefilelayouts(fhandle_t *fhp)
7551 {
7552         struct nfslayouthash *lhyp;
7553         struct nfslayout *lyp, *nlyp;
7554
7555         lhyp = NFSLAYOUTHASH(fhp);
7556         NFSLOCKLAYOUT(lhyp);
7557         TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
7558                 if (NFSBCMP(&lyp->lay_fh, fhp, sizeof(*fhp)) == 0)
7559                         nfsrv_freelayout(&lhyp->list, lyp);
7560         }
7561         NFSUNLOCKLAYOUT(lhyp);
7562 }
7563
7564 /*
7565  * Free all layouts.
7566  */
7567 static void
7568 nfsrv_freealllayouts(void)
7569 {
7570         struct nfslayouthash *lhyp;
7571         struct nfslayout *lyp, *nlyp;
7572         int i;
7573
7574         for (i = 0; i < nfsrv_layouthashsize; i++) {
7575                 lhyp = &nfslayouthash[i];
7576                 NFSLOCKLAYOUT(lhyp);
7577                 TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp)
7578                         nfsrv_freelayout(&lhyp->list, lyp);
7579                 NFSUNLOCKLAYOUT(lhyp);
7580         }
7581 }
7582
7583 /*
7584  * Look up the mount path for the DS server.
7585  */
7586 static int
7587 nfsrv_setdsserver(char *dspathp, char *mdspathp, NFSPROC_T *p,
7588     struct nfsdevice **dsp)
7589 {
7590         struct nameidata nd;
7591         struct nfsdevice *ds;
7592         struct mount *mp;
7593         int error, i;
7594         char *dsdirpath;
7595         size_t dsdirsize;
7596
7597         NFSD_DEBUG(4, "setdssrv path=%s\n", dspathp);
7598         *dsp = NULL;
7599         NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF, UIO_SYSSPACE,
7600             dspathp, p);
7601         error = namei(&nd);
7602         NFSD_DEBUG(4, "lookup=%d\n", error);
7603         if (error != 0)
7604                 return (error);
7605         if (nd.ni_vp->v_type != VDIR) {
7606                 vput(nd.ni_vp);
7607                 NFSD_DEBUG(4, "dspath not dir\n");
7608                 return (ENOTDIR);
7609         }
7610         if (strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name, "nfs") != 0) {
7611                 vput(nd.ni_vp);
7612                 NFSD_DEBUG(4, "dspath not an NFS mount\n");
7613                 return (ENXIO);
7614         }
7615
7616         /*
7617          * Allocate a DS server structure with the NFS mounted directory
7618          * vnode reference counted, so that a non-forced dismount will
7619          * fail with EBUSY.
7620          * This structure is always linked into the list, even if an error
7621          * is being returned.  The caller will free the entire list upon
7622          * an error return.
7623          */
7624         *dsp = ds = malloc(sizeof(*ds) + nfsrv_dsdirsize * sizeof(vnode_t),
7625             M_NFSDSTATE, M_WAITOK | M_ZERO);
7626         ds->nfsdev_dvp = nd.ni_vp;
7627         ds->nfsdev_nmp = VFSTONFS(nd.ni_vp->v_mount);
7628         NFSVOPUNLOCK(nd.ni_vp, 0);
7629
7630         dsdirsize = strlen(dspathp) + 16;
7631         dsdirpath = malloc(dsdirsize, M_TEMP, M_WAITOK);
7632         /* Now, create the DS directory structures. */
7633         for (i = 0; i < nfsrv_dsdirsize; i++) {
7634                 snprintf(dsdirpath, dsdirsize, "%s/ds%d", dspathp, i);
7635                 NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
7636                     UIO_SYSSPACE, dsdirpath, p);
7637                 error = namei(&nd);
7638                 NFSD_DEBUG(4, "dsdirpath=%s lookup=%d\n", dsdirpath, error);
7639                 if (error != 0)
7640                         break;
7641                 if (nd.ni_vp->v_type != VDIR) {
7642                         vput(nd.ni_vp);
7643                         error = ENOTDIR;
7644                         NFSD_DEBUG(4, "dsdirpath not a VDIR\n");
7645                         break;
7646                 }
7647                 if (strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name, "nfs") != 0) {
7648                         vput(nd.ni_vp);
7649                         error = ENXIO;
7650                         NFSD_DEBUG(4, "dsdirpath not an NFS mount\n");
7651                         break;
7652                 }
7653                 ds->nfsdev_dsdir[i] = nd.ni_vp;
7654                 NFSVOPUNLOCK(nd.ni_vp, 0);
7655         }
7656         free(dsdirpath, M_TEMP);
7657
7658         if (strlen(mdspathp) > 0) {
7659                 /*
7660                  * This DS stores file for a specific MDS exported file
7661                  * system.
7662                  */
7663                 NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
7664                     UIO_SYSSPACE, mdspathp, p);
7665                 error = namei(&nd);
7666                 NFSD_DEBUG(4, "mds lookup=%d\n", error);
7667                 if (error != 0)
7668                         goto out;
7669                 if (nd.ni_vp->v_type != VDIR) {
7670                         vput(nd.ni_vp);
7671                         error = ENOTDIR;
7672                         NFSD_DEBUG(4, "mdspath not dir\n");
7673                         goto out;
7674                 }
7675                 mp = nd.ni_vp->v_mount;
7676                 if ((mp->mnt_flag & MNT_EXPORTED) == 0) {
7677                         vput(nd.ni_vp);
7678                         error = ENXIO;
7679                         NFSD_DEBUG(4, "mdspath not an exported fs\n");
7680                         goto out;
7681                 }
7682                 ds->nfsdev_mdsfsid = mp->mnt_stat.f_fsid;
7683                 ds->nfsdev_mdsisset = 1;
7684                 vput(nd.ni_vp);
7685         }
7686
7687 out:
7688         TAILQ_INSERT_TAIL(&nfsrv_devidhead, ds, nfsdev_list);
7689         atomic_add_int(&nfsrv_devidcnt, 1);
7690         return (error);
7691 }
7692
7693 /*
7694  * Look up the mount path for the DS server and delete it.
7695  */
7696 int
7697 nfsrv_deldsserver(int op, char *dspathp, NFSPROC_T *p)
7698 {
7699         struct mount *mp;
7700         struct nfsmount *nmp;
7701         struct nfsdevice *ds;
7702         int error;
7703
7704         NFSD_DEBUG(4, "deldssrv path=%s\n", dspathp);
7705         /*
7706          * Search for the path in the mount list.  Avoid looking the path
7707          * up, since this mount point may be hung, with associated locked
7708          * vnodes, etc.
7709          * Set NFSMNTP_CANCELRPCS so that any forced dismount will be blocked
7710          * until this completes.
7711          * As noted in the man page, this should be done before any forced
7712          * dismount on the mount point, but at least the handshake on
7713          * NFSMNTP_CANCELRPCS should make it safe.
7714          */
7715         error = 0;
7716         ds = NULL;
7717         nmp = NULL;
7718         mtx_lock(&mountlist_mtx);
7719         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
7720                 if (strcmp(mp->mnt_stat.f_mntonname, dspathp) == 0 &&
7721                     strcmp(mp->mnt_stat.f_fstypename, "nfs") == 0 &&
7722                     mp->mnt_data != NULL) {
7723                         nmp = VFSTONFS(mp);
7724                         NFSLOCKMNT(nmp);
7725                         if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
7726                              NFSMNTP_CANCELRPCS)) == 0) {
7727                                 nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
7728                                 NFSUNLOCKMNT(nmp);
7729                         } else {
7730                                 NFSUNLOCKMNT(nmp);
7731                                 nmp = NULL;
7732                         }
7733                         break;
7734                 }
7735         }
7736         mtx_unlock(&mountlist_mtx);
7737
7738         if (nmp != NULL) {
7739                 ds = nfsrv_deldsnmp(op, nmp, p);
7740                 NFSD_DEBUG(4, "deldsnmp=%p\n", ds);
7741                 if (ds != NULL) {
7742                         nfsrv_killrpcs(nmp);
7743                         NFSD_DEBUG(4, "aft killrpcs\n");
7744                 } else
7745                         error = ENXIO;
7746                 NFSLOCKMNT(nmp);
7747                 nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
7748                 wakeup(nmp);
7749                 NFSUNLOCKMNT(nmp);
7750         } else
7751                 error = EINVAL;
7752         return (error);
7753 }
7754
7755 /*
7756  * Search for and remove a DS entry which matches the "nmp" argument.
7757  * The nfsdevice structure pointer is returned so that the caller can
7758  * free it via nfsrv_freeonedevid().
7759  * For the forced case, do not try to do LayoutRecalls, since the server
7760  * must be shut down now anyhow.
7761  */
7762 struct nfsdevice *
7763 nfsrv_deldsnmp(int op, struct nfsmount *nmp, NFSPROC_T *p)
7764 {
7765         struct nfsdevice *fndds;
7766
7767         NFSD_DEBUG(4, "deldsdvp\n");
7768         NFSDDSLOCK();
7769         if (op == PNFSDOP_FORCEDELDS)
7770                 fndds = nfsv4_findmirror(nmp);
7771         else
7772                 fndds = nfsrv_findmirroredds(nmp);
7773         if (fndds != NULL)
7774                 nfsrv_deleteds(fndds);
7775         NFSDDSUNLOCK();
7776         if (fndds != NULL) {
7777                 if (op != PNFSDOP_FORCEDELDS)
7778                         nfsrv_flexmirrordel(fndds->nfsdev_deviceid, p);
7779                 printf("pNFS server: mirror %s failed\n", fndds->nfsdev_host);
7780         }
7781         return (fndds);
7782 }
7783
7784 /*
7785  * Similar to nfsrv_deldsnmp(), except that the DS is indicated by deviceid.
7786  * This function also calls nfsrv_killrpcs() to unblock RPCs on the mount
7787  * point.
7788  * Also, returns an error instead of the nfsdevice found.
7789  */
7790 static int
7791 nfsrv_delds(char *devid, NFSPROC_T *p)
7792 {
7793         struct nfsdevice *ds, *fndds;
7794         struct nfsmount *nmp;
7795         int fndmirror;
7796
7797         NFSD_DEBUG(4, "delds\n");
7798         /*
7799          * Search the DS server list for a match with devid.
7800          * Remove the DS entry if found and there is a mirror.
7801          */
7802         fndds = NULL;
7803         nmp = NULL;
7804         fndmirror = 0;
7805         NFSDDSLOCK();
7806         TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
7807                 if (NFSBCMP(ds->nfsdev_deviceid, devid, NFSX_V4DEVICEID) == 0 &&
7808                     ds->nfsdev_nmp != NULL) {
7809                         NFSD_DEBUG(4, "fnd main ds\n");
7810                         fndds = ds;
7811                         break;
7812                 }
7813         }
7814         if (fndds == NULL) {
7815                 NFSDDSUNLOCK();
7816                 return (ENXIO);
7817         }
7818         if (fndds->nfsdev_mdsisset == 0 && nfsrv_faildscnt > 0)
7819                 fndmirror = 1;
7820         else if (fndds->nfsdev_mdsisset != 0) {
7821                 /* For the fsid is set case, search for a mirror. */
7822                 TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
7823                         if (ds != fndds && ds->nfsdev_nmp != NULL &&
7824                             ds->nfsdev_mdsisset != 0 &&
7825                             fsidcmp(&ds->nfsdev_mdsfsid,
7826                             &fndds->nfsdev_mdsfsid) == 0) {
7827                                 fndmirror = 1;
7828                                 break;
7829                         }
7830                 }
7831         }
7832         if (fndmirror != 0) {
7833                 nmp = fndds->nfsdev_nmp;
7834                 NFSLOCKMNT(nmp);
7835                 if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
7836                      NFSMNTP_CANCELRPCS)) == 0) {
7837                         nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
7838                         NFSUNLOCKMNT(nmp);
7839                         nfsrv_deleteds(fndds);
7840                 } else {
7841                         NFSUNLOCKMNT(nmp);
7842                         nmp = NULL;
7843                 }
7844         }
7845         NFSDDSUNLOCK();
7846         if (nmp != NULL) {
7847                 nfsrv_flexmirrordel(fndds->nfsdev_deviceid, p);
7848                 printf("pNFS server: mirror %s failed\n", fndds->nfsdev_host);
7849                 nfsrv_killrpcs(nmp);
7850                 NFSLOCKMNT(nmp);
7851                 nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
7852                 wakeup(nmp);
7853                 NFSUNLOCKMNT(nmp);
7854                 return (0);
7855         }
7856         return (ENXIO);
7857 }
7858
7859 /*
7860  * Mark a DS as disabled by setting nfsdev_nmp = NULL.
7861  */
7862 static void
7863 nfsrv_deleteds(struct nfsdevice *fndds)
7864 {
7865
7866         NFSD_DEBUG(4, "deleteds: deleting a mirror\n");
7867         fndds->nfsdev_nmp = NULL;
7868         if (fndds->nfsdev_mdsisset == 0)
7869                 nfsrv_faildscnt--;
7870 }
7871
7872 /*
7873  * Fill in the addr structures for the File and Flex File layouts.
7874  */
7875 static void
7876 nfsrv_allocdevid(struct nfsdevice *ds, char *addr, char *dnshost)
7877 {
7878         uint32_t *tl;
7879         char *netprot;
7880         int addrlen;
7881         static uint64_t new_devid = 0;
7882
7883         if (strchr(addr, ':') != NULL)
7884                 netprot = "tcp6";
7885         else
7886                 netprot = "tcp";
7887
7888         /* Fill in the device id. */
7889         NFSBCOPY(&nfsdev_time, ds->nfsdev_deviceid, sizeof(nfsdev_time));
7890         new_devid++;
7891         NFSBCOPY(&new_devid, &ds->nfsdev_deviceid[sizeof(nfsdev_time)],
7892             sizeof(new_devid));
7893
7894         /*
7895          * Fill in the file addr (actually the nfsv4_file_layout_ds_addr4
7896          * as defined in RFC5661) in XDR.
7897          */
7898         addrlen = NFSM_RNDUP(strlen(addr)) + NFSM_RNDUP(strlen(netprot)) +
7899             6 * NFSX_UNSIGNED;
7900         NFSD_DEBUG(4, "hn=%s addr=%s netprot=%s\n", dnshost, addr, netprot);
7901         ds->nfsdev_fileaddrlen = addrlen;
7902         tl = malloc(addrlen, M_NFSDSTATE, M_WAITOK | M_ZERO);
7903         ds->nfsdev_fileaddr = (char *)tl;
7904         *tl++ = txdr_unsigned(1);               /* One stripe with index 0. */
7905         *tl++ = 0;
7906         *tl++ = txdr_unsigned(1);               /* One multipath list */
7907         *tl++ = txdr_unsigned(1);               /* with one entry in it. */
7908         /* The netaddr for this one entry. */
7909         *tl++ = txdr_unsigned(strlen(netprot));
7910         NFSBCOPY(netprot, tl, strlen(netprot));
7911         tl += (NFSM_RNDUP(strlen(netprot)) / NFSX_UNSIGNED);
7912         *tl++ = txdr_unsigned(strlen(addr));
7913         NFSBCOPY(addr, tl, strlen(addr));
7914
7915         /*
7916          * Fill in the flex file addr (actually the ff_device_addr4
7917          * as defined for Flexible File Layout) in XDR.
7918          */
7919         addrlen = NFSM_RNDUP(strlen(addr)) + NFSM_RNDUP(strlen(netprot)) +
7920             9 * NFSX_UNSIGNED;
7921         ds->nfsdev_flexaddrlen = addrlen;
7922         tl = malloc(addrlen, M_NFSDSTATE, M_WAITOK | M_ZERO);
7923         ds->nfsdev_flexaddr = (char *)tl;
7924         *tl++ = txdr_unsigned(1);               /* One multipath entry. */
7925         /* The netaddr for this one entry. */
7926         *tl++ = txdr_unsigned(strlen(netprot));
7927         NFSBCOPY(netprot, tl, strlen(netprot));
7928         tl += (NFSM_RNDUP(strlen(netprot)) / NFSX_UNSIGNED);
7929         *tl++ = txdr_unsigned(strlen(addr));
7930         NFSBCOPY(addr, tl, strlen(addr));
7931         tl += (NFSM_RNDUP(strlen(addr)) / NFSX_UNSIGNED);
7932         *tl++ = txdr_unsigned(1);               /* One NFS Version. */
7933         *tl++ = txdr_unsigned(NFS_VER4);        /* NFSv4. */
7934         *tl++ = txdr_unsigned(NFSV41_MINORVERSION); /* Minor version 1. */
7935         *tl++ = txdr_unsigned(NFS_SRVMAXIO);    /* DS max rsize. */
7936         *tl++ = txdr_unsigned(NFS_SRVMAXIO);    /* DS max wsize. */
7937         *tl = newnfs_true;                      /* Tightly coupled. */
7938
7939         ds->nfsdev_hostnamelen = strlen(dnshost);
7940         ds->nfsdev_host = malloc(ds->nfsdev_hostnamelen + 1, M_NFSDSTATE,
7941             M_WAITOK);
7942         NFSBCOPY(dnshost, ds->nfsdev_host, ds->nfsdev_hostnamelen + 1);
7943 }
7944
7945
7946 /*
7947  * Create the device id list.
7948  * Return 0 if the nfsd threads are to run and ENXIO if the "-p" argument
7949  * is misconfigured.
7950  */
7951 int
7952 nfsrv_createdevids(struct nfsd_nfsd_args *args, NFSPROC_T *p)
7953 {
7954         struct nfsdevice *ds;
7955         char *addrp, *dnshostp, *dspathp, *mdspathp;
7956         int error, i;
7957
7958         addrp = args->addr;
7959         dnshostp = args->dnshost;
7960         dspathp = args->dspath;
7961         mdspathp = args->mdspath;
7962         nfsrv_maxpnfsmirror = args->mirrorcnt;
7963         if (addrp == NULL || dnshostp == NULL || dspathp == NULL ||
7964             mdspathp == NULL)
7965                 return (0);
7966
7967         /*
7968          * Loop around for each nul-terminated string in args->addr,
7969          * args->dnshost, args->dnspath and args->mdspath.
7970          */
7971         while (addrp < (args->addr + args->addrlen) &&
7972             dnshostp < (args->dnshost + args->dnshostlen) &&
7973             dspathp < (args->dspath + args->dspathlen) &&
7974             mdspathp < (args->mdspath + args->mdspathlen)) {
7975                 error = nfsrv_setdsserver(dspathp, mdspathp, p, &ds);
7976                 if (error != 0) {
7977                         /* Free all DS servers. */
7978                         nfsrv_freealldevids();
7979                         nfsrv_devidcnt = 0;
7980                         return (ENXIO);
7981                 }
7982                 nfsrv_allocdevid(ds, addrp, dnshostp);
7983                 addrp += (strlen(addrp) + 1);
7984                 dnshostp += (strlen(dnshostp) + 1);
7985                 dspathp += (strlen(dspathp) + 1);
7986                 mdspathp += (strlen(mdspathp) + 1);
7987         }
7988         if (nfsrv_devidcnt < nfsrv_maxpnfsmirror) {
7989                 /* Free all DS servers. */
7990                 nfsrv_freealldevids();
7991                 nfsrv_devidcnt = 0;
7992                 nfsrv_maxpnfsmirror = 1;
7993                 return (ENXIO);
7994         }
7995         /* We can fail at most one less DS than the mirror level. */
7996         nfsrv_faildscnt = nfsrv_maxpnfsmirror - 1;
7997
7998         /*
7999          * Allocate the nfslayout hash table now, since this is a pNFS server.
8000          * Make it 1% of the high water mark and at least 100.
8001          */
8002         if (nfslayouthash == NULL) {
8003                 nfsrv_layouthashsize = nfsrv_layouthighwater / 100;
8004                 if (nfsrv_layouthashsize < 100)
8005                         nfsrv_layouthashsize = 100;
8006                 nfslayouthash = mallocarray(nfsrv_layouthashsize,
8007                     sizeof(struct nfslayouthash), M_NFSDSESSION, M_WAITOK |
8008                     M_ZERO);
8009                 for (i = 0; i < nfsrv_layouthashsize; i++) {
8010                         mtx_init(&nfslayouthash[i].mtx, "nfslm", NULL, MTX_DEF);
8011                         TAILQ_INIT(&nfslayouthash[i].list);
8012                 }
8013         }
8014         return (0);
8015 }
8016
8017 /*
8018  * Free all device ids.
8019  */
8020 static void
8021 nfsrv_freealldevids(void)
8022 {
8023         struct nfsdevice *ds, *nds;
8024
8025         TAILQ_FOREACH_SAFE(ds, &nfsrv_devidhead, nfsdev_list, nds)
8026                 nfsrv_freedevid(ds);
8027 }
8028
8029 /*
8030  * Check to see if there is a Read/Write Layout plus either:
8031  * - A Write Delegation
8032  * or
8033  * - An Open with Write_access.
8034  * Return 1 if this is the case and 0 otherwise.
8035  * This function is used by nfsrv_proxyds() to decide if doing a Proxy
8036  * Getattr RPC to the Data Server (DS) is necessary.
8037  */
8038 #define NFSCLIDVECSIZE  6
8039 int
8040 nfsrv_checkdsattr(struct nfsrv_descript *nd, vnode_t vp, NFSPROC_T *p)
8041 {
8042         fhandle_t fh, *tfhp;
8043         struct nfsstate *stp;
8044         struct nfslayout *lyp;
8045         struct nfslayouthash *lhyp;
8046         struct nfslockhashhead *hp;
8047         struct nfslockfile *lfp;
8048         nfsquad_t clid[NFSCLIDVECSIZE];
8049         int clidcnt, ret;
8050
8051         ret = nfsvno_getfh(vp, &fh, p);
8052         if (ret != 0)
8053                 return (0);
8054
8055         /* First check for a Read/Write Layout. */
8056         clidcnt = 0;
8057         lhyp = NFSLAYOUTHASH(&fh);
8058         NFSLOCKLAYOUT(lhyp);
8059         TAILQ_FOREACH(lyp, &lhyp->list, lay_list) {
8060                 if (NFSBCMP(&lyp->lay_fh, &fh, sizeof(fh)) == 0 &&
8061                     ((lyp->lay_flags & NFSLAY_RW) != 0 ||
8062                      ((lyp->lay_flags & NFSLAY_READ) != 0 &&
8063                       nfsrv_pnfsatime != 0))) {
8064                         if (clidcnt < NFSCLIDVECSIZE)
8065                                 clid[clidcnt].qval = lyp->lay_clientid.qval;
8066                         clidcnt++;
8067                 }
8068         }
8069         NFSUNLOCKLAYOUT(lhyp);
8070         if (clidcnt == 0) {
8071                 /* None found, so return 0. */
8072                 return (0);
8073         }
8074
8075         /* Get the nfslockfile for this fh. */
8076         NFSLOCKSTATE();
8077         hp = NFSLOCKHASH(&fh);
8078         LIST_FOREACH(lfp, hp, lf_hash) {
8079                 tfhp = &lfp->lf_fh;
8080                 if (NFSVNO_CMPFH(&fh, tfhp))
8081                         break;
8082         }
8083         if (lfp == NULL) {
8084                 /* None found, so return 0. */
8085                 NFSUNLOCKSTATE();
8086                 return (0);
8087         }
8088
8089         /* Now, look for a Write delegation for this clientid. */
8090         LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
8091                 if ((stp->ls_flags & NFSLCK_DELEGWRITE) != 0 &&
8092                     nfsrv_fndclid(clid, stp->ls_clp->lc_clientid, clidcnt) != 0)
8093                         break;
8094         }
8095         if (stp != NULL) {
8096                 /* Found one, so return 1. */
8097                 NFSUNLOCKSTATE();
8098                 return (1);
8099         }
8100
8101         /* No Write delegation, so look for an Open with Write_access. */
8102         LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
8103                 KASSERT((stp->ls_flags & NFSLCK_OPEN) != 0,
8104                     ("nfsrv_checkdsattr: Non-open in Open list\n"));
8105                 if ((stp->ls_flags & NFSLCK_WRITEACCESS) != 0 &&
8106                     nfsrv_fndclid(clid, stp->ls_clp->lc_clientid, clidcnt) != 0)
8107                         break;
8108         }
8109         NFSUNLOCKSTATE();
8110         if (stp != NULL)
8111                 return (1);
8112         return (0);
8113 }
8114
8115 /*
8116  * Look for a matching clientid in the vector. Return 1 if one might match.
8117  */
8118 static int
8119 nfsrv_fndclid(nfsquad_t *clidvec, nfsquad_t clid, int clidcnt)
8120 {
8121         int i;
8122
8123         /* If too many for the vector, return 1 since there might be a match. */
8124         if (clidcnt > NFSCLIDVECSIZE)
8125                 return (1);
8126
8127         for (i = 0; i < clidcnt; i++)
8128                 if (clidvec[i].qval == clid.qval)
8129                         return (1);
8130         return (0);
8131 }
8132
8133 /*
8134  * Check the don't list for "vp" and see if issuing an rw layout is allowed.
8135  * Return 1 if issuing an rw layout isn't allowed, 0 otherwise.
8136  */
8137 static int
8138 nfsrv_dontlayout(fhandle_t *fhp)
8139 {
8140         struct nfsdontlist *mrp;
8141         int ret;
8142
8143         if (nfsrv_dontlistlen == 0)
8144                 return (0);
8145         ret = 0;
8146         NFSDDONTLISTLOCK();
8147         LIST_FOREACH(mrp, &nfsrv_dontlisthead, nfsmr_list) {
8148                 if (NFSBCMP(fhp, &mrp->nfsmr_fh, sizeof(*fhp)) == 0 &&
8149                     (mrp->nfsmr_flags & NFSMR_DONTLAYOUT) != 0) {
8150                         ret = 1;
8151                         break;
8152                 }
8153         }
8154         NFSDDONTLISTUNLOCK();
8155         return (ret);
8156 }
8157
8158 #define PNFSDS_COPYSIZ  65536
8159 /*
8160  * Create a new file on a DS and copy the contents of an extant DS file to it.
8161  * This can be used for recovery of a DS file onto a recovered DS.
8162  * The steps are:
8163  * - When called, the MDS file's vnode is locked, blocking LayoutGet operations.
8164  * - Disable issuing of read/write layouts for the file via the nfsdontlist,
8165  *   so that they will be disabled after the MDS file's vnode is unlocked.
8166  * - Set up the nfsrv_recalllist so that recall of read/write layouts can
8167  *   be done.
8168  * - Unlock the MDS file's vnode, so that the client(s) can perform proxied
8169  *   writes, LayoutCommits and LayoutReturns for the file when completing the
8170  *   LayoutReturn requested by the LayoutRecall callback.
8171  * - Issue a LayoutRecall callback for all read/write layouts and wait for
8172  *   them to be returned. (If the LayoutRecall callback replies
8173  *   NFSERR_NOMATCHLAYOUT, they are gone and no LayoutReturn is needed.)
8174  * - Exclusively lock the MDS file's vnode.  This ensures that no proxied
8175  *   writes are in progress or can occur during the DS file copy.
8176  *   It also blocks Setattr operations.
8177  * - Create the file on the recovered mirror.
8178  * - Copy the file from the operational DS.
8179  * - Copy any ACL from the MDS file to the new DS file.
8180  * - Set the modify time of the new DS file to that of the MDS file.
8181  * - Update the extended attribute for the MDS file.
8182  * - Enable issuing of rw layouts by deleting the nfsdontlist entry.
8183  * - The caller will unlock the MDS file's vnode allowing operations
8184  *   to continue normally, since it is now on the mirror again.
8185  */
8186 int
8187 nfsrv_copymr(vnode_t vp, vnode_t fvp, vnode_t dvp, struct nfsdevice *ds,
8188     struct pnfsdsfile *pf, struct pnfsdsfile *wpf, int mirrorcnt,
8189     struct ucred *cred, NFSPROC_T *p)
8190 {
8191         struct nfsdontlist *mrp, *nmrp;
8192         struct nfslayouthash *lhyp;
8193         struct nfslayout *lyp, *nlyp;
8194         struct nfslayouthead thl;
8195         struct mount *mp, *tvmp;
8196         struct acl *aclp;
8197         struct vattr va;
8198         struct timespec mtime;
8199         fhandle_t fh;
8200         vnode_t tvp;
8201         off_t rdpos, wrpos;
8202         ssize_t aresid;
8203         char *dat;
8204         int didprintf, ret, retacl, xfer;
8205
8206         ASSERT_VOP_LOCKED(fvp, "nfsrv_copymr fvp");
8207         ASSERT_VOP_LOCKED(vp, "nfsrv_copymr vp");
8208         /*
8209          * Allocate a nfsdontlist entry and set the NFSMR_DONTLAYOUT flag
8210          * so that no more RW layouts will get issued.
8211          */
8212         ret = nfsvno_getfh(vp, &fh, p);
8213         if (ret != 0) {
8214                 NFSD_DEBUG(4, "nfsrv_copymr: getfh=%d\n", ret);
8215                 return (ret);
8216         }
8217         nmrp = malloc(sizeof(*nmrp), M_NFSDSTATE, M_WAITOK);
8218         nmrp->nfsmr_flags = NFSMR_DONTLAYOUT;
8219         NFSBCOPY(&fh, &nmrp->nfsmr_fh, sizeof(fh));
8220         NFSDDONTLISTLOCK();
8221         LIST_FOREACH(mrp, &nfsrv_dontlisthead, nfsmr_list) {
8222                 if (NFSBCMP(&fh, &mrp->nfsmr_fh, sizeof(fh)) == 0)
8223                         break;
8224         }
8225         if (mrp == NULL) {
8226                 LIST_INSERT_HEAD(&nfsrv_dontlisthead, nmrp, nfsmr_list);
8227                 mrp = nmrp;
8228                 nmrp = NULL;
8229                 nfsrv_dontlistlen++;
8230                 NFSD_DEBUG(4, "nfsrv_copymr: in dontlist\n");
8231         } else {
8232                 NFSDDONTLISTUNLOCK();
8233                 free(nmrp, M_NFSDSTATE);
8234                 NFSD_DEBUG(4, "nfsrv_copymr: dup dontlist\n");
8235                 return (ENXIO);
8236         }
8237         NFSDDONTLISTUNLOCK();
8238
8239         /*
8240          * Search for all RW layouts for this file.  Move them to the
8241          * recall list, so they can be recalled and their return noted.
8242          */
8243         lhyp = NFSLAYOUTHASH(&fh);
8244         NFSDRECALLLOCK();
8245         NFSLOCKLAYOUT(lhyp);
8246         TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
8247                 if (NFSBCMP(&lyp->lay_fh, &fh, sizeof(fh)) == 0 &&
8248                     (lyp->lay_flags & NFSLAY_RW) != 0) {
8249                         TAILQ_REMOVE(&lhyp->list, lyp, lay_list);
8250                         TAILQ_INSERT_HEAD(&nfsrv_recalllisthead, lyp, lay_list);
8251                         lyp->lay_trycnt = 0;
8252                 }
8253         }
8254         NFSUNLOCKLAYOUT(lhyp);
8255         NFSDRECALLUNLOCK();
8256
8257         ret = 0;
8258         mp = tvmp = NULL;
8259         didprintf = 0;
8260         TAILQ_INIT(&thl);
8261         /* Unlock the MDS vp, so that a LayoutReturn can be done on it. */
8262         NFSVOPUNLOCK(vp, 0);
8263         /* Now, do a recall for all layouts not yet recalled. */
8264 tryagain:
8265         NFSDRECALLLOCK();
8266         TAILQ_FOREACH(lyp, &nfsrv_recalllisthead, lay_list) {
8267                 if (NFSBCMP(&lyp->lay_fh, &fh, sizeof(fh)) == 0 &&
8268                     (lyp->lay_flags & NFSLAY_RECALL) == 0) {
8269                         lyp->lay_flags |= NFSLAY_RECALL;
8270                         /*
8271                          * The layout stateid.seqid needs to be incremented
8272                          * before doing a LAYOUT_RECALL callback.
8273                          */
8274                         if (++lyp->lay_stateid.seqid == 0)
8275                                 lyp->lay_stateid.seqid = 1;
8276                         NFSDRECALLUNLOCK();
8277                         nfsrv_recalllayout(lyp->lay_clientid, &lyp->lay_stateid,
8278                             &lyp->lay_fh, lyp, 0, lyp->lay_type, p);
8279                         NFSD_DEBUG(4, "nfsrv_copymr: recalled layout\n");
8280                         goto tryagain;
8281                 }
8282         }
8283
8284         /* Now wait for them to be returned. */
8285 tryagain2:
8286         TAILQ_FOREACH(lyp, &nfsrv_recalllisthead, lay_list) {
8287                 if (NFSBCMP(&lyp->lay_fh, &fh, sizeof(fh)) == 0) {
8288                         if ((lyp->lay_flags & NFSLAY_RETURNED) != 0) {
8289                                 TAILQ_REMOVE(&nfsrv_recalllisthead, lyp,
8290                                     lay_list);
8291                                 TAILQ_INSERT_HEAD(&thl, lyp, lay_list);
8292                                 NFSD_DEBUG(4,
8293                                     "nfsrv_copymr: layout returned\n");
8294                         } else {
8295                                 lyp->lay_trycnt++;
8296                                 ret = mtx_sleep(lyp, NFSDRECALLMUTEXPTR,
8297                                     PVFS | PCATCH, "nfsmrl", hz);
8298                                 NFSD_DEBUG(4, "nfsrv_copymr: aft sleep=%d\n",
8299                                     ret);
8300                                 if (ret == EINTR || ret == ERESTART)
8301                                         break;
8302                                 if ((lyp->lay_flags & NFSLAY_RETURNED) == 0) {
8303                                         /*
8304                                          * Give up after 60sec and return
8305                                          * ENXIO, failing the copymr.
8306                                          * This layout will remain on the
8307                                          * recalllist.  It can only be cleared
8308                                          * by restarting the nfsd.
8309                                          * This seems the safe way to handle
8310                                          * it, since it cannot be safely copied
8311                                          * with an outstanding RW layout.
8312                                          */
8313                                         if (lyp->lay_trycnt >= 60) {
8314                                                 ret = ENXIO;
8315                                                 break;
8316                                         }
8317                                         if (didprintf == 0) {
8318                                                 printf("nfsrv_copymr: layout "
8319                                                     "not returned\n");
8320                                                 didprintf = 1;
8321                                         }
8322                                 }
8323                         }
8324                         goto tryagain2;
8325                 }
8326         }
8327         NFSDRECALLUNLOCK();
8328         /* We can now get rid of the layouts that have been returned. */
8329         TAILQ_FOREACH_SAFE(lyp, &thl, lay_list, nlyp)
8330                 nfsrv_freelayout(&thl, lyp);
8331
8332         /*
8333          * Do the vn_start_write() calls here, before the MDS vnode is
8334          * locked and the tvp is created (locked) in the NFS file system
8335          * that dvp is in.
8336          * For tvmp, this probably isn't necessary, since it will be an
8337          * NFS mount and they are not suspendable at this time.
8338          */
8339         if (ret == 0)
8340                 ret = vn_start_write(vp, &mp, V_WAIT | PCATCH);
8341         if (ret == 0) {
8342                 tvmp = dvp->v_mount;
8343                 ret = vn_start_write(NULL, &tvmp, V_WAIT | PCATCH);
8344         }
8345
8346         /*
8347          * LK_EXCLUSIVE lock the MDS vnode, so that any
8348          * proxied writes through the MDS will be blocked until we have
8349          * completed the copy and update of the extended attributes.
8350          * This will also ensure that any attributes and ACL will not be
8351          * changed until the copy is complete.
8352          */
8353         NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
8354         if (ret == 0 && (vp->v_iflag & VI_DOOMED) != 0) {
8355                 NFSD_DEBUG(4, "nfsrv_copymr: lk_exclusive doomed\n");
8356                 ret = ESTALE;
8357         }
8358
8359         /* Create the data file on the recovered DS. */
8360         if (ret == 0)
8361                 ret = nfsrv_createdsfile(vp, &fh, pf, dvp, ds, cred, p, &tvp);
8362
8363         /* Copy the DS file, if created successfully. */
8364         if (ret == 0) {
8365                 /*
8366                  * Get any NFSv4 ACL on the MDS file, so that it can be set
8367                  * on the new DS file.
8368                  */
8369                 aclp = acl_alloc(M_WAITOK | M_ZERO);
8370                 retacl = VOP_GETACL(vp, ACL_TYPE_NFS4, aclp, cred, p);
8371                 if (retacl != 0 && retacl != ENOATTR)
8372                         NFSD_DEBUG(1, "nfsrv_copymr: vop_getacl=%d\n", retacl);
8373                 dat = malloc(PNFSDS_COPYSIZ, M_TEMP, M_WAITOK);
8374                 /* Malloc a block of 0s used to check for holes. */
8375                 if (nfsrv_zeropnfsdat == NULL)
8376                         nfsrv_zeropnfsdat = malloc(PNFSDS_COPYSIZ, M_TEMP,
8377                             M_WAITOK | M_ZERO);
8378                 rdpos = wrpos = 0;
8379                 ret = VOP_GETATTR(fvp, &va, cred);
8380                 aresid = 0;
8381                 while (ret == 0 && aresid == 0) {
8382                         ret = vn_rdwr(UIO_READ, fvp, dat, PNFSDS_COPYSIZ,
8383                             rdpos, UIO_SYSSPACE, IO_NODELOCKED, cred, NULL,
8384                             &aresid, p);
8385                         xfer = PNFSDS_COPYSIZ - aresid;
8386                         if (ret == 0 && xfer > 0) {
8387                                 rdpos += xfer;
8388                                 /*
8389                                  * Skip the write for holes, except for the
8390                                  * last block.
8391                                  */
8392                                 if (xfer < PNFSDS_COPYSIZ || rdpos ==
8393                                     va.va_size || NFSBCMP(dat,
8394                                     nfsrv_zeropnfsdat, PNFSDS_COPYSIZ) != 0)
8395                                         ret = vn_rdwr(UIO_WRITE, tvp, dat, xfer,
8396                                             wrpos, UIO_SYSSPACE, IO_NODELOCKED,
8397                                             cred, NULL, NULL, p);
8398                                 if (ret == 0)
8399                                         wrpos += xfer;
8400                         }
8401                 }
8402
8403                 /* If there is an ACL and the copy succeeded, set the ACL. */
8404                 if (ret == 0 && retacl == 0) {
8405                         ret = VOP_SETACL(tvp, ACL_TYPE_NFS4, aclp, cred, p);
8406                         /*
8407                          * Don't consider these as errors, since VOP_GETACL()
8408                          * can return an ACL when they are not actually
8409                          * supported.  For example, for UFS, VOP_GETACL()
8410                          * will return a trivial ACL based on the uid/gid/mode
8411                          * when there is no ACL on the file.
8412                          * This case should be recognized as a trivial ACL
8413                          * by UFS's VOP_SETACL() and succeed, but...
8414                          */
8415                         if (ret == ENOATTR || ret == EOPNOTSUPP || ret == EPERM)
8416                                 ret = 0;
8417                 }
8418
8419                 if (ret == 0)
8420                         ret = VOP_FSYNC(tvp, MNT_WAIT, p);
8421
8422                 /* Set the DS data file's modify time that of the MDS file. */
8423                 if (ret == 0)
8424                         ret = VOP_GETATTR(vp, &va, cred);
8425                 if (ret == 0) {
8426                         mtime = va.va_mtime;
8427                         VATTR_NULL(&va);
8428                         va.va_mtime = mtime;
8429                         ret = VOP_SETATTR(tvp, &va, cred);
8430                 }
8431
8432                 vput(tvp);
8433                 acl_free(aclp);
8434                 free(dat, M_TEMP);
8435         }
8436         if (tvmp != NULL)
8437                 vn_finished_write(tvmp);
8438
8439         /* Update the extended attributes for the newly created DS file. */
8440         if (ret == 0)
8441                 ret = vn_extattr_set(vp, IO_NODELOCKED,
8442                     EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile",
8443                     sizeof(*wpf) * mirrorcnt, (char *)wpf, p);
8444         if (mp != NULL)
8445                 vn_finished_write(mp);
8446
8447         /* Get rid of the dontlist entry, so that Layouts can be issued. */
8448         NFSDDONTLISTLOCK();
8449         LIST_REMOVE(mrp, nfsmr_list);
8450         NFSDDONTLISTUNLOCK();
8451         free(mrp, M_NFSDSTATE);
8452         return (ret);
8453 }
8454
8455 /*
8456  * Create a data storage file on the recovered DS.
8457  */
8458 static int
8459 nfsrv_createdsfile(vnode_t vp, fhandle_t *fhp, struct pnfsdsfile *pf,
8460     vnode_t dvp, struct nfsdevice *ds, struct ucred *cred, NFSPROC_T *p,
8461     vnode_t *tvpp)
8462 {
8463         struct vattr va, nva;
8464         int error;
8465
8466         /* Make data file name based on FH. */
8467         error = VOP_GETATTR(vp, &va, cred);
8468         if (error == 0) {
8469                 /* Set the attributes for "vp" to Setattr the DS vp. */
8470                 VATTR_NULL(&nva);
8471                 nva.va_uid = va.va_uid;
8472                 nva.va_gid = va.va_gid;
8473                 nva.va_mode = va.va_mode;
8474                 nva.va_size = 0;
8475                 VATTR_NULL(&va);
8476                 va.va_type = VREG;
8477                 va.va_mode = nva.va_mode;
8478                 NFSD_DEBUG(4, "nfsrv_dscreatefile: dvp=%p pf=%p\n", dvp, pf);
8479                 error = nfsrv_dscreate(dvp, &va, &nva, fhp, pf, NULL,
8480                     pf->dsf_filename, cred, p, tvpp);
8481         }
8482         return (error);
8483 }
8484
8485 /*
8486  * Look up the MDS file shared locked, and then get the extended attribute
8487  * to find the extant DS file to be copied to the new mirror.
8488  * If successful, *vpp is set to the MDS file's vp and *nvpp is
8489  * set to a DS data file for the MDS file, both exclusively locked.
8490  * The "buf" argument has the pnfsdsfile structure from the MDS file
8491  * in it and buflen is set to its length.
8492  */
8493 int
8494 nfsrv_mdscopymr(char *mdspathp, char *dspathp, char *curdspathp, char *buf,
8495     int *buflenp, char *fname, NFSPROC_T *p, struct vnode **vpp,
8496     struct vnode **nvpp, struct pnfsdsfile **pfp, struct nfsdevice **dsp,
8497     struct nfsdevice **fdsp)
8498 {
8499         struct nameidata nd;
8500         struct vnode *vp, *curvp;
8501         struct pnfsdsfile *pf;
8502         struct nfsmount *nmp, *curnmp;
8503         int dsdir, error, mirrorcnt, ippos;
8504
8505         vp = NULL;
8506         curvp = NULL;
8507         curnmp = NULL;
8508         *dsp = NULL;
8509         *fdsp = NULL;
8510         if (dspathp == NULL && curdspathp != NULL)
8511                 return (EPERM);
8512
8513         /*
8514          * Look up the MDS file shared locked.  The lock will be upgraded
8515          * to an exclusive lock after any rw layouts have been returned.
8516          */
8517         NFSD_DEBUG(4, "mdsopen path=%s\n", mdspathp);
8518         NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF, UIO_SYSSPACE,
8519             mdspathp, p);
8520         error = namei(&nd);
8521         NFSD_DEBUG(4, "lookup=%d\n", error);
8522         if (error != 0)
8523                 return (error);
8524         if (nd.ni_vp->v_type != VREG) {
8525                 vput(nd.ni_vp);
8526                 NFSD_DEBUG(4, "mdspath not reg\n");
8527                 return (EISDIR);
8528         }
8529         vp = nd.ni_vp;
8530
8531         if (curdspathp != NULL) {
8532                 /*
8533                  * Look up the current DS path and find the nfsdev structure for
8534                  * it.
8535                  */
8536                 NFSD_DEBUG(4, "curmdsdev path=%s\n", curdspathp);
8537                 NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
8538                     UIO_SYSSPACE, curdspathp, p);
8539                 error = namei(&nd);
8540                 NFSD_DEBUG(4, "ds lookup=%d\n", error);
8541                 if (error != 0) {
8542                         vput(vp);
8543                         return (error);
8544                 }
8545                 if (nd.ni_vp->v_type != VDIR) {
8546                         vput(nd.ni_vp);
8547                         vput(vp);
8548                         NFSD_DEBUG(4, "curdspath not dir\n");
8549                         return (ENOTDIR);
8550                 }
8551                 if (strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name, "nfs") != 0) {
8552                         vput(nd.ni_vp);
8553                         vput(vp);
8554                         NFSD_DEBUG(4, "curdspath not an NFS mount\n");
8555                         return (ENXIO);
8556                 }
8557                 curnmp = VFSTONFS(nd.ni_vp->v_mount);
8558         
8559                 /* Search the nfsdev list for a match. */
8560                 NFSDDSLOCK();
8561                 *fdsp = nfsv4_findmirror(curnmp);
8562                 NFSDDSUNLOCK();
8563                 if (*fdsp == NULL)
8564                         curnmp = NULL;
8565                 if (curnmp == NULL) {
8566                         vput(nd.ni_vp);
8567                         vput(vp);
8568                         NFSD_DEBUG(4, "mdscopymr: no current ds\n");
8569                         return (ENXIO);
8570                 }
8571                 curvp = nd.ni_vp;
8572         }
8573
8574         if (dspathp != NULL) {
8575                 /* Look up the nfsdev path and find the nfsdev structure. */
8576                 NFSD_DEBUG(4, "mdsdev path=%s\n", dspathp);
8577                 NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
8578                     UIO_SYSSPACE, dspathp, p);
8579                 error = namei(&nd);
8580                 NFSD_DEBUG(4, "ds lookup=%d\n", error);
8581                 if (error != 0) {
8582                         vput(vp);
8583                         if (curvp != NULL)
8584                                 vput(curvp);
8585                         return (error);
8586                 }
8587                 if (nd.ni_vp->v_type != VDIR || nd.ni_vp == curvp) {
8588                         vput(nd.ni_vp);
8589                         vput(vp);
8590                         if (curvp != NULL)
8591                                 vput(curvp);
8592                         NFSD_DEBUG(4, "dspath not dir\n");
8593                         if (nd.ni_vp == curvp)
8594                                 return (EPERM);
8595                         return (ENOTDIR);
8596                 }
8597                 if (strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name, "nfs") != 0) {
8598                         vput(nd.ni_vp);
8599                         vput(vp);
8600                         if (curvp != NULL)
8601                                 vput(curvp);
8602                         NFSD_DEBUG(4, "dspath not an NFS mount\n");
8603                         return (ENXIO);
8604                 }
8605                 nmp = VFSTONFS(nd.ni_vp->v_mount);
8606         
8607                 /*
8608                  * Search the nfsdevice list for a match.  If curnmp == NULL,
8609                  * this is a recovery and there must be a mirror.
8610                  */
8611                 NFSDDSLOCK();
8612                 if (curnmp == NULL)
8613                         *dsp = nfsrv_findmirroredds(nmp);
8614                 else
8615                         *dsp = nfsv4_findmirror(nmp);
8616                 NFSDDSUNLOCK();
8617                 if (*dsp == NULL) {
8618                         vput(nd.ni_vp);
8619                         vput(vp);
8620                         if (curvp != NULL)
8621                                 vput(curvp);
8622                         NFSD_DEBUG(4, "mdscopymr: no ds\n");
8623                         return (ENXIO);
8624                 }
8625         } else {
8626                 nd.ni_vp = NULL;
8627                 nmp = NULL;
8628         }
8629
8630         /*
8631          * Get a vp for an available DS data file using the extended
8632          * attribute on the MDS file.
8633          * If there is a valid entry for the new DS in the extended attribute
8634          * on the MDS file (as checked via the nmp argument),
8635          * nfsrv_dsgetsockmnt() returns EEXIST, so no copying will occur.
8636          */
8637         error = nfsrv_dsgetsockmnt(vp, 0, buf, buflenp, &mirrorcnt, p,
8638             NULL, NULL, NULL, fname, nvpp, &nmp, curnmp, &ippos, &dsdir);
8639         if (curvp != NULL)
8640                 vput(curvp);
8641         if (nd.ni_vp == NULL) {
8642                 if (error == 0 && nmp != NULL) {
8643                         /* Search the nfsdev list for a match. */
8644                         NFSDDSLOCK();
8645                         *dsp = nfsrv_findmirroredds(nmp);
8646                         NFSDDSUNLOCK();
8647                 }
8648                 if (error == 0 && (nmp == NULL || *dsp == NULL)) {
8649                         if (nvpp != NULL && *nvpp != NULL) {
8650                                 vput(*nvpp);
8651                                 *nvpp = NULL;
8652                         }
8653                         error = ENXIO;
8654                 }
8655         } else
8656                 vput(nd.ni_vp);
8657
8658         /*
8659          * When dspathp != NULL and curdspathp == NULL, this is a recovery
8660          * and is only allowed if there is a 0.0.0.0 IP address entry.
8661          * When curdspathp != NULL, the ippos will be set to that entry.
8662          */
8663         if (error == 0 && dspathp != NULL && ippos == -1) {
8664                 if (nvpp != NULL && *nvpp != NULL) {
8665                         vput(*nvpp);
8666                         *nvpp = NULL;
8667                 }
8668                 error = ENXIO;
8669         }
8670         if (error == 0) {
8671                 *vpp = vp;
8672
8673                 pf = (struct pnfsdsfile *)buf;
8674                 if (ippos == -1) {
8675                         /* If no zeroip pnfsdsfile, add one. */
8676                         ippos = *buflenp / sizeof(*pf);
8677                         *buflenp += sizeof(*pf);
8678                         pf += ippos;
8679                         pf->dsf_dir = dsdir;
8680                         strlcpy(pf->dsf_filename, fname,
8681                             sizeof(pf->dsf_filename));
8682                 } else
8683                         pf += ippos;
8684                 *pfp = pf;
8685         } else
8686                 vput(vp);
8687         return (error);
8688 }
8689
8690 /*
8691  * Search for a matching pnfsd mirror device structure, base on the nmp arg.
8692  * Return one if found, NULL otherwise.
8693  */
8694 static struct nfsdevice *
8695 nfsrv_findmirroredds(struct nfsmount *nmp)
8696 {
8697         struct nfsdevice *ds, *fndds;
8698         int fndmirror;
8699
8700         mtx_assert(NFSDDSMUTEXPTR, MA_OWNED);
8701         /*
8702          * Search the DS server list for a match with nmp.
8703          * Remove the DS entry if found and there is a mirror.
8704          */
8705         fndds = NULL;
8706         fndmirror = 0;
8707         if (nfsrv_devidcnt == 0)
8708                 return (fndds);
8709         TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
8710                 if (ds->nfsdev_nmp == nmp) {
8711                         NFSD_DEBUG(4, "nfsrv_findmirroredds: fnd main ds\n");
8712                         fndds = ds;
8713                         break;
8714                 }
8715         }
8716         if (fndds == NULL)
8717                 return (fndds);
8718         if (fndds->nfsdev_mdsisset == 0 && nfsrv_faildscnt > 0)
8719                 fndmirror = 1;
8720         else if (fndds->nfsdev_mdsisset != 0) {
8721                 /* For the fsid is set case, search for a mirror. */
8722                 TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
8723                         if (ds != fndds && ds->nfsdev_nmp != NULL &&
8724                             ds->nfsdev_mdsisset != 0 &&
8725                             fsidcmp(&ds->nfsdev_mdsfsid,
8726                             &fndds->nfsdev_mdsfsid) == 0) {
8727                                 fndmirror = 1;
8728                                 break;
8729                         }
8730                 }
8731         }
8732         if (fndmirror == 0) {
8733                 NFSD_DEBUG(4, "nfsrv_findmirroredds: no mirror for DS\n");
8734                 return (NULL);
8735         }
8736         return (fndds);
8737 }
8738