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