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