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