xref: /openbmc/linux/fs/nfs/pnfs.c (revision c494a447)
1 /*
2  *  pNFS functions to call and manage layout drivers.
3  *
4  *  Copyright (c) 2002 [year of first publication]
5  *  The Regents of the University of Michigan
6  *  All Rights Reserved
7  *
8  *  Dean Hildebrand <dhildebz@umich.edu>
9  *
10  *  Permission is granted to use, copy, create derivative works, and
11  *  redistribute this software and such derivative works for any purpose,
12  *  so long as the name of the University of Michigan is not used in
13  *  any advertising or publicity pertaining to the use or distribution
14  *  of this software without specific, written prior authorization. If
15  *  the above copyright notice or any other identification of the
16  *  University of Michigan is included in any copy of any portion of
17  *  this software, then the disclaimer below must also be included.
18  *
19  *  This software is provided as is, without representation or warranty
20  *  of any kind either express or implied, including without limitation
21  *  the implied warranties of merchantability, fitness for a particular
22  *  purpose, or noninfringement.  The Regents of the University of
23  *  Michigan shall not be liable for any damages, including special,
24  *  indirect, incidental, or consequential damages, with respect to any
25  *  claim arising out of or in connection with the use of the software,
26  *  even if it has been or is hereafter advised of the possibility of
27  *  such damages.
28  */
29 
30 #include <linux/nfs_fs.h>
31 #include <linux/nfs_page.h>
32 #include <linux/module.h>
33 #include <linux/sort.h>
34 #include "internal.h"
35 #include "pnfs.h"
36 #include "iostat.h"
37 #include "nfs4trace.h"
38 #include "delegation.h"
39 #include "nfs42.h"
40 #include "nfs4_fs.h"
41 
42 #define NFSDBG_FACILITY		NFSDBG_PNFS
43 #define PNFS_LAYOUTGET_RETRY_TIMEOUT (120*HZ)
44 
45 /* Locking:
46  *
47  * pnfs_spinlock:
48  *      protects pnfs_modules_tbl.
49  */
50 static DEFINE_SPINLOCK(pnfs_spinlock);
51 
52 /*
53  * pnfs_modules_tbl holds all pnfs modules
54  */
55 static LIST_HEAD(pnfs_modules_tbl);
56 
57 static void pnfs_layoutreturn_before_put_layout_hdr(struct pnfs_layout_hdr *lo);
58 static void pnfs_free_returned_lsegs(struct pnfs_layout_hdr *lo,
59 		struct list_head *free_me,
60 		const struct pnfs_layout_range *range,
61 		u32 seq);
62 static bool pnfs_lseg_dec_and_remove_zero(struct pnfs_layout_segment *lseg,
63 		                struct list_head *tmp_list);
64 
65 /* Return the registered pnfs layout driver module matching given id */
66 static struct pnfs_layoutdriver_type *
67 find_pnfs_driver_locked(u32 id)
68 {
69 	struct pnfs_layoutdriver_type *local;
70 
71 	list_for_each_entry(local, &pnfs_modules_tbl, pnfs_tblid)
72 		if (local->id == id)
73 			goto out;
74 	local = NULL;
75 out:
76 	dprintk("%s: Searching for id %u, found %p\n", __func__, id, local);
77 	return local;
78 }
79 
80 static struct pnfs_layoutdriver_type *
81 find_pnfs_driver(u32 id)
82 {
83 	struct pnfs_layoutdriver_type *local;
84 
85 	spin_lock(&pnfs_spinlock);
86 	local = find_pnfs_driver_locked(id);
87 	if (local != NULL && !try_module_get(local->owner)) {
88 		dprintk("%s: Could not grab reference on module\n", __func__);
89 		local = NULL;
90 	}
91 	spin_unlock(&pnfs_spinlock);
92 	return local;
93 }
94 
95 const struct pnfs_layoutdriver_type *pnfs_find_layoutdriver(u32 id)
96 {
97 	return find_pnfs_driver(id);
98 }
99 
100 void pnfs_put_layoutdriver(const struct pnfs_layoutdriver_type *ld)
101 {
102 	if (ld)
103 		module_put(ld->owner);
104 }
105 
106 void
107 unset_pnfs_layoutdriver(struct nfs_server *nfss)
108 {
109 	if (nfss->pnfs_curr_ld) {
110 		if (nfss->pnfs_curr_ld->clear_layoutdriver)
111 			nfss->pnfs_curr_ld->clear_layoutdriver(nfss);
112 		/* Decrement the MDS count. Purge the deviceid cache if zero */
113 		if (atomic_dec_and_test(&nfss->nfs_client->cl_mds_count))
114 			nfs4_deviceid_purge_client(nfss->nfs_client);
115 		module_put(nfss->pnfs_curr_ld->owner);
116 	}
117 	nfss->pnfs_curr_ld = NULL;
118 }
119 
120 /*
121  * When the server sends a list of layout types, we choose one in the order
122  * given in the list below.
123  *
124  * FIXME: should this list be configurable in some fashion? module param?
125  * 	  mount option? something else?
126  */
127 static const u32 ld_prefs[] = {
128 	LAYOUT_SCSI,
129 	LAYOUT_BLOCK_VOLUME,
130 	LAYOUT_OSD2_OBJECTS,
131 	LAYOUT_FLEX_FILES,
132 	LAYOUT_NFSV4_1_FILES,
133 	0
134 };
135 
136 static int
137 ld_cmp(const void *e1, const void *e2)
138 {
139 	u32 ld1 = *((u32 *)e1);
140 	u32 ld2 = *((u32 *)e2);
141 	int i;
142 
143 	for (i = 0; ld_prefs[i] != 0; i++) {
144 		if (ld1 == ld_prefs[i])
145 			return -1;
146 
147 		if (ld2 == ld_prefs[i])
148 			return 1;
149 	}
150 	return 0;
151 }
152 
153 /*
154  * Try to set the server's pnfs module to the pnfs layout type specified by id.
155  * Currently only one pNFS layout driver per filesystem is supported.
156  *
157  * @ids array of layout types supported by MDS.
158  */
159 void
160 set_pnfs_layoutdriver(struct nfs_server *server, const struct nfs_fh *mntfh,
161 		      struct nfs_fsinfo *fsinfo)
162 {
163 	struct pnfs_layoutdriver_type *ld_type = NULL;
164 	u32 id;
165 	int i;
166 
167 	if (fsinfo->nlayouttypes == 0)
168 		goto out_no_driver;
169 	if (!(server->nfs_client->cl_exchange_flags &
170 		 (EXCHGID4_FLAG_USE_NON_PNFS | EXCHGID4_FLAG_USE_PNFS_MDS))) {
171 		printk(KERN_ERR "NFS: %s: cl_exchange_flags 0x%x\n",
172 			__func__, server->nfs_client->cl_exchange_flags);
173 		goto out_no_driver;
174 	}
175 
176 	sort(fsinfo->layouttype, fsinfo->nlayouttypes,
177 		sizeof(*fsinfo->layouttype), ld_cmp, NULL);
178 
179 	for (i = 0; i < fsinfo->nlayouttypes; i++) {
180 		id = fsinfo->layouttype[i];
181 		ld_type = find_pnfs_driver(id);
182 		if (!ld_type) {
183 			request_module("%s-%u", LAYOUT_NFSV4_1_MODULE_PREFIX,
184 					id);
185 			ld_type = find_pnfs_driver(id);
186 		}
187 		if (ld_type)
188 			break;
189 	}
190 
191 	if (!ld_type) {
192 		dprintk("%s: No pNFS module found!\n", __func__);
193 		goto out_no_driver;
194 	}
195 
196 	server->pnfs_curr_ld = ld_type;
197 	if (ld_type->set_layoutdriver
198 	    && ld_type->set_layoutdriver(server, mntfh)) {
199 		printk(KERN_ERR "NFS: %s: Error initializing pNFS layout "
200 			"driver %u.\n", __func__, id);
201 		module_put(ld_type->owner);
202 		goto out_no_driver;
203 	}
204 	/* Bump the MDS count */
205 	atomic_inc(&server->nfs_client->cl_mds_count);
206 
207 	dprintk("%s: pNFS module for %u set\n", __func__, id);
208 	return;
209 
210 out_no_driver:
211 	dprintk("%s: Using NFSv4 I/O\n", __func__);
212 	server->pnfs_curr_ld = NULL;
213 }
214 
215 int
216 pnfs_register_layoutdriver(struct pnfs_layoutdriver_type *ld_type)
217 {
218 	int status = -EINVAL;
219 	struct pnfs_layoutdriver_type *tmp;
220 
221 	if (ld_type->id == 0) {
222 		printk(KERN_ERR "NFS: %s id 0 is reserved\n", __func__);
223 		return status;
224 	}
225 	if (!ld_type->alloc_lseg || !ld_type->free_lseg) {
226 		printk(KERN_ERR "NFS: %s Layout driver must provide "
227 		       "alloc_lseg and free_lseg.\n", __func__);
228 		return status;
229 	}
230 
231 	spin_lock(&pnfs_spinlock);
232 	tmp = find_pnfs_driver_locked(ld_type->id);
233 	if (!tmp) {
234 		list_add(&ld_type->pnfs_tblid, &pnfs_modules_tbl);
235 		status = 0;
236 		dprintk("%s Registering id:%u name:%s\n", __func__, ld_type->id,
237 			ld_type->name);
238 	} else {
239 		printk(KERN_ERR "NFS: %s Module with id %d already loaded!\n",
240 			__func__, ld_type->id);
241 	}
242 	spin_unlock(&pnfs_spinlock);
243 
244 	return status;
245 }
246 EXPORT_SYMBOL_GPL(pnfs_register_layoutdriver);
247 
248 void
249 pnfs_unregister_layoutdriver(struct pnfs_layoutdriver_type *ld_type)
250 {
251 	dprintk("%s Deregistering id:%u\n", __func__, ld_type->id);
252 	spin_lock(&pnfs_spinlock);
253 	list_del(&ld_type->pnfs_tblid);
254 	spin_unlock(&pnfs_spinlock);
255 }
256 EXPORT_SYMBOL_GPL(pnfs_unregister_layoutdriver);
257 
258 /*
259  * pNFS client layout cache
260  */
261 
262 /* Need to hold i_lock if caller does not already hold reference */
263 void
264 pnfs_get_layout_hdr(struct pnfs_layout_hdr *lo)
265 {
266 	refcount_inc(&lo->plh_refcount);
267 }
268 
269 static struct pnfs_layout_hdr *
270 pnfs_alloc_layout_hdr(struct inode *ino, gfp_t gfp_flags)
271 {
272 	struct pnfs_layoutdriver_type *ld = NFS_SERVER(ino)->pnfs_curr_ld;
273 	return ld->alloc_layout_hdr(ino, gfp_flags);
274 }
275 
276 static void
277 pnfs_free_layout_hdr(struct pnfs_layout_hdr *lo)
278 {
279 	struct nfs_server *server = NFS_SERVER(lo->plh_inode);
280 	struct pnfs_layoutdriver_type *ld = server->pnfs_curr_ld;
281 
282 	if (test_and_clear_bit(NFS_LAYOUT_HASHED, &lo->plh_flags)) {
283 		struct nfs_client *clp = server->nfs_client;
284 
285 		spin_lock(&clp->cl_lock);
286 		list_del_rcu(&lo->plh_layouts);
287 		spin_unlock(&clp->cl_lock);
288 	}
289 	put_cred(lo->plh_lc_cred);
290 	return ld->free_layout_hdr(lo);
291 }
292 
293 static void
294 pnfs_detach_layout_hdr(struct pnfs_layout_hdr *lo)
295 {
296 	struct nfs_inode *nfsi = NFS_I(lo->plh_inode);
297 	dprintk("%s: freeing layout cache %p\n", __func__, lo);
298 	nfsi->layout = NULL;
299 	/* Reset MDS Threshold I/O counters */
300 	nfsi->write_io = 0;
301 	nfsi->read_io = 0;
302 }
303 
304 void
305 pnfs_put_layout_hdr(struct pnfs_layout_hdr *lo)
306 {
307 	struct inode *inode;
308 	unsigned long i_state;
309 
310 	if (!lo)
311 		return;
312 	inode = lo->plh_inode;
313 	pnfs_layoutreturn_before_put_layout_hdr(lo);
314 
315 	if (refcount_dec_and_lock(&lo->plh_refcount, &inode->i_lock)) {
316 		if (!list_empty(&lo->plh_segs))
317 			WARN_ONCE(1, "NFS: BUG unfreed layout segments.\n");
318 		pnfs_detach_layout_hdr(lo);
319 		i_state = inode->i_state;
320 		spin_unlock(&inode->i_lock);
321 		pnfs_free_layout_hdr(lo);
322 		/* Notify pnfs_destroy_layout_final() that we're done */
323 		if (i_state & (I_FREEING | I_CLEAR))
324 			wake_up_var(lo);
325 	}
326 }
327 
328 static struct inode *
329 pnfs_grab_inode_layout_hdr(struct pnfs_layout_hdr *lo)
330 {
331 	struct inode *inode = igrab(lo->plh_inode);
332 	if (inode)
333 		return inode;
334 	set_bit(NFS_LAYOUT_INODE_FREEING, &lo->plh_flags);
335 	return NULL;
336 }
337 
338 /*
339  * Compare 2 layout stateid sequence ids, to see which is newer,
340  * taking into account wraparound issues.
341  */
342 static bool pnfs_seqid_is_newer(u32 s1, u32 s2)
343 {
344 	return (s32)(s1 - s2) > 0;
345 }
346 
347 static void pnfs_barrier_update(struct pnfs_layout_hdr *lo, u32 newseq)
348 {
349 	if (pnfs_seqid_is_newer(newseq, lo->plh_barrier) || !lo->plh_barrier)
350 		lo->plh_barrier = newseq;
351 }
352 
353 static void
354 pnfs_set_plh_return_info(struct pnfs_layout_hdr *lo, enum pnfs_iomode iomode,
355 			 u32 seq)
356 {
357 	if (lo->plh_return_iomode != 0 && lo->plh_return_iomode != iomode)
358 		iomode = IOMODE_ANY;
359 	lo->plh_return_iomode = iomode;
360 	set_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags);
361 	/*
362 	 * We must set lo->plh_return_seq to avoid livelocks with
363 	 * pnfs_layout_need_return()
364 	 */
365 	if (seq == 0)
366 		seq = be32_to_cpu(lo->plh_stateid.seqid);
367 	if (!lo->plh_return_seq || pnfs_seqid_is_newer(seq, lo->plh_return_seq))
368 		lo->plh_return_seq = seq;
369 	pnfs_barrier_update(lo, seq);
370 }
371 
372 static void
373 pnfs_clear_layoutreturn_info(struct pnfs_layout_hdr *lo)
374 {
375 	struct pnfs_layout_segment *lseg;
376 	lo->plh_return_iomode = 0;
377 	lo->plh_return_seq = 0;
378 	clear_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags);
379 	list_for_each_entry(lseg, &lo->plh_segs, pls_list) {
380 		if (!test_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags))
381 			continue;
382 		pnfs_set_plh_return_info(lo, lseg->pls_range.iomode, 0);
383 	}
384 }
385 
386 static void pnfs_clear_layoutreturn_waitbit(struct pnfs_layout_hdr *lo)
387 {
388 	clear_bit_unlock(NFS_LAYOUT_RETURN, &lo->plh_flags);
389 	clear_bit(NFS_LAYOUT_RETURN_LOCK, &lo->plh_flags);
390 	smp_mb__after_atomic();
391 	wake_up_bit(&lo->plh_flags, NFS_LAYOUT_RETURN);
392 	rpc_wake_up(&NFS_SERVER(lo->plh_inode)->roc_rpcwaitq);
393 }
394 
395 static void
396 pnfs_clear_lseg_state(struct pnfs_layout_segment *lseg,
397 		struct list_head *free_me)
398 {
399 	clear_bit(NFS_LSEG_ROC, &lseg->pls_flags);
400 	clear_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags);
401 	if (test_and_clear_bit(NFS_LSEG_VALID, &lseg->pls_flags))
402 		pnfs_lseg_dec_and_remove_zero(lseg, free_me);
403 	if (test_and_clear_bit(NFS_LSEG_LAYOUTCOMMIT, &lseg->pls_flags))
404 		pnfs_lseg_dec_and_remove_zero(lseg, free_me);
405 }
406 
407 /*
408  * Update the seqid of a layout stateid after receiving
409  * NFS4ERR_OLD_STATEID
410  */
411 bool nfs4_layout_refresh_old_stateid(nfs4_stateid *dst,
412 		struct pnfs_layout_range *dst_range,
413 		struct inode *inode)
414 {
415 	struct pnfs_layout_hdr *lo;
416 	struct pnfs_layout_range range = {
417 		.iomode = IOMODE_ANY,
418 		.offset = 0,
419 		.length = NFS4_MAX_UINT64,
420 	};
421 	bool ret = false;
422 	LIST_HEAD(head);
423 	int err;
424 
425 	spin_lock(&inode->i_lock);
426 	lo = NFS_I(inode)->layout;
427 	if (lo &&  pnfs_layout_is_valid(lo) &&
428 	    nfs4_stateid_match_other(dst, &lo->plh_stateid)) {
429 		/* Is our call using the most recent seqid? If so, bump it */
430 		if (!nfs4_stateid_is_newer(&lo->plh_stateid, dst)) {
431 			nfs4_stateid_seqid_inc(dst);
432 			ret = true;
433 			goto out;
434 		}
435 		/* Try to update the seqid to the most recent */
436 		err = pnfs_mark_matching_lsegs_return(lo, &head, &range, 0);
437 		if (err != -EBUSY) {
438 			dst->seqid = lo->plh_stateid.seqid;
439 			*dst_range = range;
440 			ret = true;
441 		}
442 	}
443 out:
444 	spin_unlock(&inode->i_lock);
445 	pnfs_free_lseg_list(&head);
446 	return ret;
447 }
448 
449 /*
450  * Mark a pnfs_layout_hdr and all associated layout segments as invalid
451  *
452  * In order to continue using the pnfs_layout_hdr, a full recovery
453  * is required.
454  * Note that caller must hold inode->i_lock.
455  */
456 int
457 pnfs_mark_layout_stateid_invalid(struct pnfs_layout_hdr *lo,
458 		struct list_head *lseg_list)
459 {
460 	struct pnfs_layout_range range = {
461 		.iomode = IOMODE_ANY,
462 		.offset = 0,
463 		.length = NFS4_MAX_UINT64,
464 	};
465 	struct pnfs_layout_segment *lseg, *next;
466 
467 	set_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags);
468 	list_for_each_entry_safe(lseg, next, &lo->plh_segs, pls_list)
469 		pnfs_clear_lseg_state(lseg, lseg_list);
470 	pnfs_clear_layoutreturn_info(lo);
471 	pnfs_free_returned_lsegs(lo, lseg_list, &range, 0);
472 	if (test_bit(NFS_LAYOUT_RETURN, &lo->plh_flags) &&
473 	    !test_and_set_bit(NFS_LAYOUT_RETURN_LOCK, &lo->plh_flags))
474 		pnfs_clear_layoutreturn_waitbit(lo);
475 	return !list_empty(&lo->plh_segs);
476 }
477 
478 static int
479 pnfs_iomode_to_fail_bit(u32 iomode)
480 {
481 	return iomode == IOMODE_RW ?
482 		NFS_LAYOUT_RW_FAILED : NFS_LAYOUT_RO_FAILED;
483 }
484 
485 static void
486 pnfs_layout_set_fail_bit(struct pnfs_layout_hdr *lo, int fail_bit)
487 {
488 	lo->plh_retry_timestamp = jiffies;
489 	if (!test_and_set_bit(fail_bit, &lo->plh_flags))
490 		refcount_inc(&lo->plh_refcount);
491 }
492 
493 static void
494 pnfs_layout_clear_fail_bit(struct pnfs_layout_hdr *lo, int fail_bit)
495 {
496 	if (test_and_clear_bit(fail_bit, &lo->plh_flags))
497 		refcount_dec(&lo->plh_refcount);
498 }
499 
500 static void
501 pnfs_layout_io_set_failed(struct pnfs_layout_hdr *lo, u32 iomode)
502 {
503 	struct inode *inode = lo->plh_inode;
504 	struct pnfs_layout_range range = {
505 		.iomode = iomode,
506 		.offset = 0,
507 		.length = NFS4_MAX_UINT64,
508 	};
509 	LIST_HEAD(head);
510 
511 	spin_lock(&inode->i_lock);
512 	pnfs_layout_set_fail_bit(lo, pnfs_iomode_to_fail_bit(iomode));
513 	pnfs_mark_matching_lsegs_invalid(lo, &head, &range, 0);
514 	spin_unlock(&inode->i_lock);
515 	pnfs_free_lseg_list(&head);
516 	dprintk("%s Setting layout IOMODE_%s fail bit\n", __func__,
517 			iomode == IOMODE_RW ?  "RW" : "READ");
518 }
519 
520 static bool
521 pnfs_layout_io_test_failed(struct pnfs_layout_hdr *lo, u32 iomode)
522 {
523 	unsigned long start, end;
524 	int fail_bit = pnfs_iomode_to_fail_bit(iomode);
525 
526 	if (test_bit(fail_bit, &lo->plh_flags) == 0)
527 		return false;
528 	end = jiffies;
529 	start = end - PNFS_LAYOUTGET_RETRY_TIMEOUT;
530 	if (!time_in_range(lo->plh_retry_timestamp, start, end)) {
531 		/* It is time to retry the failed layoutgets */
532 		pnfs_layout_clear_fail_bit(lo, fail_bit);
533 		return false;
534 	}
535 	return true;
536 }
537 
538 static void
539 pnfs_init_lseg(struct pnfs_layout_hdr *lo, struct pnfs_layout_segment *lseg,
540 		const struct pnfs_layout_range *range,
541 		const nfs4_stateid *stateid)
542 {
543 	INIT_LIST_HEAD(&lseg->pls_list);
544 	INIT_LIST_HEAD(&lseg->pls_lc_list);
545 	INIT_LIST_HEAD(&lseg->pls_commits);
546 	refcount_set(&lseg->pls_refcount, 1);
547 	set_bit(NFS_LSEG_VALID, &lseg->pls_flags);
548 	lseg->pls_layout = lo;
549 	lseg->pls_range = *range;
550 	lseg->pls_seq = be32_to_cpu(stateid->seqid);
551 }
552 
553 static void pnfs_free_lseg(struct pnfs_layout_segment *lseg)
554 {
555 	if (lseg != NULL) {
556 		struct inode *inode = lseg->pls_layout->plh_inode;
557 		NFS_SERVER(inode)->pnfs_curr_ld->free_lseg(lseg);
558 	}
559 }
560 
561 static void
562 pnfs_layout_remove_lseg(struct pnfs_layout_hdr *lo,
563 		struct pnfs_layout_segment *lseg)
564 {
565 	WARN_ON(test_bit(NFS_LSEG_VALID, &lseg->pls_flags));
566 	list_del_init(&lseg->pls_list);
567 	/* Matched by pnfs_get_layout_hdr in pnfs_layout_insert_lseg */
568 	refcount_dec(&lo->plh_refcount);
569 	if (test_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags))
570 		return;
571 	if (list_empty(&lo->plh_segs) &&
572 	    !test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags) &&
573 	    !test_bit(NFS_LAYOUT_RETURN, &lo->plh_flags)) {
574 		if (atomic_read(&lo->plh_outstanding) == 0)
575 			set_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags);
576 		clear_bit(NFS_LAYOUT_BULK_RECALL, &lo->plh_flags);
577 	}
578 }
579 
580 static bool
581 pnfs_cache_lseg_for_layoutreturn(struct pnfs_layout_hdr *lo,
582 		struct pnfs_layout_segment *lseg)
583 {
584 	if (test_and_clear_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags) &&
585 	    pnfs_layout_is_valid(lo)) {
586 		pnfs_set_plh_return_info(lo, lseg->pls_range.iomode, 0);
587 		list_move_tail(&lseg->pls_list, &lo->plh_return_segs);
588 		return true;
589 	}
590 	return false;
591 }
592 
593 void
594 pnfs_put_lseg(struct pnfs_layout_segment *lseg)
595 {
596 	struct pnfs_layout_hdr *lo;
597 	struct inode *inode;
598 
599 	if (!lseg)
600 		return;
601 
602 	dprintk("%s: lseg %p ref %d valid %d\n", __func__, lseg,
603 		refcount_read(&lseg->pls_refcount),
604 		test_bit(NFS_LSEG_VALID, &lseg->pls_flags));
605 
606 	lo = lseg->pls_layout;
607 	inode = lo->plh_inode;
608 
609 	if (refcount_dec_and_lock(&lseg->pls_refcount, &inode->i_lock)) {
610 		pnfs_get_layout_hdr(lo);
611 		pnfs_layout_remove_lseg(lo, lseg);
612 		if (pnfs_cache_lseg_for_layoutreturn(lo, lseg))
613 			lseg = NULL;
614 		spin_unlock(&inode->i_lock);
615 		pnfs_free_lseg(lseg);
616 		pnfs_put_layout_hdr(lo);
617 	}
618 }
619 EXPORT_SYMBOL_GPL(pnfs_put_lseg);
620 
621 /*
622  * is l2 fully contained in l1?
623  *   start1                             end1
624  *   [----------------------------------)
625  *           start2           end2
626  *           [----------------)
627  */
628 static bool
629 pnfs_lseg_range_contained(const struct pnfs_layout_range *l1,
630 		 const struct pnfs_layout_range *l2)
631 {
632 	u64 start1 = l1->offset;
633 	u64 end1 = pnfs_end_offset(start1, l1->length);
634 	u64 start2 = l2->offset;
635 	u64 end2 = pnfs_end_offset(start2, l2->length);
636 
637 	return (start1 <= start2) && (end1 >= end2);
638 }
639 
640 static bool pnfs_lseg_dec_and_remove_zero(struct pnfs_layout_segment *lseg,
641 		struct list_head *tmp_list)
642 {
643 	if (!refcount_dec_and_test(&lseg->pls_refcount))
644 		return false;
645 	pnfs_layout_remove_lseg(lseg->pls_layout, lseg);
646 	list_add(&lseg->pls_list, tmp_list);
647 	return true;
648 }
649 
650 /* Returns 1 if lseg is removed from list, 0 otherwise */
651 static int mark_lseg_invalid(struct pnfs_layout_segment *lseg,
652 			     struct list_head *tmp_list)
653 {
654 	int rv = 0;
655 
656 	if (test_and_clear_bit(NFS_LSEG_VALID, &lseg->pls_flags)) {
657 		/* Remove the reference keeping the lseg in the
658 		 * list.  It will now be removed when all
659 		 * outstanding io is finished.
660 		 */
661 		dprintk("%s: lseg %p ref %d\n", __func__, lseg,
662 			refcount_read(&lseg->pls_refcount));
663 		if (pnfs_lseg_dec_and_remove_zero(lseg, tmp_list))
664 			rv = 1;
665 	}
666 	return rv;
667 }
668 
669 static bool
670 pnfs_should_free_range(const struct pnfs_layout_range *lseg_range,
671 		 const struct pnfs_layout_range *recall_range)
672 {
673 	return (recall_range->iomode == IOMODE_ANY ||
674 		lseg_range->iomode == recall_range->iomode) &&
675 	       pnfs_lseg_range_intersecting(lseg_range, recall_range);
676 }
677 
678 static bool
679 pnfs_match_lseg_recall(const struct pnfs_layout_segment *lseg,
680 		const struct pnfs_layout_range *recall_range,
681 		u32 seq)
682 {
683 	if (seq != 0 && pnfs_seqid_is_newer(lseg->pls_seq, seq))
684 		return false;
685 	if (recall_range == NULL)
686 		return true;
687 	return pnfs_should_free_range(&lseg->pls_range, recall_range);
688 }
689 
690 /**
691  * pnfs_mark_matching_lsegs_invalid - tear down lsegs or mark them for later
692  * @lo: layout header containing the lsegs
693  * @tmp_list: list head where doomed lsegs should go
694  * @recall_range: optional recall range argument to match (may be NULL)
695  * @seq: only invalidate lsegs obtained prior to this sequence (may be 0)
696  *
697  * Walk the list of lsegs in the layout header, and tear down any that should
698  * be destroyed. If "recall_range" is specified then the segment must match
699  * that range. If "seq" is non-zero, then only match segments that were handed
700  * out at or before that sequence.
701  *
702  * Returns number of matching invalid lsegs remaining in list after scanning
703  * it and purging them.
704  */
705 int
706 pnfs_mark_matching_lsegs_invalid(struct pnfs_layout_hdr *lo,
707 			    struct list_head *tmp_list,
708 			    const struct pnfs_layout_range *recall_range,
709 			    u32 seq)
710 {
711 	struct pnfs_layout_segment *lseg, *next;
712 	int remaining = 0;
713 
714 	dprintk("%s:Begin lo %p\n", __func__, lo);
715 
716 	if (list_empty(&lo->plh_segs))
717 		return 0;
718 	list_for_each_entry_safe(lseg, next, &lo->plh_segs, pls_list)
719 		if (pnfs_match_lseg_recall(lseg, recall_range, seq)) {
720 			dprintk("%s: freeing lseg %p iomode %d seq %u "
721 				"offset %llu length %llu\n", __func__,
722 				lseg, lseg->pls_range.iomode, lseg->pls_seq,
723 				lseg->pls_range.offset, lseg->pls_range.length);
724 			if (!mark_lseg_invalid(lseg, tmp_list))
725 				remaining++;
726 		}
727 	dprintk("%s:Return %i\n", __func__, remaining);
728 	return remaining;
729 }
730 
731 static void
732 pnfs_free_returned_lsegs(struct pnfs_layout_hdr *lo,
733 		struct list_head *free_me,
734 		const struct pnfs_layout_range *range,
735 		u32 seq)
736 {
737 	struct pnfs_layout_segment *lseg, *next;
738 
739 	list_for_each_entry_safe(lseg, next, &lo->plh_return_segs, pls_list) {
740 		if (pnfs_match_lseg_recall(lseg, range, seq))
741 			list_move_tail(&lseg->pls_list, free_me);
742 	}
743 }
744 
745 /* note free_me must contain lsegs from a single layout_hdr */
746 void
747 pnfs_free_lseg_list(struct list_head *free_me)
748 {
749 	struct pnfs_layout_segment *lseg, *tmp;
750 
751 	if (list_empty(free_me))
752 		return;
753 
754 	list_for_each_entry_safe(lseg, tmp, free_me, pls_list) {
755 		list_del(&lseg->pls_list);
756 		pnfs_free_lseg(lseg);
757 	}
758 }
759 
760 static struct pnfs_layout_hdr *__pnfs_destroy_layout(struct nfs_inode *nfsi)
761 {
762 	struct pnfs_layout_hdr *lo;
763 	LIST_HEAD(tmp_list);
764 
765 	spin_lock(&nfsi->vfs_inode.i_lock);
766 	lo = nfsi->layout;
767 	if (lo) {
768 		pnfs_get_layout_hdr(lo);
769 		pnfs_mark_layout_stateid_invalid(lo, &tmp_list);
770 		pnfs_layout_clear_fail_bit(lo, NFS_LAYOUT_RO_FAILED);
771 		pnfs_layout_clear_fail_bit(lo, NFS_LAYOUT_RW_FAILED);
772 		spin_unlock(&nfsi->vfs_inode.i_lock);
773 		pnfs_free_lseg_list(&tmp_list);
774 		nfs_commit_inode(&nfsi->vfs_inode, 0);
775 		pnfs_put_layout_hdr(lo);
776 	} else
777 		spin_unlock(&nfsi->vfs_inode.i_lock);
778 	return lo;
779 }
780 
781 void pnfs_destroy_layout(struct nfs_inode *nfsi)
782 {
783 	__pnfs_destroy_layout(nfsi);
784 }
785 EXPORT_SYMBOL_GPL(pnfs_destroy_layout);
786 
787 static bool pnfs_layout_removed(struct nfs_inode *nfsi,
788 				struct pnfs_layout_hdr *lo)
789 {
790 	bool ret;
791 
792 	spin_lock(&nfsi->vfs_inode.i_lock);
793 	ret = nfsi->layout != lo;
794 	spin_unlock(&nfsi->vfs_inode.i_lock);
795 	return ret;
796 }
797 
798 void pnfs_destroy_layout_final(struct nfs_inode *nfsi)
799 {
800 	struct pnfs_layout_hdr *lo = __pnfs_destroy_layout(nfsi);
801 
802 	if (lo)
803 		wait_var_event(lo, pnfs_layout_removed(nfsi, lo));
804 }
805 
806 static bool
807 pnfs_layout_add_bulk_destroy_list(struct inode *inode,
808 		struct list_head *layout_list)
809 {
810 	struct pnfs_layout_hdr *lo;
811 	bool ret = false;
812 
813 	spin_lock(&inode->i_lock);
814 	lo = NFS_I(inode)->layout;
815 	if (lo != NULL && list_empty(&lo->plh_bulk_destroy)) {
816 		pnfs_get_layout_hdr(lo);
817 		list_add(&lo->plh_bulk_destroy, layout_list);
818 		ret = true;
819 	}
820 	spin_unlock(&inode->i_lock);
821 	return ret;
822 }
823 
824 /* Caller must hold rcu_read_lock and clp->cl_lock */
825 static int
826 pnfs_layout_bulk_destroy_byserver_locked(struct nfs_client *clp,
827 		struct nfs_server *server,
828 		struct list_head *layout_list)
829 	__must_hold(&clp->cl_lock)
830 	__must_hold(RCU)
831 {
832 	struct pnfs_layout_hdr *lo, *next;
833 	struct inode *inode;
834 
835 	list_for_each_entry_safe(lo, next, &server->layouts, plh_layouts) {
836 		if (test_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags) ||
837 		    test_bit(NFS_LAYOUT_INODE_FREEING, &lo->plh_flags) ||
838 		    !list_empty(&lo->plh_bulk_destroy))
839 			continue;
840 		/* If the sb is being destroyed, just bail */
841 		if (!nfs_sb_active(server->super))
842 			break;
843 		inode = pnfs_grab_inode_layout_hdr(lo);
844 		if (inode != NULL) {
845 			if (test_and_clear_bit(NFS_LAYOUT_HASHED, &lo->plh_flags))
846 				list_del_rcu(&lo->plh_layouts);
847 			if (pnfs_layout_add_bulk_destroy_list(inode,
848 						layout_list))
849 				continue;
850 			rcu_read_unlock();
851 			spin_unlock(&clp->cl_lock);
852 			iput(inode);
853 		} else {
854 			rcu_read_unlock();
855 			spin_unlock(&clp->cl_lock);
856 		}
857 		nfs_sb_deactive(server->super);
858 		spin_lock(&clp->cl_lock);
859 		rcu_read_lock();
860 		return -EAGAIN;
861 	}
862 	return 0;
863 }
864 
865 static int
866 pnfs_layout_free_bulk_destroy_list(struct list_head *layout_list,
867 		bool is_bulk_recall)
868 {
869 	struct pnfs_layout_hdr *lo;
870 	struct inode *inode;
871 	LIST_HEAD(lseg_list);
872 	int ret = 0;
873 
874 	while (!list_empty(layout_list)) {
875 		lo = list_entry(layout_list->next, struct pnfs_layout_hdr,
876 				plh_bulk_destroy);
877 		dprintk("%s freeing layout for inode %lu\n", __func__,
878 			lo->plh_inode->i_ino);
879 		inode = lo->plh_inode;
880 
881 		pnfs_layoutcommit_inode(inode, false);
882 
883 		spin_lock(&inode->i_lock);
884 		list_del_init(&lo->plh_bulk_destroy);
885 		if (pnfs_mark_layout_stateid_invalid(lo, &lseg_list)) {
886 			if (is_bulk_recall)
887 				set_bit(NFS_LAYOUT_BULK_RECALL, &lo->plh_flags);
888 			ret = -EAGAIN;
889 		}
890 		spin_unlock(&inode->i_lock);
891 		pnfs_free_lseg_list(&lseg_list);
892 		/* Free all lsegs that are attached to commit buckets */
893 		nfs_commit_inode(inode, 0);
894 		pnfs_put_layout_hdr(lo);
895 		nfs_iput_and_deactive(inode);
896 	}
897 	return ret;
898 }
899 
900 int
901 pnfs_destroy_layouts_byfsid(struct nfs_client *clp,
902 		struct nfs_fsid *fsid,
903 		bool is_recall)
904 {
905 	struct nfs_server *server;
906 	LIST_HEAD(layout_list);
907 
908 	spin_lock(&clp->cl_lock);
909 	rcu_read_lock();
910 restart:
911 	list_for_each_entry_rcu(server, &clp->cl_superblocks, client_link) {
912 		if (memcmp(&server->fsid, fsid, sizeof(*fsid)) != 0)
913 			continue;
914 		if (pnfs_layout_bulk_destroy_byserver_locked(clp,
915 				server,
916 				&layout_list) != 0)
917 			goto restart;
918 	}
919 	rcu_read_unlock();
920 	spin_unlock(&clp->cl_lock);
921 
922 	if (list_empty(&layout_list))
923 		return 0;
924 	return pnfs_layout_free_bulk_destroy_list(&layout_list, is_recall);
925 }
926 
927 int
928 pnfs_destroy_layouts_byclid(struct nfs_client *clp,
929 		bool is_recall)
930 {
931 	struct nfs_server *server;
932 	LIST_HEAD(layout_list);
933 
934 	spin_lock(&clp->cl_lock);
935 	rcu_read_lock();
936 restart:
937 	list_for_each_entry_rcu(server, &clp->cl_superblocks, client_link) {
938 		if (pnfs_layout_bulk_destroy_byserver_locked(clp,
939 					server,
940 					&layout_list) != 0)
941 			goto restart;
942 	}
943 	rcu_read_unlock();
944 	spin_unlock(&clp->cl_lock);
945 
946 	if (list_empty(&layout_list))
947 		return 0;
948 	return pnfs_layout_free_bulk_destroy_list(&layout_list, is_recall);
949 }
950 
951 /*
952  * Called by the state manager to remove all layouts established under an
953  * expired lease.
954  */
955 void
956 pnfs_destroy_all_layouts(struct nfs_client *clp)
957 {
958 	nfs4_deviceid_mark_client_invalid(clp);
959 	nfs4_deviceid_purge_client(clp);
960 
961 	pnfs_destroy_layouts_byclid(clp, false);
962 }
963 
964 static void
965 pnfs_set_layout_cred(struct pnfs_layout_hdr *lo, const struct cred *cred)
966 {
967 	const struct cred *old;
968 
969 	if (cred && cred_fscmp(lo->plh_lc_cred, cred) != 0) {
970 		old = xchg(&lo->plh_lc_cred, get_cred(cred));
971 		put_cred(old);
972 	}
973 }
974 
975 /* update lo->plh_stateid with new if is more recent */
976 void
977 pnfs_set_layout_stateid(struct pnfs_layout_hdr *lo, const nfs4_stateid *new,
978 			const struct cred *cred, bool update_barrier)
979 {
980 	u32 oldseq = be32_to_cpu(lo->plh_stateid.seqid);
981 	u32 newseq = be32_to_cpu(new->seqid);
982 
983 	if (!pnfs_layout_is_valid(lo)) {
984 		pnfs_set_layout_cred(lo, cred);
985 		nfs4_stateid_copy(&lo->plh_stateid, new);
986 		lo->plh_barrier = newseq;
987 		pnfs_clear_layoutreturn_info(lo);
988 		clear_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags);
989 		return;
990 	}
991 
992 	if (pnfs_seqid_is_newer(newseq, oldseq))
993 		nfs4_stateid_copy(&lo->plh_stateid, new);
994 
995 	if (update_barrier) {
996 		pnfs_barrier_update(lo, newseq);
997 		return;
998 	}
999 	/*
1000 	 * Because of wraparound, we want to keep the barrier
1001 	 * "close" to the current seqids. We really only want to
1002 	 * get here from a layoutget call.
1003 	 */
1004 	if (atomic_read(&lo->plh_outstanding) == 1)
1005 		 pnfs_barrier_update(lo, be32_to_cpu(lo->plh_stateid.seqid));
1006 }
1007 
1008 static bool
1009 pnfs_layout_stateid_blocked(const struct pnfs_layout_hdr *lo,
1010 		const nfs4_stateid *stateid)
1011 {
1012 	u32 seqid = be32_to_cpu(stateid->seqid);
1013 
1014 	return lo->plh_barrier && pnfs_seqid_is_newer(lo->plh_barrier, seqid);
1015 }
1016 
1017 /* lget is set to 1 if called from inside send_layoutget call chain */
1018 static bool
1019 pnfs_layoutgets_blocked(const struct pnfs_layout_hdr *lo)
1020 {
1021 	return lo->plh_block_lgets ||
1022 		test_bit(NFS_LAYOUT_BULK_RECALL, &lo->plh_flags);
1023 }
1024 
1025 static struct nfs_server *
1026 pnfs_find_server(struct inode *inode, struct nfs_open_context *ctx)
1027 {
1028 	struct nfs_server *server;
1029 
1030 	if (inode) {
1031 		server = NFS_SERVER(inode);
1032 	} else {
1033 		struct dentry *parent_dir = dget_parent(ctx->dentry);
1034 		server = NFS_SERVER(parent_dir->d_inode);
1035 		dput(parent_dir);
1036 	}
1037 	return server;
1038 }
1039 
1040 static void nfs4_free_pages(struct page **pages, size_t size)
1041 {
1042 	int i;
1043 
1044 	if (!pages)
1045 		return;
1046 
1047 	for (i = 0; i < size; i++) {
1048 		if (!pages[i])
1049 			break;
1050 		__free_page(pages[i]);
1051 	}
1052 	kfree(pages);
1053 }
1054 
1055 static struct page **nfs4_alloc_pages(size_t size, gfp_t gfp_flags)
1056 {
1057 	struct page **pages;
1058 	int i;
1059 
1060 	pages = kmalloc_array(size, sizeof(struct page *), gfp_flags);
1061 	if (!pages) {
1062 		dprintk("%s: can't alloc array of %zu pages\n", __func__, size);
1063 		return NULL;
1064 	}
1065 
1066 	for (i = 0; i < size; i++) {
1067 		pages[i] = alloc_page(gfp_flags);
1068 		if (!pages[i]) {
1069 			dprintk("%s: failed to allocate page\n", __func__);
1070 			nfs4_free_pages(pages, i);
1071 			return NULL;
1072 		}
1073 	}
1074 
1075 	return pages;
1076 }
1077 
1078 static struct nfs4_layoutget *
1079 pnfs_alloc_init_layoutget_args(struct inode *ino,
1080 	   struct nfs_open_context *ctx,
1081 	   const nfs4_stateid *stateid,
1082 	   const struct pnfs_layout_range *range,
1083 	   gfp_t gfp_flags)
1084 {
1085 	struct nfs_server *server = pnfs_find_server(ino, ctx);
1086 	size_t max_reply_sz = server->pnfs_curr_ld->max_layoutget_response;
1087 	size_t max_pages = max_response_pages(server);
1088 	struct nfs4_layoutget *lgp;
1089 
1090 	dprintk("--> %s\n", __func__);
1091 
1092 	lgp = kzalloc(sizeof(*lgp), gfp_flags);
1093 	if (lgp == NULL)
1094 		return NULL;
1095 
1096 	if (max_reply_sz) {
1097 		size_t npages = (max_reply_sz + PAGE_SIZE - 1) >> PAGE_SHIFT;
1098 		if (npages < max_pages)
1099 			max_pages = npages;
1100 	}
1101 
1102 	lgp->args.layout.pages = nfs4_alloc_pages(max_pages, gfp_flags);
1103 	if (!lgp->args.layout.pages) {
1104 		kfree(lgp);
1105 		return NULL;
1106 	}
1107 	lgp->args.layout.pglen = max_pages * PAGE_SIZE;
1108 	lgp->res.layoutp = &lgp->args.layout;
1109 
1110 	/* Don't confuse uninitialised result and success */
1111 	lgp->res.status = -NFS4ERR_DELAY;
1112 
1113 	lgp->args.minlength = PAGE_SIZE;
1114 	if (lgp->args.minlength > range->length)
1115 		lgp->args.minlength = range->length;
1116 	if (ino) {
1117 		loff_t i_size = i_size_read(ino);
1118 
1119 		if (range->iomode == IOMODE_READ) {
1120 			if (range->offset >= i_size)
1121 				lgp->args.minlength = 0;
1122 			else if (i_size - range->offset < lgp->args.minlength)
1123 				lgp->args.minlength = i_size - range->offset;
1124 		}
1125 	}
1126 	lgp->args.maxcount = PNFS_LAYOUT_MAXSIZE;
1127 	pnfs_copy_range(&lgp->args.range, range);
1128 	lgp->args.type = server->pnfs_curr_ld->id;
1129 	lgp->args.inode = ino;
1130 	lgp->args.ctx = get_nfs_open_context(ctx);
1131 	nfs4_stateid_copy(&lgp->args.stateid, stateid);
1132 	lgp->gfp_flags = gfp_flags;
1133 	lgp->cred = ctx->cred;
1134 	return lgp;
1135 }
1136 
1137 void pnfs_layoutget_free(struct nfs4_layoutget *lgp)
1138 {
1139 	size_t max_pages = lgp->args.layout.pglen / PAGE_SIZE;
1140 
1141 	nfs4_free_pages(lgp->args.layout.pages, max_pages);
1142 	pnfs_put_layout_hdr(lgp->lo);
1143 	put_nfs_open_context(lgp->args.ctx);
1144 	kfree(lgp);
1145 }
1146 
1147 static void pnfs_clear_layoutcommit(struct inode *inode,
1148 		struct list_head *head)
1149 {
1150 	struct nfs_inode *nfsi = NFS_I(inode);
1151 	struct pnfs_layout_segment *lseg, *tmp;
1152 
1153 	if (!test_and_clear_bit(NFS_INO_LAYOUTCOMMIT, &nfsi->flags))
1154 		return;
1155 	list_for_each_entry_safe(lseg, tmp, &nfsi->layout->plh_segs, pls_list) {
1156 		if (!test_and_clear_bit(NFS_LSEG_LAYOUTCOMMIT, &lseg->pls_flags))
1157 			continue;
1158 		pnfs_lseg_dec_and_remove_zero(lseg, head);
1159 	}
1160 }
1161 
1162 void pnfs_layoutreturn_free_lsegs(struct pnfs_layout_hdr *lo,
1163 		const nfs4_stateid *arg_stateid,
1164 		const struct pnfs_layout_range *range,
1165 		const nfs4_stateid *stateid)
1166 {
1167 	struct inode *inode = lo->plh_inode;
1168 	LIST_HEAD(freeme);
1169 
1170 	spin_lock(&inode->i_lock);
1171 	if (!pnfs_layout_is_valid(lo) ||
1172 	    !nfs4_stateid_match_other(&lo->plh_stateid, arg_stateid))
1173 		goto out_unlock;
1174 	if (stateid) {
1175 		u32 seq = be32_to_cpu(arg_stateid->seqid);
1176 
1177 		pnfs_mark_matching_lsegs_invalid(lo, &freeme, range, seq);
1178 		pnfs_free_returned_lsegs(lo, &freeme, range, seq);
1179 		pnfs_set_layout_stateid(lo, stateid, NULL, true);
1180 	} else
1181 		pnfs_mark_layout_stateid_invalid(lo, &freeme);
1182 out_unlock:
1183 	pnfs_clear_layoutreturn_waitbit(lo);
1184 	spin_unlock(&inode->i_lock);
1185 	pnfs_free_lseg_list(&freeme);
1186 
1187 }
1188 
1189 static bool
1190 pnfs_prepare_layoutreturn(struct pnfs_layout_hdr *lo,
1191 		nfs4_stateid *stateid,
1192 		const struct cred **cred,
1193 		enum pnfs_iomode *iomode)
1194 {
1195 	/* Serialise LAYOUTGET/LAYOUTRETURN */
1196 	if (atomic_read(&lo->plh_outstanding) != 0)
1197 		return false;
1198 	if (test_and_set_bit(NFS_LAYOUT_RETURN_LOCK, &lo->plh_flags))
1199 		return false;
1200 	set_bit(NFS_LAYOUT_RETURN, &lo->plh_flags);
1201 	pnfs_get_layout_hdr(lo);
1202 	nfs4_stateid_copy(stateid, &lo->plh_stateid);
1203 	*cred = get_cred(lo->plh_lc_cred);
1204 	if (test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags)) {
1205 		if (lo->plh_return_seq != 0)
1206 			stateid->seqid = cpu_to_be32(lo->plh_return_seq);
1207 		if (iomode != NULL)
1208 			*iomode = lo->plh_return_iomode;
1209 		pnfs_clear_layoutreturn_info(lo);
1210 	} else if (iomode != NULL)
1211 		*iomode = IOMODE_ANY;
1212 	pnfs_barrier_update(lo, be32_to_cpu(stateid->seqid));
1213 	return true;
1214 }
1215 
1216 static void
1217 pnfs_init_layoutreturn_args(struct nfs4_layoutreturn_args *args,
1218 		struct pnfs_layout_hdr *lo,
1219 		const nfs4_stateid *stateid,
1220 		enum pnfs_iomode iomode)
1221 {
1222 	struct inode *inode = lo->plh_inode;
1223 
1224 	args->layout_type = NFS_SERVER(inode)->pnfs_curr_ld->id;
1225 	args->inode = inode;
1226 	args->range.iomode = iomode;
1227 	args->range.offset = 0;
1228 	args->range.length = NFS4_MAX_UINT64;
1229 	args->layout = lo;
1230 	nfs4_stateid_copy(&args->stateid, stateid);
1231 }
1232 
1233 static int
1234 pnfs_send_layoutreturn(struct pnfs_layout_hdr *lo,
1235 		       const nfs4_stateid *stateid,
1236 		       const struct cred **pcred,
1237 		       enum pnfs_iomode iomode,
1238 		       bool sync)
1239 {
1240 	struct inode *ino = lo->plh_inode;
1241 	struct pnfs_layoutdriver_type *ld = NFS_SERVER(ino)->pnfs_curr_ld;
1242 	struct nfs4_layoutreturn *lrp;
1243 	const struct cred *cred = *pcred;
1244 	int status = 0;
1245 
1246 	*pcred = NULL;
1247 	lrp = kzalloc(sizeof(*lrp), nfs_io_gfp_mask());
1248 	if (unlikely(lrp == NULL)) {
1249 		status = -ENOMEM;
1250 		spin_lock(&ino->i_lock);
1251 		pnfs_clear_layoutreturn_waitbit(lo);
1252 		spin_unlock(&ino->i_lock);
1253 		put_cred(cred);
1254 		pnfs_put_layout_hdr(lo);
1255 		goto out;
1256 	}
1257 
1258 	pnfs_init_layoutreturn_args(&lrp->args, lo, stateid, iomode);
1259 	lrp->args.ld_private = &lrp->ld_private;
1260 	lrp->clp = NFS_SERVER(ino)->nfs_client;
1261 	lrp->cred = cred;
1262 	if (ld->prepare_layoutreturn)
1263 		ld->prepare_layoutreturn(&lrp->args);
1264 
1265 	status = nfs4_proc_layoutreturn(lrp, sync);
1266 out:
1267 	dprintk("<-- %s status: %d\n", __func__, status);
1268 	return status;
1269 }
1270 
1271 static bool
1272 pnfs_layout_segments_returnable(struct pnfs_layout_hdr *lo,
1273 				enum pnfs_iomode iomode,
1274 				u32 seq)
1275 {
1276 	struct pnfs_layout_range recall_range = {
1277 		.length = NFS4_MAX_UINT64,
1278 		.iomode = iomode,
1279 	};
1280 	return pnfs_mark_matching_lsegs_return(lo, &lo->plh_return_segs,
1281 					       &recall_range, seq) != -EBUSY;
1282 }
1283 
1284 /* Return true if layoutreturn is needed */
1285 static bool
1286 pnfs_layout_need_return(struct pnfs_layout_hdr *lo)
1287 {
1288 	if (!test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags))
1289 		return false;
1290 	return pnfs_layout_segments_returnable(lo, lo->plh_return_iomode,
1291 					       lo->plh_return_seq);
1292 }
1293 
1294 static void pnfs_layoutreturn_before_put_layout_hdr(struct pnfs_layout_hdr *lo)
1295 {
1296 	struct inode *inode= lo->plh_inode;
1297 
1298 	if (!test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags))
1299 		return;
1300 	spin_lock(&inode->i_lock);
1301 	if (pnfs_layout_need_return(lo)) {
1302 		const struct cred *cred;
1303 		nfs4_stateid stateid;
1304 		enum pnfs_iomode iomode;
1305 		bool send;
1306 
1307 		send = pnfs_prepare_layoutreturn(lo, &stateid, &cred, &iomode);
1308 		spin_unlock(&inode->i_lock);
1309 		if (send) {
1310 			/* Send an async layoutreturn so we dont deadlock */
1311 			pnfs_send_layoutreturn(lo, &stateid, &cred, iomode, false);
1312 		}
1313 	} else
1314 		spin_unlock(&inode->i_lock);
1315 }
1316 
1317 /*
1318  * Initiates a LAYOUTRETURN(FILE), and removes the pnfs_layout_hdr
1319  * when the layout segment list is empty.
1320  *
1321  * Note that a pnfs_layout_hdr can exist with an empty layout segment
1322  * list when LAYOUTGET has failed, or when LAYOUTGET succeeded, but the
1323  * deviceid is marked invalid.
1324  */
1325 int
1326 _pnfs_return_layout(struct inode *ino)
1327 {
1328 	struct pnfs_layout_hdr *lo = NULL;
1329 	struct nfs_inode *nfsi = NFS_I(ino);
1330 	struct pnfs_layout_range range = {
1331 		.iomode		= IOMODE_ANY,
1332 		.offset		= 0,
1333 		.length		= NFS4_MAX_UINT64,
1334 	};
1335 	LIST_HEAD(tmp_list);
1336 	const struct cred *cred;
1337 	nfs4_stateid stateid;
1338 	int status = 0;
1339 	bool send, valid_layout;
1340 
1341 	dprintk("NFS: %s for inode %lu\n", __func__, ino->i_ino);
1342 
1343 	spin_lock(&ino->i_lock);
1344 	lo = nfsi->layout;
1345 	if (!lo) {
1346 		spin_unlock(&ino->i_lock);
1347 		dprintk("NFS: %s no layout to return\n", __func__);
1348 		goto out;
1349 	}
1350 	/* Reference matched in nfs4_layoutreturn_release */
1351 	pnfs_get_layout_hdr(lo);
1352 	/* Is there an outstanding layoutreturn ? */
1353 	if (test_bit(NFS_LAYOUT_RETURN_LOCK, &lo->plh_flags)) {
1354 		spin_unlock(&ino->i_lock);
1355 		if (wait_on_bit(&lo->plh_flags, NFS_LAYOUT_RETURN,
1356 					TASK_UNINTERRUPTIBLE))
1357 			goto out_put_layout_hdr;
1358 		spin_lock(&ino->i_lock);
1359 	}
1360 	valid_layout = pnfs_layout_is_valid(lo);
1361 	pnfs_clear_layoutcommit(ino, &tmp_list);
1362 	pnfs_mark_matching_lsegs_return(lo, &tmp_list, &range, 0);
1363 
1364 	if (NFS_SERVER(ino)->pnfs_curr_ld->return_range)
1365 		NFS_SERVER(ino)->pnfs_curr_ld->return_range(lo, &range);
1366 
1367 	/* Don't send a LAYOUTRETURN if list was initially empty */
1368 	if (!test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags) ||
1369 			!valid_layout) {
1370 		spin_unlock(&ino->i_lock);
1371 		dprintk("NFS: %s no layout segments to return\n", __func__);
1372 		goto out_wait_layoutreturn;
1373 	}
1374 
1375 	send = pnfs_prepare_layoutreturn(lo, &stateid, &cred, NULL);
1376 	spin_unlock(&ino->i_lock);
1377 	if (send)
1378 		status = pnfs_send_layoutreturn(lo, &stateid, &cred, IOMODE_ANY, true);
1379 out_wait_layoutreturn:
1380 	wait_on_bit(&lo->plh_flags, NFS_LAYOUT_RETURN, TASK_UNINTERRUPTIBLE);
1381 out_put_layout_hdr:
1382 	pnfs_free_lseg_list(&tmp_list);
1383 	pnfs_put_layout_hdr(lo);
1384 out:
1385 	dprintk("<-- %s status: %d\n", __func__, status);
1386 	return status;
1387 }
1388 
1389 int
1390 pnfs_commit_and_return_layout(struct inode *inode)
1391 {
1392 	struct pnfs_layout_hdr *lo;
1393 	int ret;
1394 
1395 	spin_lock(&inode->i_lock);
1396 	lo = NFS_I(inode)->layout;
1397 	if (lo == NULL) {
1398 		spin_unlock(&inode->i_lock);
1399 		return 0;
1400 	}
1401 	pnfs_get_layout_hdr(lo);
1402 	/* Block new layoutgets and read/write to ds */
1403 	lo->plh_block_lgets++;
1404 	spin_unlock(&inode->i_lock);
1405 	filemap_fdatawait(inode->i_mapping);
1406 	ret = pnfs_layoutcommit_inode(inode, true);
1407 	if (ret == 0)
1408 		ret = _pnfs_return_layout(inode);
1409 	spin_lock(&inode->i_lock);
1410 	lo->plh_block_lgets--;
1411 	spin_unlock(&inode->i_lock);
1412 	pnfs_put_layout_hdr(lo);
1413 	return ret;
1414 }
1415 
1416 bool pnfs_roc(struct inode *ino,
1417 		struct nfs4_layoutreturn_args *args,
1418 		struct nfs4_layoutreturn_res *res,
1419 		const struct cred *cred)
1420 {
1421 	struct nfs_inode *nfsi = NFS_I(ino);
1422 	struct nfs_open_context *ctx;
1423 	struct nfs4_state *state;
1424 	struct pnfs_layout_hdr *lo;
1425 	struct pnfs_layout_segment *lseg, *next;
1426 	const struct cred *lc_cred;
1427 	nfs4_stateid stateid;
1428 	enum pnfs_iomode iomode = 0;
1429 	bool layoutreturn = false, roc = false;
1430 	bool skip_read = false;
1431 
1432 	if (!nfs_have_layout(ino))
1433 		return false;
1434 retry:
1435 	rcu_read_lock();
1436 	spin_lock(&ino->i_lock);
1437 	lo = nfsi->layout;
1438 	if (!lo || !pnfs_layout_is_valid(lo) ||
1439 	    test_bit(NFS_LAYOUT_BULK_RECALL, &lo->plh_flags)) {
1440 		lo = NULL;
1441 		goto out_noroc;
1442 	}
1443 	pnfs_get_layout_hdr(lo);
1444 	if (test_bit(NFS_LAYOUT_RETURN_LOCK, &lo->plh_flags)) {
1445 		spin_unlock(&ino->i_lock);
1446 		rcu_read_unlock();
1447 		wait_on_bit(&lo->plh_flags, NFS_LAYOUT_RETURN,
1448 				TASK_UNINTERRUPTIBLE);
1449 		pnfs_put_layout_hdr(lo);
1450 		goto retry;
1451 	}
1452 
1453 	/* no roc if we hold a delegation */
1454 	if (nfs4_check_delegation(ino, FMODE_READ)) {
1455 		if (nfs4_check_delegation(ino, FMODE_WRITE))
1456 			goto out_noroc;
1457 		skip_read = true;
1458 	}
1459 
1460 	list_for_each_entry_rcu(ctx, &nfsi->open_files, list) {
1461 		state = ctx->state;
1462 		if (state == NULL)
1463 			continue;
1464 		/* Don't return layout if there is open file state */
1465 		if (state->state & FMODE_WRITE)
1466 			goto out_noroc;
1467 		if (state->state & FMODE_READ)
1468 			skip_read = true;
1469 	}
1470 
1471 
1472 	list_for_each_entry_safe(lseg, next, &lo->plh_segs, pls_list) {
1473 		if (skip_read && lseg->pls_range.iomode == IOMODE_READ)
1474 			continue;
1475 		/* If we are sending layoutreturn, invalidate all valid lsegs */
1476 		if (!test_and_clear_bit(NFS_LSEG_ROC, &lseg->pls_flags))
1477 			continue;
1478 		/*
1479 		 * Note: mark lseg for return so pnfs_layout_remove_lseg
1480 		 * doesn't invalidate the layout for us.
1481 		 */
1482 		set_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags);
1483 		if (!mark_lseg_invalid(lseg, &lo->plh_return_segs))
1484 			continue;
1485 		pnfs_set_plh_return_info(lo, lseg->pls_range.iomode, 0);
1486 	}
1487 
1488 	if (!test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags))
1489 		goto out_noroc;
1490 
1491 	/* ROC in two conditions:
1492 	 * 1. there are ROC lsegs
1493 	 * 2. we don't send layoutreturn
1494 	 */
1495 	/* lo ref dropped in pnfs_roc_release() */
1496 	layoutreturn = pnfs_prepare_layoutreturn(lo, &stateid, &lc_cred, &iomode);
1497 	/* If the creds don't match, we can't compound the layoutreturn */
1498 	if (!layoutreturn || cred_fscmp(cred, lc_cred) != 0)
1499 		goto out_noroc;
1500 
1501 	roc = layoutreturn;
1502 	pnfs_init_layoutreturn_args(args, lo, &stateid, iomode);
1503 	res->lrs_present = 0;
1504 	layoutreturn = false;
1505 	put_cred(lc_cred);
1506 
1507 out_noroc:
1508 	spin_unlock(&ino->i_lock);
1509 	rcu_read_unlock();
1510 	pnfs_layoutcommit_inode(ino, true);
1511 	if (roc) {
1512 		struct pnfs_layoutdriver_type *ld = NFS_SERVER(ino)->pnfs_curr_ld;
1513 		if (ld->prepare_layoutreturn)
1514 			ld->prepare_layoutreturn(args);
1515 		pnfs_put_layout_hdr(lo);
1516 		return true;
1517 	}
1518 	if (layoutreturn)
1519 		pnfs_send_layoutreturn(lo, &stateid, &lc_cred, iomode, true);
1520 	pnfs_put_layout_hdr(lo);
1521 	return false;
1522 }
1523 
1524 int pnfs_roc_done(struct rpc_task *task, struct nfs4_layoutreturn_args **argpp,
1525 		  struct nfs4_layoutreturn_res **respp, int *ret)
1526 {
1527 	struct nfs4_layoutreturn_args *arg = *argpp;
1528 	int retval = -EAGAIN;
1529 
1530 	if (!arg)
1531 		return 0;
1532 	/* Handle Layoutreturn errors */
1533 	switch (*ret) {
1534 	case 0:
1535 		retval = 0;
1536 		break;
1537 	case -NFS4ERR_NOMATCHING_LAYOUT:
1538 		/* Was there an RPC level error? If not, retry */
1539 		if (task->tk_rpc_status == 0)
1540 			break;
1541 		/* If the call was not sent, let caller handle it */
1542 		if (!RPC_WAS_SENT(task))
1543 			return 0;
1544 		/*
1545 		 * Otherwise, assume the call succeeded and
1546 		 * that we need to release the layout
1547 		 */
1548 		*ret = 0;
1549 		(*respp)->lrs_present = 0;
1550 		retval = 0;
1551 		break;
1552 	case -NFS4ERR_DELAY:
1553 		/* Let the caller handle the retry */
1554 		*ret = -NFS4ERR_NOMATCHING_LAYOUT;
1555 		return 0;
1556 	case -NFS4ERR_OLD_STATEID:
1557 		if (!nfs4_layout_refresh_old_stateid(&arg->stateid,
1558 						     &arg->range, arg->inode))
1559 			break;
1560 		*ret = -NFS4ERR_NOMATCHING_LAYOUT;
1561 		return -EAGAIN;
1562 	}
1563 	*argpp = NULL;
1564 	*respp = NULL;
1565 	return retval;
1566 }
1567 
1568 void pnfs_roc_release(struct nfs4_layoutreturn_args *args,
1569 		struct nfs4_layoutreturn_res *res,
1570 		int ret)
1571 {
1572 	struct pnfs_layout_hdr *lo = args->layout;
1573 	struct inode *inode = args->inode;
1574 	const nfs4_stateid *res_stateid = NULL;
1575 	struct nfs4_xdr_opaque_data *ld_private = args->ld_private;
1576 
1577 	switch (ret) {
1578 	case -NFS4ERR_NOMATCHING_LAYOUT:
1579 		spin_lock(&inode->i_lock);
1580 		if (pnfs_layout_is_valid(lo) &&
1581 		    nfs4_stateid_match_other(&args->stateid, &lo->plh_stateid))
1582 			pnfs_set_plh_return_info(lo, args->range.iomode, 0);
1583 		pnfs_clear_layoutreturn_waitbit(lo);
1584 		spin_unlock(&inode->i_lock);
1585 		break;
1586 	case 0:
1587 		if (res->lrs_present)
1588 			res_stateid = &res->stateid;
1589 		fallthrough;
1590 	default:
1591 		pnfs_layoutreturn_free_lsegs(lo, &args->stateid, &args->range,
1592 					     res_stateid);
1593 	}
1594 	trace_nfs4_layoutreturn_on_close(args->inode, &args->stateid, ret);
1595 	if (ld_private && ld_private->ops && ld_private->ops->free)
1596 		ld_private->ops->free(ld_private);
1597 	pnfs_put_layout_hdr(lo);
1598 }
1599 
1600 bool pnfs_wait_on_layoutreturn(struct inode *ino, struct rpc_task *task)
1601 {
1602 	struct nfs_inode *nfsi = NFS_I(ino);
1603         struct pnfs_layout_hdr *lo;
1604         bool sleep = false;
1605 
1606 	/* we might not have grabbed lo reference. so need to check under
1607 	 * i_lock */
1608         spin_lock(&ino->i_lock);
1609         lo = nfsi->layout;
1610         if (lo && test_bit(NFS_LAYOUT_RETURN, &lo->plh_flags)) {
1611                 rpc_sleep_on(&NFS_SERVER(ino)->roc_rpcwaitq, task, NULL);
1612                 sleep = true;
1613 	}
1614         spin_unlock(&ino->i_lock);
1615         return sleep;
1616 }
1617 
1618 /*
1619  * Compare two layout segments for sorting into layout cache.
1620  * We want to preferentially return RW over RO layouts, so ensure those
1621  * are seen first.
1622  */
1623 static s64
1624 pnfs_lseg_range_cmp(const struct pnfs_layout_range *l1,
1625 	   const struct pnfs_layout_range *l2)
1626 {
1627 	s64 d;
1628 
1629 	/* high offset > low offset */
1630 	d = l1->offset - l2->offset;
1631 	if (d)
1632 		return d;
1633 
1634 	/* short length > long length */
1635 	d = l2->length - l1->length;
1636 	if (d)
1637 		return d;
1638 
1639 	/* read > read/write */
1640 	return (int)(l1->iomode == IOMODE_READ) - (int)(l2->iomode == IOMODE_READ);
1641 }
1642 
1643 static bool
1644 pnfs_lseg_range_is_after(const struct pnfs_layout_range *l1,
1645 		const struct pnfs_layout_range *l2)
1646 {
1647 	return pnfs_lseg_range_cmp(l1, l2) > 0;
1648 }
1649 
1650 static bool
1651 pnfs_lseg_no_merge(struct pnfs_layout_segment *lseg,
1652 		struct pnfs_layout_segment *old)
1653 {
1654 	return false;
1655 }
1656 
1657 void
1658 pnfs_generic_layout_insert_lseg(struct pnfs_layout_hdr *lo,
1659 		   struct pnfs_layout_segment *lseg,
1660 		   bool (*is_after)(const struct pnfs_layout_range *,
1661 			   const struct pnfs_layout_range *),
1662 		   bool (*do_merge)(struct pnfs_layout_segment *,
1663 			   struct pnfs_layout_segment *),
1664 		   struct list_head *free_me)
1665 {
1666 	struct pnfs_layout_segment *lp, *tmp;
1667 
1668 	dprintk("%s:Begin\n", __func__);
1669 
1670 	list_for_each_entry_safe(lp, tmp, &lo->plh_segs, pls_list) {
1671 		if (test_bit(NFS_LSEG_VALID, &lp->pls_flags) == 0)
1672 			continue;
1673 		if (do_merge(lseg, lp)) {
1674 			mark_lseg_invalid(lp, free_me);
1675 			continue;
1676 		}
1677 		if (is_after(&lseg->pls_range, &lp->pls_range))
1678 			continue;
1679 		list_add_tail(&lseg->pls_list, &lp->pls_list);
1680 		dprintk("%s: inserted lseg %p "
1681 			"iomode %d offset %llu length %llu before "
1682 			"lp %p iomode %d offset %llu length %llu\n",
1683 			__func__, lseg, lseg->pls_range.iomode,
1684 			lseg->pls_range.offset, lseg->pls_range.length,
1685 			lp, lp->pls_range.iomode, lp->pls_range.offset,
1686 			lp->pls_range.length);
1687 		goto out;
1688 	}
1689 	list_add_tail(&lseg->pls_list, &lo->plh_segs);
1690 	dprintk("%s: inserted lseg %p "
1691 		"iomode %d offset %llu length %llu at tail\n",
1692 		__func__, lseg, lseg->pls_range.iomode,
1693 		lseg->pls_range.offset, lseg->pls_range.length);
1694 out:
1695 	pnfs_get_layout_hdr(lo);
1696 
1697 	dprintk("%s:Return\n", __func__);
1698 }
1699 EXPORT_SYMBOL_GPL(pnfs_generic_layout_insert_lseg);
1700 
1701 static void
1702 pnfs_layout_insert_lseg(struct pnfs_layout_hdr *lo,
1703 		   struct pnfs_layout_segment *lseg,
1704 		   struct list_head *free_me)
1705 {
1706 	struct inode *inode = lo->plh_inode;
1707 	struct pnfs_layoutdriver_type *ld = NFS_SERVER(inode)->pnfs_curr_ld;
1708 
1709 	if (ld->add_lseg != NULL)
1710 		ld->add_lseg(lo, lseg, free_me);
1711 	else
1712 		pnfs_generic_layout_insert_lseg(lo, lseg,
1713 				pnfs_lseg_range_is_after,
1714 				pnfs_lseg_no_merge,
1715 				free_me);
1716 }
1717 
1718 static struct pnfs_layout_hdr *
1719 alloc_init_layout_hdr(struct inode *ino,
1720 		      struct nfs_open_context *ctx,
1721 		      gfp_t gfp_flags)
1722 {
1723 	struct pnfs_layout_hdr *lo;
1724 
1725 	lo = pnfs_alloc_layout_hdr(ino, gfp_flags);
1726 	if (!lo)
1727 		return NULL;
1728 	refcount_set(&lo->plh_refcount, 1);
1729 	INIT_LIST_HEAD(&lo->plh_layouts);
1730 	INIT_LIST_HEAD(&lo->plh_segs);
1731 	INIT_LIST_HEAD(&lo->plh_return_segs);
1732 	INIT_LIST_HEAD(&lo->plh_bulk_destroy);
1733 	lo->plh_inode = ino;
1734 	lo->plh_lc_cred = get_cred(ctx->cred);
1735 	lo->plh_flags |= 1 << NFS_LAYOUT_INVALID_STID;
1736 	return lo;
1737 }
1738 
1739 static struct pnfs_layout_hdr *
1740 pnfs_find_alloc_layout(struct inode *ino,
1741 		       struct nfs_open_context *ctx,
1742 		       gfp_t gfp_flags)
1743 	__releases(&ino->i_lock)
1744 	__acquires(&ino->i_lock)
1745 {
1746 	struct nfs_inode *nfsi = NFS_I(ino);
1747 	struct pnfs_layout_hdr *new = NULL;
1748 
1749 	dprintk("%s Begin ino=%p layout=%p\n", __func__, ino, nfsi->layout);
1750 
1751 	if (nfsi->layout != NULL)
1752 		goto out_existing;
1753 	spin_unlock(&ino->i_lock);
1754 	new = alloc_init_layout_hdr(ino, ctx, gfp_flags);
1755 	spin_lock(&ino->i_lock);
1756 
1757 	if (likely(nfsi->layout == NULL)) {	/* Won the race? */
1758 		nfsi->layout = new;
1759 		return new;
1760 	} else if (new != NULL)
1761 		pnfs_free_layout_hdr(new);
1762 out_existing:
1763 	pnfs_get_layout_hdr(nfsi->layout);
1764 	return nfsi->layout;
1765 }
1766 
1767 /*
1768  * iomode matching rules:
1769  * iomode	lseg	strict match
1770  *                      iomode
1771  * -----	-----	------ -----
1772  * ANY		READ	N/A    true
1773  * ANY		RW	N/A    true
1774  * RW		READ	N/A    false
1775  * RW		RW	N/A    true
1776  * READ		READ	N/A    true
1777  * READ		RW	true   false
1778  * READ		RW	false  true
1779  */
1780 static bool
1781 pnfs_lseg_range_match(const struct pnfs_layout_range *ls_range,
1782 		 const struct pnfs_layout_range *range,
1783 		 bool strict_iomode)
1784 {
1785 	struct pnfs_layout_range range1;
1786 
1787 	if ((range->iomode == IOMODE_RW &&
1788 	     ls_range->iomode != IOMODE_RW) ||
1789 	    (range->iomode != ls_range->iomode &&
1790 	     strict_iomode) ||
1791 	    !pnfs_lseg_range_intersecting(ls_range, range))
1792 		return false;
1793 
1794 	/* range1 covers only the first byte in the range */
1795 	range1 = *range;
1796 	range1.length = 1;
1797 	return pnfs_lseg_range_contained(ls_range, &range1);
1798 }
1799 
1800 /*
1801  * lookup range in layout
1802  */
1803 static struct pnfs_layout_segment *
1804 pnfs_find_lseg(struct pnfs_layout_hdr *lo,
1805 		struct pnfs_layout_range *range,
1806 		bool strict_iomode)
1807 {
1808 	struct pnfs_layout_segment *lseg, *ret = NULL;
1809 
1810 	dprintk("%s:Begin\n", __func__);
1811 
1812 	list_for_each_entry(lseg, &lo->plh_segs, pls_list) {
1813 		if (test_bit(NFS_LSEG_VALID, &lseg->pls_flags) &&
1814 		    pnfs_lseg_range_match(&lseg->pls_range, range,
1815 					  strict_iomode)) {
1816 			ret = pnfs_get_lseg(lseg);
1817 			break;
1818 		}
1819 	}
1820 
1821 	dprintk("%s:Return lseg %p ref %d\n",
1822 		__func__, ret, ret ? refcount_read(&ret->pls_refcount) : 0);
1823 	return ret;
1824 }
1825 
1826 /*
1827  * Use mdsthreshold hints set at each OPEN to determine if I/O should go
1828  * to the MDS or over pNFS
1829  *
1830  * The nfs_inode read_io and write_io fields are cumulative counters reset
1831  * when there are no layout segments. Note that in pnfs_update_layout iomode
1832  * is set to IOMODE_READ for a READ request, and set to IOMODE_RW for a
1833  * WRITE request.
1834  *
1835  * A return of true means use MDS I/O.
1836  *
1837  * From rfc 5661:
1838  * If a file's size is smaller than the file size threshold, data accesses
1839  * SHOULD be sent to the metadata server.  If an I/O request has a length that
1840  * is below the I/O size threshold, the I/O SHOULD be sent to the metadata
1841  * server.  If both file size and I/O size are provided, the client SHOULD
1842  * reach or exceed  both thresholds before sending its read or write
1843  * requests to the data server.
1844  */
1845 static bool pnfs_within_mdsthreshold(struct nfs_open_context *ctx,
1846 				     struct inode *ino, int iomode)
1847 {
1848 	struct nfs4_threshold *t = ctx->mdsthreshold;
1849 	struct nfs_inode *nfsi = NFS_I(ino);
1850 	loff_t fsize = i_size_read(ino);
1851 	bool size = false, size_set = false, io = false, io_set = false, ret = false;
1852 
1853 	if (t == NULL)
1854 		return ret;
1855 
1856 	dprintk("%s bm=0x%x rd_sz=%llu wr_sz=%llu rd_io=%llu wr_io=%llu\n",
1857 		__func__, t->bm, t->rd_sz, t->wr_sz, t->rd_io_sz, t->wr_io_sz);
1858 
1859 	switch (iomode) {
1860 	case IOMODE_READ:
1861 		if (t->bm & THRESHOLD_RD) {
1862 			dprintk("%s fsize %llu\n", __func__, fsize);
1863 			size_set = true;
1864 			if (fsize < t->rd_sz)
1865 				size = true;
1866 		}
1867 		if (t->bm & THRESHOLD_RD_IO) {
1868 			dprintk("%s nfsi->read_io %llu\n", __func__,
1869 				nfsi->read_io);
1870 			io_set = true;
1871 			if (nfsi->read_io < t->rd_io_sz)
1872 				io = true;
1873 		}
1874 		break;
1875 	case IOMODE_RW:
1876 		if (t->bm & THRESHOLD_WR) {
1877 			dprintk("%s fsize %llu\n", __func__, fsize);
1878 			size_set = true;
1879 			if (fsize < t->wr_sz)
1880 				size = true;
1881 		}
1882 		if (t->bm & THRESHOLD_WR_IO) {
1883 			dprintk("%s nfsi->write_io %llu\n", __func__,
1884 				nfsi->write_io);
1885 			io_set = true;
1886 			if (nfsi->write_io < t->wr_io_sz)
1887 				io = true;
1888 		}
1889 		break;
1890 	}
1891 	if (size_set && io_set) {
1892 		if (size && io)
1893 			ret = true;
1894 	} else if (size || io)
1895 		ret = true;
1896 
1897 	dprintk("<-- %s size %d io %d ret %d\n", __func__, size, io, ret);
1898 	return ret;
1899 }
1900 
1901 static int pnfs_prepare_to_retry_layoutget(struct pnfs_layout_hdr *lo)
1902 {
1903 	/*
1904 	 * send layoutcommit as it can hold up layoutreturn due to lseg
1905 	 * reference
1906 	 */
1907 	pnfs_layoutcommit_inode(lo->plh_inode, false);
1908 	return wait_on_bit_action(&lo->plh_flags, NFS_LAYOUT_RETURN,
1909 				   nfs_wait_bit_killable,
1910 				   TASK_KILLABLE);
1911 }
1912 
1913 static void nfs_layoutget_begin(struct pnfs_layout_hdr *lo)
1914 {
1915 	atomic_inc(&lo->plh_outstanding);
1916 }
1917 
1918 static void nfs_layoutget_end(struct pnfs_layout_hdr *lo)
1919 {
1920 	if (atomic_dec_and_test(&lo->plh_outstanding))
1921 		wake_up_var(&lo->plh_outstanding);
1922 }
1923 
1924 static bool pnfs_is_first_layoutget(struct pnfs_layout_hdr *lo)
1925 {
1926 	return test_bit(NFS_LAYOUT_FIRST_LAYOUTGET, &lo->plh_flags);
1927 }
1928 
1929 static void pnfs_clear_first_layoutget(struct pnfs_layout_hdr *lo)
1930 {
1931 	unsigned long *bitlock = &lo->plh_flags;
1932 
1933 	clear_bit_unlock(NFS_LAYOUT_FIRST_LAYOUTGET, bitlock);
1934 	smp_mb__after_atomic();
1935 	wake_up_bit(bitlock, NFS_LAYOUT_FIRST_LAYOUTGET);
1936 }
1937 
1938 static void _add_to_server_list(struct pnfs_layout_hdr *lo,
1939 				struct nfs_server *server)
1940 {
1941 	if (!test_and_set_bit(NFS_LAYOUT_HASHED, &lo->plh_flags)) {
1942 		struct nfs_client *clp = server->nfs_client;
1943 
1944 		/* The lo must be on the clp list if there is any
1945 		 * chance of a CB_LAYOUTRECALL(FILE) coming in.
1946 		 */
1947 		spin_lock(&clp->cl_lock);
1948 		list_add_tail_rcu(&lo->plh_layouts, &server->layouts);
1949 		spin_unlock(&clp->cl_lock);
1950 	}
1951 }
1952 
1953 /*
1954  * Layout segment is retreived from the server if not cached.
1955  * The appropriate layout segment is referenced and returned to the caller.
1956  */
1957 struct pnfs_layout_segment *
1958 pnfs_update_layout(struct inode *ino,
1959 		   struct nfs_open_context *ctx,
1960 		   loff_t pos,
1961 		   u64 count,
1962 		   enum pnfs_iomode iomode,
1963 		   bool strict_iomode,
1964 		   gfp_t gfp_flags)
1965 {
1966 	struct pnfs_layout_range arg = {
1967 		.iomode = iomode,
1968 		.offset = pos,
1969 		.length = count,
1970 	};
1971 	unsigned pg_offset;
1972 	struct nfs_server *server = NFS_SERVER(ino);
1973 	struct nfs_client *clp = server->nfs_client;
1974 	struct pnfs_layout_hdr *lo = NULL;
1975 	struct pnfs_layout_segment *lseg = NULL;
1976 	struct nfs4_layoutget *lgp;
1977 	nfs4_stateid stateid;
1978 	long timeout = 0;
1979 	unsigned long giveup = jiffies + (clp->cl_lease_time << 1);
1980 	bool first;
1981 
1982 	if (!pnfs_enabled_sb(NFS_SERVER(ino))) {
1983 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1984 				 PNFS_UPDATE_LAYOUT_NO_PNFS);
1985 		goto out;
1986 	}
1987 
1988 	if (pnfs_within_mdsthreshold(ctx, ino, iomode)) {
1989 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
1990 				 PNFS_UPDATE_LAYOUT_MDSTHRESH);
1991 		goto out;
1992 	}
1993 
1994 lookup_again:
1995 	lseg = ERR_PTR(nfs4_client_recover_expired_lease(clp));
1996 	if (IS_ERR(lseg))
1997 		goto out;
1998 	first = false;
1999 	spin_lock(&ino->i_lock);
2000 	lo = pnfs_find_alloc_layout(ino, ctx, gfp_flags);
2001 	if (lo == NULL) {
2002 		spin_unlock(&ino->i_lock);
2003 		lseg = ERR_PTR(-ENOMEM);
2004 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2005 				 PNFS_UPDATE_LAYOUT_NOMEM);
2006 		goto out;
2007 	}
2008 
2009 	/* Do we even need to bother with this? */
2010 	if (test_bit(NFS_LAYOUT_BULK_RECALL, &lo->plh_flags)) {
2011 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2012 				 PNFS_UPDATE_LAYOUT_BULK_RECALL);
2013 		dprintk("%s matches recall, use MDS\n", __func__);
2014 		goto out_unlock;
2015 	}
2016 
2017 	/* if LAYOUTGET already failed once we don't try again */
2018 	if (pnfs_layout_io_test_failed(lo, iomode)) {
2019 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2020 				 PNFS_UPDATE_LAYOUT_IO_TEST_FAIL);
2021 		goto out_unlock;
2022 	}
2023 
2024 	/*
2025 	 * If the layout segment list is empty, but there are outstanding
2026 	 * layoutget calls, then they might be subject to a layoutrecall.
2027 	 */
2028 	if ((list_empty(&lo->plh_segs) || !pnfs_layout_is_valid(lo)) &&
2029 	    atomic_read(&lo->plh_outstanding) != 0) {
2030 		spin_unlock(&ino->i_lock);
2031 		lseg = ERR_PTR(wait_var_event_killable(&lo->plh_outstanding,
2032 					!atomic_read(&lo->plh_outstanding)));
2033 		if (IS_ERR(lseg))
2034 			goto out_put_layout_hdr;
2035 		pnfs_put_layout_hdr(lo);
2036 		goto lookup_again;
2037 	}
2038 
2039 	/*
2040 	 * Because we free lsegs when sending LAYOUTRETURN, we need to wait
2041 	 * for LAYOUTRETURN.
2042 	 */
2043 	if (test_bit(NFS_LAYOUT_RETURN, &lo->plh_flags)) {
2044 		spin_unlock(&ino->i_lock);
2045 		dprintk("%s wait for layoutreturn\n", __func__);
2046 		lseg = ERR_PTR(pnfs_prepare_to_retry_layoutget(lo));
2047 		if (!IS_ERR(lseg)) {
2048 			pnfs_put_layout_hdr(lo);
2049 			dprintk("%s retrying\n", __func__);
2050 			trace_pnfs_update_layout(ino, pos, count, iomode, lo,
2051 						 lseg,
2052 						 PNFS_UPDATE_LAYOUT_RETRY);
2053 			goto lookup_again;
2054 		}
2055 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2056 					 PNFS_UPDATE_LAYOUT_RETURN);
2057 		goto out_put_layout_hdr;
2058 	}
2059 
2060 	lseg = pnfs_find_lseg(lo, &arg, strict_iomode);
2061 	if (lseg) {
2062 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2063 				PNFS_UPDATE_LAYOUT_FOUND_CACHED);
2064 		goto out_unlock;
2065 	}
2066 
2067 	/*
2068 	 * Choose a stateid for the LAYOUTGET. If we don't have a layout
2069 	 * stateid, or it has been invalidated, then we must use the open
2070 	 * stateid.
2071 	 */
2072 	if (test_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags)) {
2073 		int status;
2074 
2075 		/*
2076 		 * The first layoutget for the file. Need to serialize per
2077 		 * RFC 5661 Errata 3208.
2078 		 */
2079 		if (test_and_set_bit(NFS_LAYOUT_FIRST_LAYOUTGET,
2080 				     &lo->plh_flags)) {
2081 			spin_unlock(&ino->i_lock);
2082 			lseg = ERR_PTR(wait_on_bit(&lo->plh_flags,
2083 						NFS_LAYOUT_FIRST_LAYOUTGET,
2084 						TASK_KILLABLE));
2085 			if (IS_ERR(lseg))
2086 				goto out_put_layout_hdr;
2087 			pnfs_put_layout_hdr(lo);
2088 			dprintk("%s retrying\n", __func__);
2089 			goto lookup_again;
2090 		}
2091 
2092 		spin_unlock(&ino->i_lock);
2093 		first = true;
2094 		status = nfs4_select_rw_stateid(ctx->state,
2095 					iomode == IOMODE_RW ? FMODE_WRITE : FMODE_READ,
2096 					NULL, &stateid, NULL);
2097 		if (status != 0) {
2098 			lseg = ERR_PTR(status);
2099 			trace_pnfs_update_layout(ino, pos, count,
2100 					iomode, lo, lseg,
2101 					PNFS_UPDATE_LAYOUT_INVALID_OPEN);
2102 			nfs4_schedule_stateid_recovery(server, ctx->state);
2103 			pnfs_clear_first_layoutget(lo);
2104 			pnfs_put_layout_hdr(lo);
2105 			goto lookup_again;
2106 		}
2107 		spin_lock(&ino->i_lock);
2108 	} else {
2109 		nfs4_stateid_copy(&stateid, &lo->plh_stateid);
2110 	}
2111 
2112 	if (pnfs_layoutgets_blocked(lo)) {
2113 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2114 				PNFS_UPDATE_LAYOUT_BLOCKED);
2115 		goto out_unlock;
2116 	}
2117 	nfs_layoutget_begin(lo);
2118 	spin_unlock(&ino->i_lock);
2119 
2120 	_add_to_server_list(lo, server);
2121 
2122 	pg_offset = arg.offset & ~PAGE_MASK;
2123 	if (pg_offset) {
2124 		arg.offset -= pg_offset;
2125 		arg.length += pg_offset;
2126 	}
2127 	if (arg.length != NFS4_MAX_UINT64)
2128 		arg.length = PAGE_ALIGN(arg.length);
2129 
2130 	lgp = pnfs_alloc_init_layoutget_args(ino, ctx, &stateid, &arg, gfp_flags);
2131 	if (!lgp) {
2132 		lseg = ERR_PTR(-ENOMEM);
2133 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, NULL,
2134 					 PNFS_UPDATE_LAYOUT_NOMEM);
2135 		nfs_layoutget_end(lo);
2136 		goto out_put_layout_hdr;
2137 	}
2138 
2139 	lgp->lo = lo;
2140 	pnfs_get_layout_hdr(lo);
2141 
2142 	lseg = nfs4_proc_layoutget(lgp, &timeout);
2143 	trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2144 				 PNFS_UPDATE_LAYOUT_SEND_LAYOUTGET);
2145 	nfs_layoutget_end(lo);
2146 	if (IS_ERR(lseg)) {
2147 		switch(PTR_ERR(lseg)) {
2148 		case -EBUSY:
2149 			if (time_after(jiffies, giveup))
2150 				lseg = NULL;
2151 			break;
2152 		case -ERECALLCONFLICT:
2153 		case -EAGAIN:
2154 			break;
2155 		default:
2156 			if (!nfs_error_is_fatal(PTR_ERR(lseg))) {
2157 				pnfs_layout_clear_fail_bit(lo, pnfs_iomode_to_fail_bit(iomode));
2158 				lseg = NULL;
2159 			}
2160 			goto out_put_layout_hdr;
2161 		}
2162 		if (lseg) {
2163 			if (first)
2164 				pnfs_clear_first_layoutget(lo);
2165 			trace_pnfs_update_layout(ino, pos, count,
2166 				iomode, lo, lseg, PNFS_UPDATE_LAYOUT_RETRY);
2167 			pnfs_put_layout_hdr(lo);
2168 			goto lookup_again;
2169 		}
2170 	} else {
2171 		pnfs_layout_clear_fail_bit(lo, pnfs_iomode_to_fail_bit(iomode));
2172 	}
2173 
2174 out_put_layout_hdr:
2175 	if (first)
2176 		pnfs_clear_first_layoutget(lo);
2177 	trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2178 				 PNFS_UPDATE_LAYOUT_EXIT);
2179 	pnfs_put_layout_hdr(lo);
2180 out:
2181 	dprintk("%s: inode %s/%llu pNFS layout segment %s for "
2182 			"(%s, offset: %llu, length: %llu)\n",
2183 			__func__, ino->i_sb->s_id,
2184 			(unsigned long long)NFS_FILEID(ino),
2185 			IS_ERR_OR_NULL(lseg) ? "not found" : "found",
2186 			iomode==IOMODE_RW ?  "read/write" : "read-only",
2187 			(unsigned long long)pos,
2188 			(unsigned long long)count);
2189 	return lseg;
2190 out_unlock:
2191 	spin_unlock(&ino->i_lock);
2192 	goto out_put_layout_hdr;
2193 }
2194 EXPORT_SYMBOL_GPL(pnfs_update_layout);
2195 
2196 static bool
2197 pnfs_sanity_check_layout_range(struct pnfs_layout_range *range)
2198 {
2199 	switch (range->iomode) {
2200 	case IOMODE_READ:
2201 	case IOMODE_RW:
2202 		break;
2203 	default:
2204 		return false;
2205 	}
2206 	if (range->offset == NFS4_MAX_UINT64)
2207 		return false;
2208 	if (range->length == 0)
2209 		return false;
2210 	if (range->length != NFS4_MAX_UINT64 &&
2211 	    range->length > NFS4_MAX_UINT64 - range->offset)
2212 		return false;
2213 	return true;
2214 }
2215 
2216 static struct pnfs_layout_hdr *
2217 _pnfs_grab_empty_layout(struct inode *ino, struct nfs_open_context *ctx)
2218 {
2219 	struct pnfs_layout_hdr *lo;
2220 
2221 	spin_lock(&ino->i_lock);
2222 	lo = pnfs_find_alloc_layout(ino, ctx, nfs_io_gfp_mask());
2223 	if (!lo)
2224 		goto out_unlock;
2225 	if (!test_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags))
2226 		goto out_unlock;
2227 	if (test_bit(NFS_LAYOUT_RETURN, &lo->plh_flags))
2228 		goto out_unlock;
2229 	if (pnfs_layoutgets_blocked(lo))
2230 		goto out_unlock;
2231 	if (test_and_set_bit(NFS_LAYOUT_FIRST_LAYOUTGET, &lo->plh_flags))
2232 		goto out_unlock;
2233 	nfs_layoutget_begin(lo);
2234 	spin_unlock(&ino->i_lock);
2235 	_add_to_server_list(lo, NFS_SERVER(ino));
2236 	return lo;
2237 
2238 out_unlock:
2239 	spin_unlock(&ino->i_lock);
2240 	pnfs_put_layout_hdr(lo);
2241 	return NULL;
2242 }
2243 
2244 static void _lgopen_prepare_attached(struct nfs4_opendata *data,
2245 				     struct nfs_open_context *ctx)
2246 {
2247 	struct inode *ino = data->dentry->d_inode;
2248 	struct pnfs_layout_range rng = {
2249 		.iomode = (data->o_arg.fmode & FMODE_WRITE) ?
2250 			  IOMODE_RW: IOMODE_READ,
2251 		.offset = 0,
2252 		.length = NFS4_MAX_UINT64,
2253 	};
2254 	struct nfs4_layoutget *lgp;
2255 	struct pnfs_layout_hdr *lo;
2256 
2257 	/* Heuristic: don't send layoutget if we have cached data */
2258 	if (rng.iomode == IOMODE_READ &&
2259 	   (i_size_read(ino) == 0 || ino->i_mapping->nrpages != 0))
2260 		return;
2261 
2262 	lo = _pnfs_grab_empty_layout(ino, ctx);
2263 	if (!lo)
2264 		return;
2265 	lgp = pnfs_alloc_init_layoutget_args(ino, ctx, &current_stateid, &rng,
2266 					     nfs_io_gfp_mask());
2267 	if (!lgp) {
2268 		pnfs_clear_first_layoutget(lo);
2269 		nfs_layoutget_end(lo);
2270 		pnfs_put_layout_hdr(lo);
2271 		return;
2272 	}
2273 	lgp->lo = lo;
2274 	data->lgp = lgp;
2275 	data->o_arg.lg_args = &lgp->args;
2276 	data->o_res.lg_res = &lgp->res;
2277 }
2278 
2279 static void _lgopen_prepare_floating(struct nfs4_opendata *data,
2280 				     struct nfs_open_context *ctx)
2281 {
2282 	struct inode *ino = data->dentry->d_inode;
2283 	struct pnfs_layout_range rng = {
2284 		.iomode = (data->o_arg.fmode & FMODE_WRITE) ?
2285 			  IOMODE_RW: IOMODE_READ,
2286 		.offset = 0,
2287 		.length = NFS4_MAX_UINT64,
2288 	};
2289 	struct nfs4_layoutget *lgp;
2290 
2291 	lgp = pnfs_alloc_init_layoutget_args(ino, ctx, &current_stateid, &rng,
2292 					     nfs_io_gfp_mask());
2293 	if (!lgp)
2294 		return;
2295 	data->lgp = lgp;
2296 	data->o_arg.lg_args = &lgp->args;
2297 	data->o_res.lg_res = &lgp->res;
2298 }
2299 
2300 void pnfs_lgopen_prepare(struct nfs4_opendata *data,
2301 			 struct nfs_open_context *ctx)
2302 {
2303 	struct nfs_server *server = NFS_SERVER(data->dir->d_inode);
2304 
2305 	if (!(pnfs_enabled_sb(server) &&
2306 	      server->pnfs_curr_ld->flags & PNFS_LAYOUTGET_ON_OPEN))
2307 		return;
2308 	/* Could check on max_ops, but currently hardcoded high enough */
2309 	if (!nfs_server_capable(data->dir->d_inode, NFS_CAP_LGOPEN))
2310 		return;
2311 	if (data->lgp)
2312 		return;
2313 	if (data->state)
2314 		_lgopen_prepare_attached(data, ctx);
2315 	else
2316 		_lgopen_prepare_floating(data, ctx);
2317 }
2318 
2319 void pnfs_parse_lgopen(struct inode *ino, struct nfs4_layoutget *lgp,
2320 		       struct nfs_open_context *ctx)
2321 {
2322 	struct pnfs_layout_hdr *lo;
2323 	struct pnfs_layout_segment *lseg;
2324 	struct nfs_server *srv = NFS_SERVER(ino);
2325 	u32 iomode;
2326 
2327 	if (!lgp)
2328 		return;
2329 	dprintk("%s: entered with status %i\n", __func__, lgp->res.status);
2330 	if (lgp->res.status) {
2331 		switch (lgp->res.status) {
2332 		default:
2333 			break;
2334 		/*
2335 		 * Halt lgopen attempts if the server doesn't recognise
2336 		 * the "current stateid" value, the layout type, or the
2337 		 * layoutget operation as being valid.
2338 		 * Also if it complains about too many ops in the compound
2339 		 * or of the request/reply being too big.
2340 		 */
2341 		case -NFS4ERR_BAD_STATEID:
2342 		case -NFS4ERR_NOTSUPP:
2343 		case -NFS4ERR_REP_TOO_BIG:
2344 		case -NFS4ERR_REP_TOO_BIG_TO_CACHE:
2345 		case -NFS4ERR_REQ_TOO_BIG:
2346 		case -NFS4ERR_TOO_MANY_OPS:
2347 		case -NFS4ERR_UNKNOWN_LAYOUTTYPE:
2348 			srv->caps &= ~NFS_CAP_LGOPEN;
2349 		}
2350 		return;
2351 	}
2352 	if (!lgp->lo) {
2353 		lo = _pnfs_grab_empty_layout(ino, ctx);
2354 		if (!lo)
2355 			return;
2356 		lgp->lo = lo;
2357 	} else
2358 		lo = lgp->lo;
2359 
2360 	lseg = pnfs_layout_process(lgp);
2361 	if (!IS_ERR(lseg)) {
2362 		iomode = lgp->args.range.iomode;
2363 		pnfs_layout_clear_fail_bit(lo, pnfs_iomode_to_fail_bit(iomode));
2364 		pnfs_put_lseg(lseg);
2365 	}
2366 }
2367 
2368 void nfs4_lgopen_release(struct nfs4_layoutget *lgp)
2369 {
2370 	if (lgp != NULL) {
2371 		if (lgp->lo) {
2372 			pnfs_clear_first_layoutget(lgp->lo);
2373 			nfs_layoutget_end(lgp->lo);
2374 		}
2375 		pnfs_layoutget_free(lgp);
2376 	}
2377 }
2378 
2379 struct pnfs_layout_segment *
2380 pnfs_layout_process(struct nfs4_layoutget *lgp)
2381 {
2382 	struct pnfs_layout_hdr *lo = lgp->lo;
2383 	struct nfs4_layoutget_res *res = &lgp->res;
2384 	struct pnfs_layout_segment *lseg;
2385 	struct inode *ino = lo->plh_inode;
2386 	LIST_HEAD(free_me);
2387 
2388 	if (!pnfs_sanity_check_layout_range(&res->range))
2389 		return ERR_PTR(-EINVAL);
2390 
2391 	/* Inject layout blob into I/O device driver */
2392 	lseg = NFS_SERVER(ino)->pnfs_curr_ld->alloc_lseg(lo, res, lgp->gfp_flags);
2393 	if (IS_ERR_OR_NULL(lseg)) {
2394 		if (!lseg)
2395 			lseg = ERR_PTR(-ENOMEM);
2396 
2397 		dprintk("%s: Could not allocate layout: error %ld\n",
2398 		       __func__, PTR_ERR(lseg));
2399 		return lseg;
2400 	}
2401 
2402 	pnfs_init_lseg(lo, lseg, &res->range, &res->stateid);
2403 
2404 	spin_lock(&ino->i_lock);
2405 	if (pnfs_layoutgets_blocked(lo)) {
2406 		dprintk("%s forget reply due to state\n", __func__);
2407 		goto out_forget;
2408 	}
2409 
2410 	if (!pnfs_layout_is_valid(lo) && !pnfs_is_first_layoutget(lo))
2411 		goto out_forget;
2412 
2413 	if (nfs4_stateid_match_other(&lo->plh_stateid, &res->stateid)) {
2414 		/* existing state ID, make sure the sequence number matches. */
2415 		if (pnfs_layout_stateid_blocked(lo, &res->stateid)) {
2416 			if (!pnfs_layout_is_valid(lo))
2417 				lo->plh_barrier = 0;
2418 			dprintk("%s forget reply due to sequence\n", __func__);
2419 			goto out_forget;
2420 		}
2421 		pnfs_set_layout_stateid(lo, &res->stateid, lgp->cred, false);
2422 	} else if (pnfs_layout_is_valid(lo)) {
2423 		/*
2424 		 * We got an entirely new state ID.  Mark all segments for the
2425 		 * inode invalid, and retry the layoutget
2426 		 */
2427 		struct pnfs_layout_range range = {
2428 			.iomode = IOMODE_ANY,
2429 			.length = NFS4_MAX_UINT64,
2430 		};
2431 		pnfs_mark_matching_lsegs_return(lo, &free_me, &range, 0);
2432 		goto out_forget;
2433 	} else {
2434 		/* We have a completely new layout */
2435 		pnfs_set_layout_stateid(lo, &res->stateid, lgp->cred, true);
2436 	}
2437 
2438 	pnfs_get_lseg(lseg);
2439 	pnfs_layout_insert_lseg(lo, lseg, &free_me);
2440 
2441 
2442 	if (res->return_on_close)
2443 		set_bit(NFS_LSEG_ROC, &lseg->pls_flags);
2444 
2445 	spin_unlock(&ino->i_lock);
2446 	pnfs_free_lseg_list(&free_me);
2447 	return lseg;
2448 
2449 out_forget:
2450 	spin_unlock(&ino->i_lock);
2451 	lseg->pls_layout = lo;
2452 	NFS_SERVER(ino)->pnfs_curr_ld->free_lseg(lseg);
2453 	return ERR_PTR(-EAGAIN);
2454 }
2455 
2456 /**
2457  * pnfs_mark_matching_lsegs_return - Free or return matching layout segments
2458  * @lo: pointer to layout header
2459  * @tmp_list: list header to be used with pnfs_free_lseg_list()
2460  * @return_range: describe layout segment ranges to be returned
2461  * @seq: stateid seqid to match
2462  *
2463  * This function is mainly intended for use by layoutrecall. It attempts
2464  * to free the layout segment immediately, or else to mark it for return
2465  * as soon as its reference count drops to zero.
2466  *
2467  * Returns
2468  * - 0: a layoutreturn needs to be scheduled.
2469  * - EBUSY: there are layout segment that are still in use.
2470  * - ENOENT: there are no layout segments that need to be returned.
2471  */
2472 int
2473 pnfs_mark_matching_lsegs_return(struct pnfs_layout_hdr *lo,
2474 				struct list_head *tmp_list,
2475 				const struct pnfs_layout_range *return_range,
2476 				u32 seq)
2477 {
2478 	struct pnfs_layout_segment *lseg, *next;
2479 	int remaining = 0;
2480 
2481 	dprintk("%s:Begin lo %p\n", __func__, lo);
2482 
2483 	assert_spin_locked(&lo->plh_inode->i_lock);
2484 
2485 	if (test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags))
2486 		tmp_list = &lo->plh_return_segs;
2487 
2488 	list_for_each_entry_safe(lseg, next, &lo->plh_segs, pls_list)
2489 		if (pnfs_match_lseg_recall(lseg, return_range, seq)) {
2490 			dprintk("%s: marking lseg %p iomode %d "
2491 				"offset %llu length %llu\n", __func__,
2492 				lseg, lseg->pls_range.iomode,
2493 				lseg->pls_range.offset,
2494 				lseg->pls_range.length);
2495 			if (test_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags))
2496 				tmp_list = &lo->plh_return_segs;
2497 			if (mark_lseg_invalid(lseg, tmp_list))
2498 				continue;
2499 			remaining++;
2500 			set_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags);
2501 		}
2502 
2503 	if (remaining) {
2504 		pnfs_set_plh_return_info(lo, return_range->iomode, seq);
2505 		return -EBUSY;
2506 	}
2507 
2508 	if (!list_empty(&lo->plh_return_segs)) {
2509 		pnfs_set_plh_return_info(lo, return_range->iomode, seq);
2510 		return 0;
2511 	}
2512 
2513 	return -ENOENT;
2514 }
2515 
2516 static void
2517 pnfs_mark_layout_for_return(struct inode *inode,
2518 			    const struct pnfs_layout_range *range)
2519 {
2520 	struct pnfs_layout_hdr *lo;
2521 	bool return_now = false;
2522 
2523 	spin_lock(&inode->i_lock);
2524 	lo = NFS_I(inode)->layout;
2525 	if (!pnfs_layout_is_valid(lo)) {
2526 		spin_unlock(&inode->i_lock);
2527 		return;
2528 	}
2529 	pnfs_set_plh_return_info(lo, range->iomode, 0);
2530 	/*
2531 	 * mark all matching lsegs so that we are sure to have no live
2532 	 * segments at hand when sending layoutreturn. See pnfs_put_lseg()
2533 	 * for how it works.
2534 	 */
2535 	if (pnfs_mark_matching_lsegs_return(lo, &lo->plh_return_segs, range, 0) != -EBUSY) {
2536 		const struct cred *cred;
2537 		nfs4_stateid stateid;
2538 		enum pnfs_iomode iomode;
2539 
2540 		return_now = pnfs_prepare_layoutreturn(lo, &stateid, &cred, &iomode);
2541 		spin_unlock(&inode->i_lock);
2542 		if (return_now)
2543 			pnfs_send_layoutreturn(lo, &stateid, &cred, iomode, false);
2544 	} else {
2545 		spin_unlock(&inode->i_lock);
2546 		nfs_commit_inode(inode, 0);
2547 	}
2548 }
2549 
2550 void pnfs_error_mark_layout_for_return(struct inode *inode,
2551 				       struct pnfs_layout_segment *lseg)
2552 {
2553 	struct pnfs_layout_range range = {
2554 		.iomode = lseg->pls_range.iomode,
2555 		.offset = 0,
2556 		.length = NFS4_MAX_UINT64,
2557 	};
2558 
2559 	pnfs_mark_layout_for_return(inode, &range);
2560 }
2561 EXPORT_SYMBOL_GPL(pnfs_error_mark_layout_for_return);
2562 
2563 static bool
2564 pnfs_layout_can_be_returned(struct pnfs_layout_hdr *lo)
2565 {
2566 	return pnfs_layout_is_valid(lo) &&
2567 		!test_bit(NFS_LAYOUT_INODE_FREEING, &lo->plh_flags) &&
2568 		!test_bit(NFS_LAYOUT_RETURN, &lo->plh_flags);
2569 }
2570 
2571 static struct pnfs_layout_segment *
2572 pnfs_find_first_lseg(struct pnfs_layout_hdr *lo,
2573 		     const struct pnfs_layout_range *range,
2574 		     enum pnfs_iomode iomode)
2575 {
2576 	struct pnfs_layout_segment *lseg;
2577 
2578 	list_for_each_entry(lseg, &lo->plh_segs, pls_list) {
2579 		if (!test_bit(NFS_LSEG_VALID, &lseg->pls_flags))
2580 			continue;
2581 		if (test_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags))
2582 			continue;
2583 		if (lseg->pls_range.iomode != iomode && iomode != IOMODE_ANY)
2584 			continue;
2585 		if (pnfs_lseg_range_intersecting(&lseg->pls_range, range))
2586 			return lseg;
2587 	}
2588 	return NULL;
2589 }
2590 
2591 /* Find open file states whose mode matches that of the range */
2592 static bool
2593 pnfs_should_return_unused_layout(struct pnfs_layout_hdr *lo,
2594 				 const struct pnfs_layout_range *range)
2595 {
2596 	struct list_head *head;
2597 	struct nfs_open_context *ctx;
2598 	fmode_t mode = 0;
2599 
2600 	if (!pnfs_layout_can_be_returned(lo) ||
2601 	    !pnfs_find_first_lseg(lo, range, range->iomode))
2602 		return false;
2603 
2604 	head = &NFS_I(lo->plh_inode)->open_files;
2605 	list_for_each_entry_rcu(ctx, head, list) {
2606 		if (ctx->state)
2607 			mode |= ctx->state->state & (FMODE_READ|FMODE_WRITE);
2608 	}
2609 
2610 	switch (range->iomode) {
2611 	default:
2612 		break;
2613 	case IOMODE_READ:
2614 		mode &= ~FMODE_WRITE;
2615 		break;
2616 	case IOMODE_RW:
2617 		if (pnfs_find_first_lseg(lo, range, IOMODE_READ))
2618 			mode &= ~FMODE_READ;
2619 	}
2620 	return mode == 0;
2621 }
2622 
2623 static int
2624 pnfs_layout_return_unused_byserver(struct nfs_server *server, void *data)
2625 {
2626 	const struct pnfs_layout_range *range = data;
2627 	struct pnfs_layout_hdr *lo;
2628 	struct inode *inode;
2629 restart:
2630 	rcu_read_lock();
2631 	list_for_each_entry_rcu(lo, &server->layouts, plh_layouts) {
2632 		if (!pnfs_layout_can_be_returned(lo) ||
2633 		    test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags))
2634 			continue;
2635 		inode = lo->plh_inode;
2636 		spin_lock(&inode->i_lock);
2637 		if (!pnfs_should_return_unused_layout(lo, range)) {
2638 			spin_unlock(&inode->i_lock);
2639 			continue;
2640 		}
2641 		spin_unlock(&inode->i_lock);
2642 		inode = pnfs_grab_inode_layout_hdr(lo);
2643 		if (!inode)
2644 			continue;
2645 		rcu_read_unlock();
2646 		pnfs_mark_layout_for_return(inode, range);
2647 		iput(inode);
2648 		cond_resched();
2649 		goto restart;
2650 	}
2651 	rcu_read_unlock();
2652 	return 0;
2653 }
2654 
2655 void
2656 pnfs_layout_return_unused_byclid(struct nfs_client *clp,
2657 				 enum pnfs_iomode iomode)
2658 {
2659 	struct pnfs_layout_range range = {
2660 		.iomode = iomode,
2661 		.offset = 0,
2662 		.length = NFS4_MAX_UINT64,
2663 	};
2664 
2665 	nfs_client_for_each_server(clp, pnfs_layout_return_unused_byserver,
2666 			&range);
2667 }
2668 
2669 void
2670 pnfs_generic_pg_check_layout(struct nfs_pageio_descriptor *pgio)
2671 {
2672 	if (pgio->pg_lseg == NULL ||
2673 	    test_bit(NFS_LSEG_VALID, &pgio->pg_lseg->pls_flags))
2674 		return;
2675 	pnfs_put_lseg(pgio->pg_lseg);
2676 	pgio->pg_lseg = NULL;
2677 }
2678 EXPORT_SYMBOL_GPL(pnfs_generic_pg_check_layout);
2679 
2680 /*
2681  * Check for any intersection between the request and the pgio->pg_lseg,
2682  * and if none, put this pgio->pg_lseg away.
2683  */
2684 void
2685 pnfs_generic_pg_check_range(struct nfs_pageio_descriptor *pgio, struct nfs_page *req)
2686 {
2687 	if (pgio->pg_lseg && !pnfs_lseg_request_intersecting(pgio->pg_lseg, req)) {
2688 		pnfs_put_lseg(pgio->pg_lseg);
2689 		pgio->pg_lseg = NULL;
2690 	}
2691 }
2692 EXPORT_SYMBOL_GPL(pnfs_generic_pg_check_range);
2693 
2694 void
2695 pnfs_generic_pg_init_read(struct nfs_pageio_descriptor *pgio, struct nfs_page *req)
2696 {
2697 	u64 rd_size;
2698 
2699 	pnfs_generic_pg_check_layout(pgio);
2700 	pnfs_generic_pg_check_range(pgio, req);
2701 	if (pgio->pg_lseg == NULL) {
2702 		if (pgio->pg_dreq == NULL)
2703 			rd_size = i_size_read(pgio->pg_inode) - req_offset(req);
2704 		else
2705 			rd_size = nfs_dreq_bytes_left(pgio->pg_dreq);
2706 
2707 		pgio->pg_lseg =
2708 			pnfs_update_layout(pgio->pg_inode, nfs_req_openctx(req),
2709 					   req_offset(req), rd_size,
2710 					   IOMODE_READ, false,
2711 					   nfs_io_gfp_mask());
2712 		if (IS_ERR(pgio->pg_lseg)) {
2713 			pgio->pg_error = PTR_ERR(pgio->pg_lseg);
2714 			pgio->pg_lseg = NULL;
2715 			return;
2716 		}
2717 	}
2718 	/* If no lseg, fall back to read through mds */
2719 	if (pgio->pg_lseg == NULL)
2720 		nfs_pageio_reset_read_mds(pgio);
2721 
2722 }
2723 EXPORT_SYMBOL_GPL(pnfs_generic_pg_init_read);
2724 
2725 void
2726 pnfs_generic_pg_init_write(struct nfs_pageio_descriptor *pgio,
2727 			   struct nfs_page *req, u64 wb_size)
2728 {
2729 	pnfs_generic_pg_check_layout(pgio);
2730 	pnfs_generic_pg_check_range(pgio, req);
2731 	if (pgio->pg_lseg == NULL) {
2732 		pgio->pg_lseg =
2733 			pnfs_update_layout(pgio->pg_inode, nfs_req_openctx(req),
2734 					   req_offset(req), wb_size, IOMODE_RW,
2735 					   false, nfs_io_gfp_mask());
2736 		if (IS_ERR(pgio->pg_lseg)) {
2737 			pgio->pg_error = PTR_ERR(pgio->pg_lseg);
2738 			pgio->pg_lseg = NULL;
2739 			return;
2740 		}
2741 	}
2742 	/* If no lseg, fall back to write through mds */
2743 	if (pgio->pg_lseg == NULL)
2744 		nfs_pageio_reset_write_mds(pgio);
2745 }
2746 EXPORT_SYMBOL_GPL(pnfs_generic_pg_init_write);
2747 
2748 void
2749 pnfs_generic_pg_cleanup(struct nfs_pageio_descriptor *desc)
2750 {
2751 	if (desc->pg_lseg) {
2752 		pnfs_put_lseg(desc->pg_lseg);
2753 		desc->pg_lseg = NULL;
2754 	}
2755 }
2756 EXPORT_SYMBOL_GPL(pnfs_generic_pg_cleanup);
2757 
2758 /*
2759  * Return 0 if @req cannot be coalesced into @pgio, otherwise return the number
2760  * of bytes (maximum @req->wb_bytes) that can be coalesced.
2761  */
2762 size_t
2763 pnfs_generic_pg_test(struct nfs_pageio_descriptor *pgio,
2764 		     struct nfs_page *prev, struct nfs_page *req)
2765 {
2766 	unsigned int size;
2767 	u64 seg_end, req_start, seg_left;
2768 
2769 	size = nfs_generic_pg_test(pgio, prev, req);
2770 	if (!size)
2771 		return 0;
2772 
2773 	/*
2774 	 * 'size' contains the number of bytes left in the current page (up
2775 	 * to the original size asked for in @req->wb_bytes).
2776 	 *
2777 	 * Calculate how many bytes are left in the layout segment
2778 	 * and if there are less bytes than 'size', return that instead.
2779 	 *
2780 	 * Please also note that 'end_offset' is actually the offset of the
2781 	 * first byte that lies outside the pnfs_layout_range. FIXME?
2782 	 *
2783 	 */
2784 	if (pgio->pg_lseg) {
2785 		seg_end = pnfs_end_offset(pgio->pg_lseg->pls_range.offset,
2786 				     pgio->pg_lseg->pls_range.length);
2787 		req_start = req_offset(req);
2788 
2789 		/* start of request is past the last byte of this segment */
2790 		if (req_start >= seg_end)
2791 			return 0;
2792 
2793 		/* adjust 'size' iff there are fewer bytes left in the
2794 		 * segment than what nfs_generic_pg_test returned */
2795 		seg_left = seg_end - req_start;
2796 		if (seg_left < size)
2797 			size = (unsigned int)seg_left;
2798 	}
2799 
2800 	return size;
2801 }
2802 EXPORT_SYMBOL_GPL(pnfs_generic_pg_test);
2803 
2804 int pnfs_write_done_resend_to_mds(struct nfs_pgio_header *hdr)
2805 {
2806 	struct nfs_pageio_descriptor pgio;
2807 
2808 	/* Resend all requests through the MDS */
2809 	nfs_pageio_init_write(&pgio, hdr->inode, FLUSH_STABLE, true,
2810 			      hdr->completion_ops);
2811 	set_bit(NFS_CONTEXT_RESEND_WRITES, &hdr->args.context->flags);
2812 	return nfs_pageio_resend(&pgio, hdr);
2813 }
2814 EXPORT_SYMBOL_GPL(pnfs_write_done_resend_to_mds);
2815 
2816 static void pnfs_ld_handle_write_error(struct nfs_pgio_header *hdr)
2817 {
2818 
2819 	dprintk("pnfs write error = %d\n", hdr->pnfs_error);
2820 	if (NFS_SERVER(hdr->inode)->pnfs_curr_ld->flags &
2821 	    PNFS_LAYOUTRET_ON_ERROR) {
2822 		pnfs_return_layout(hdr->inode);
2823 	}
2824 	if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags))
2825 		hdr->task.tk_status = pnfs_write_done_resend_to_mds(hdr);
2826 }
2827 
2828 /*
2829  * Called by non rpc-based layout drivers
2830  */
2831 void pnfs_ld_write_done(struct nfs_pgio_header *hdr)
2832 {
2833 	if (likely(!hdr->pnfs_error)) {
2834 		pnfs_set_layoutcommit(hdr->inode, hdr->lseg,
2835 				hdr->mds_offset + hdr->res.count);
2836 		hdr->mds_ops->rpc_call_done(&hdr->task, hdr);
2837 	}
2838 	trace_nfs4_pnfs_write(hdr, hdr->pnfs_error);
2839 	if (unlikely(hdr->pnfs_error))
2840 		pnfs_ld_handle_write_error(hdr);
2841 	hdr->mds_ops->rpc_release(hdr);
2842 }
2843 EXPORT_SYMBOL_GPL(pnfs_ld_write_done);
2844 
2845 static void
2846 pnfs_write_through_mds(struct nfs_pageio_descriptor *desc,
2847 		struct nfs_pgio_header *hdr)
2848 {
2849 	struct nfs_pgio_mirror *mirror = nfs_pgio_current_mirror(desc);
2850 
2851 	if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
2852 		list_splice_tail_init(&hdr->pages, &mirror->pg_list);
2853 		nfs_pageio_reset_write_mds(desc);
2854 		mirror->pg_recoalesce = 1;
2855 	}
2856 	hdr->completion_ops->completion(hdr);
2857 }
2858 
2859 static enum pnfs_try_status
2860 pnfs_try_to_write_data(struct nfs_pgio_header *hdr,
2861 			const struct rpc_call_ops *call_ops,
2862 			struct pnfs_layout_segment *lseg,
2863 			int how)
2864 {
2865 	struct inode *inode = hdr->inode;
2866 	enum pnfs_try_status trypnfs;
2867 	struct nfs_server *nfss = NFS_SERVER(inode);
2868 
2869 	hdr->mds_ops = call_ops;
2870 
2871 	dprintk("%s: Writing ino:%lu %u@%llu (how %d)\n", __func__,
2872 		inode->i_ino, hdr->args.count, hdr->args.offset, how);
2873 	trypnfs = nfss->pnfs_curr_ld->write_pagelist(hdr, how);
2874 	if (trypnfs != PNFS_NOT_ATTEMPTED)
2875 		nfs_inc_stats(inode, NFSIOS_PNFS_WRITE);
2876 	dprintk("%s End (trypnfs:%d)\n", __func__, trypnfs);
2877 	return trypnfs;
2878 }
2879 
2880 static void
2881 pnfs_do_write(struct nfs_pageio_descriptor *desc,
2882 	      struct nfs_pgio_header *hdr, int how)
2883 {
2884 	const struct rpc_call_ops *call_ops = desc->pg_rpc_callops;
2885 	struct pnfs_layout_segment *lseg = desc->pg_lseg;
2886 	enum pnfs_try_status trypnfs;
2887 
2888 	trypnfs = pnfs_try_to_write_data(hdr, call_ops, lseg, how);
2889 	switch (trypnfs) {
2890 	case PNFS_NOT_ATTEMPTED:
2891 		pnfs_write_through_mds(desc, hdr);
2892 		break;
2893 	case PNFS_ATTEMPTED:
2894 		break;
2895 	case PNFS_TRY_AGAIN:
2896 		/* cleanup hdr and prepare to redo pnfs */
2897 		if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
2898 			struct nfs_pgio_mirror *mirror = nfs_pgio_current_mirror(desc);
2899 			list_splice_init(&hdr->pages, &mirror->pg_list);
2900 			mirror->pg_recoalesce = 1;
2901 		}
2902 		hdr->mds_ops->rpc_release(hdr);
2903 	}
2904 }
2905 
2906 static void pnfs_writehdr_free(struct nfs_pgio_header *hdr)
2907 {
2908 	pnfs_put_lseg(hdr->lseg);
2909 	nfs_pgio_header_free(hdr);
2910 }
2911 
2912 int
2913 pnfs_generic_pg_writepages(struct nfs_pageio_descriptor *desc)
2914 {
2915 	struct nfs_pgio_header *hdr;
2916 	int ret;
2917 
2918 	hdr = nfs_pgio_header_alloc(desc->pg_rw_ops);
2919 	if (!hdr) {
2920 		desc->pg_error = -ENOMEM;
2921 		return desc->pg_error;
2922 	}
2923 	nfs_pgheader_init(desc, hdr, pnfs_writehdr_free);
2924 
2925 	hdr->lseg = pnfs_get_lseg(desc->pg_lseg);
2926 	ret = nfs_generic_pgio(desc, hdr);
2927 	if (!ret)
2928 		pnfs_do_write(desc, hdr, desc->pg_ioflags);
2929 
2930 	return ret;
2931 }
2932 EXPORT_SYMBOL_GPL(pnfs_generic_pg_writepages);
2933 
2934 int pnfs_read_done_resend_to_mds(struct nfs_pgio_header *hdr)
2935 {
2936 	struct nfs_pageio_descriptor pgio;
2937 
2938 	/* Resend all requests through the MDS */
2939 	nfs_pageio_init_read(&pgio, hdr->inode, true, hdr->completion_ops);
2940 	return nfs_pageio_resend(&pgio, hdr);
2941 }
2942 EXPORT_SYMBOL_GPL(pnfs_read_done_resend_to_mds);
2943 
2944 static void pnfs_ld_handle_read_error(struct nfs_pgio_header *hdr)
2945 {
2946 	dprintk("pnfs read error = %d\n", hdr->pnfs_error);
2947 	if (NFS_SERVER(hdr->inode)->pnfs_curr_ld->flags &
2948 	    PNFS_LAYOUTRET_ON_ERROR) {
2949 		pnfs_return_layout(hdr->inode);
2950 	}
2951 	if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags))
2952 		hdr->task.tk_status = pnfs_read_done_resend_to_mds(hdr);
2953 }
2954 
2955 /*
2956  * Called by non rpc-based layout drivers
2957  */
2958 void pnfs_ld_read_done(struct nfs_pgio_header *hdr)
2959 {
2960 	if (likely(!hdr->pnfs_error))
2961 		hdr->mds_ops->rpc_call_done(&hdr->task, hdr);
2962 	trace_nfs4_pnfs_read(hdr, hdr->pnfs_error);
2963 	if (unlikely(hdr->pnfs_error))
2964 		pnfs_ld_handle_read_error(hdr);
2965 	hdr->mds_ops->rpc_release(hdr);
2966 }
2967 EXPORT_SYMBOL_GPL(pnfs_ld_read_done);
2968 
2969 static void
2970 pnfs_read_through_mds(struct nfs_pageio_descriptor *desc,
2971 		struct nfs_pgio_header *hdr)
2972 {
2973 	struct nfs_pgio_mirror *mirror = nfs_pgio_current_mirror(desc);
2974 
2975 	if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
2976 		list_splice_tail_init(&hdr->pages, &mirror->pg_list);
2977 		nfs_pageio_reset_read_mds(desc);
2978 		mirror->pg_recoalesce = 1;
2979 	}
2980 	hdr->completion_ops->completion(hdr);
2981 }
2982 
2983 /*
2984  * Call the appropriate parallel I/O subsystem read function.
2985  */
2986 static enum pnfs_try_status
2987 pnfs_try_to_read_data(struct nfs_pgio_header *hdr,
2988 		       const struct rpc_call_ops *call_ops,
2989 		       struct pnfs_layout_segment *lseg)
2990 {
2991 	struct inode *inode = hdr->inode;
2992 	struct nfs_server *nfss = NFS_SERVER(inode);
2993 	enum pnfs_try_status trypnfs;
2994 
2995 	hdr->mds_ops = call_ops;
2996 
2997 	dprintk("%s: Reading ino:%lu %u@%llu\n",
2998 		__func__, inode->i_ino, hdr->args.count, hdr->args.offset);
2999 
3000 	trypnfs = nfss->pnfs_curr_ld->read_pagelist(hdr);
3001 	if (trypnfs != PNFS_NOT_ATTEMPTED)
3002 		nfs_inc_stats(inode, NFSIOS_PNFS_READ);
3003 	dprintk("%s End (trypnfs:%d)\n", __func__, trypnfs);
3004 	return trypnfs;
3005 }
3006 
3007 /* Resend all requests through pnfs. */
3008 void pnfs_read_resend_pnfs(struct nfs_pgio_header *hdr,
3009 			   unsigned int mirror_idx)
3010 {
3011 	struct nfs_pageio_descriptor pgio;
3012 
3013 	if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
3014 		/* Prevent deadlocks with layoutreturn! */
3015 		pnfs_put_lseg(hdr->lseg);
3016 		hdr->lseg = NULL;
3017 
3018 		nfs_pageio_init_read(&pgio, hdr->inode, false,
3019 					hdr->completion_ops);
3020 		pgio.pg_mirror_idx = mirror_idx;
3021 		hdr->task.tk_status = nfs_pageio_resend(&pgio, hdr);
3022 	}
3023 }
3024 EXPORT_SYMBOL_GPL(pnfs_read_resend_pnfs);
3025 
3026 static void
3027 pnfs_do_read(struct nfs_pageio_descriptor *desc, struct nfs_pgio_header *hdr)
3028 {
3029 	const struct rpc_call_ops *call_ops = desc->pg_rpc_callops;
3030 	struct pnfs_layout_segment *lseg = desc->pg_lseg;
3031 	enum pnfs_try_status trypnfs;
3032 
3033 	trypnfs = pnfs_try_to_read_data(hdr, call_ops, lseg);
3034 	switch (trypnfs) {
3035 	case PNFS_NOT_ATTEMPTED:
3036 		pnfs_read_through_mds(desc, hdr);
3037 		break;
3038 	case PNFS_ATTEMPTED:
3039 		break;
3040 	case PNFS_TRY_AGAIN:
3041 		/* cleanup hdr and prepare to redo pnfs */
3042 		if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
3043 			struct nfs_pgio_mirror *mirror = nfs_pgio_current_mirror(desc);
3044 			list_splice_init(&hdr->pages, &mirror->pg_list);
3045 			mirror->pg_recoalesce = 1;
3046 		}
3047 		hdr->mds_ops->rpc_release(hdr);
3048 	}
3049 }
3050 
3051 static void pnfs_readhdr_free(struct nfs_pgio_header *hdr)
3052 {
3053 	pnfs_put_lseg(hdr->lseg);
3054 	nfs_pgio_header_free(hdr);
3055 }
3056 
3057 int
3058 pnfs_generic_pg_readpages(struct nfs_pageio_descriptor *desc)
3059 {
3060 	struct nfs_pgio_header *hdr;
3061 	int ret;
3062 
3063 	hdr = nfs_pgio_header_alloc(desc->pg_rw_ops);
3064 	if (!hdr) {
3065 		desc->pg_error = -ENOMEM;
3066 		return desc->pg_error;
3067 	}
3068 	nfs_pgheader_init(desc, hdr, pnfs_readhdr_free);
3069 	hdr->lseg = pnfs_get_lseg(desc->pg_lseg);
3070 	ret = nfs_generic_pgio(desc, hdr);
3071 	if (!ret)
3072 		pnfs_do_read(desc, hdr);
3073 	return ret;
3074 }
3075 EXPORT_SYMBOL_GPL(pnfs_generic_pg_readpages);
3076 
3077 static void pnfs_clear_layoutcommitting(struct inode *inode)
3078 {
3079 	unsigned long *bitlock = &NFS_I(inode)->flags;
3080 
3081 	clear_bit_unlock(NFS_INO_LAYOUTCOMMITTING, bitlock);
3082 	smp_mb__after_atomic();
3083 	wake_up_bit(bitlock, NFS_INO_LAYOUTCOMMITTING);
3084 }
3085 
3086 /*
3087  * There can be multiple RW segments.
3088  */
3089 static void pnfs_list_write_lseg(struct inode *inode, struct list_head *listp)
3090 {
3091 	struct pnfs_layout_segment *lseg;
3092 
3093 	list_for_each_entry(lseg, &NFS_I(inode)->layout->plh_segs, pls_list) {
3094 		if (lseg->pls_range.iomode == IOMODE_RW &&
3095 		    test_and_clear_bit(NFS_LSEG_LAYOUTCOMMIT, &lseg->pls_flags))
3096 			list_add(&lseg->pls_lc_list, listp);
3097 	}
3098 }
3099 
3100 static void pnfs_list_write_lseg_done(struct inode *inode, struct list_head *listp)
3101 {
3102 	struct pnfs_layout_segment *lseg, *tmp;
3103 
3104 	/* Matched by references in pnfs_set_layoutcommit */
3105 	list_for_each_entry_safe(lseg, tmp, listp, pls_lc_list) {
3106 		list_del_init(&lseg->pls_lc_list);
3107 		pnfs_put_lseg(lseg);
3108 	}
3109 
3110 	pnfs_clear_layoutcommitting(inode);
3111 }
3112 
3113 void pnfs_set_lo_fail(struct pnfs_layout_segment *lseg)
3114 {
3115 	pnfs_layout_io_set_failed(lseg->pls_layout, lseg->pls_range.iomode);
3116 }
3117 EXPORT_SYMBOL_GPL(pnfs_set_lo_fail);
3118 
3119 void
3120 pnfs_set_layoutcommit(struct inode *inode, struct pnfs_layout_segment *lseg,
3121 		loff_t end_pos)
3122 {
3123 	struct nfs_inode *nfsi = NFS_I(inode);
3124 	bool mark_as_dirty = false;
3125 
3126 	spin_lock(&inode->i_lock);
3127 	if (!test_and_set_bit(NFS_INO_LAYOUTCOMMIT, &nfsi->flags)) {
3128 		nfsi->layout->plh_lwb = end_pos;
3129 		mark_as_dirty = true;
3130 		dprintk("%s: Set layoutcommit for inode %lu ",
3131 			__func__, inode->i_ino);
3132 	} else if (end_pos > nfsi->layout->plh_lwb)
3133 		nfsi->layout->plh_lwb = end_pos;
3134 	if (!test_and_set_bit(NFS_LSEG_LAYOUTCOMMIT, &lseg->pls_flags)) {
3135 		/* references matched in nfs4_layoutcommit_release */
3136 		pnfs_get_lseg(lseg);
3137 	}
3138 	spin_unlock(&inode->i_lock);
3139 	dprintk("%s: lseg %p end_pos %llu\n",
3140 		__func__, lseg, nfsi->layout->plh_lwb);
3141 
3142 	/* if pnfs_layoutcommit_inode() runs between inode locks, the next one
3143 	 * will be a noop because NFS_INO_LAYOUTCOMMIT will not be set */
3144 	if (mark_as_dirty)
3145 		mark_inode_dirty_sync(inode);
3146 }
3147 EXPORT_SYMBOL_GPL(pnfs_set_layoutcommit);
3148 
3149 void pnfs_cleanup_layoutcommit(struct nfs4_layoutcommit_data *data)
3150 {
3151 	struct nfs_server *nfss = NFS_SERVER(data->args.inode);
3152 
3153 	if (nfss->pnfs_curr_ld->cleanup_layoutcommit)
3154 		nfss->pnfs_curr_ld->cleanup_layoutcommit(data);
3155 	pnfs_list_write_lseg_done(data->args.inode, &data->lseg_list);
3156 }
3157 
3158 /*
3159  * For the LAYOUT4_NFSV4_1_FILES layout type, NFS_DATA_SYNC WRITEs and
3160  * NFS_UNSTABLE WRITEs with a COMMIT to data servers must store enough
3161  * data to disk to allow the server to recover the data if it crashes.
3162  * LAYOUTCOMMIT is only needed when the NFL4_UFLG_COMMIT_THRU_MDS flag
3163  * is off, and a COMMIT is sent to a data server, or
3164  * if WRITEs to a data server return NFS_DATA_SYNC.
3165  */
3166 int
3167 pnfs_layoutcommit_inode(struct inode *inode, bool sync)
3168 {
3169 	struct pnfs_layoutdriver_type *ld = NFS_SERVER(inode)->pnfs_curr_ld;
3170 	struct nfs4_layoutcommit_data *data;
3171 	struct nfs_inode *nfsi = NFS_I(inode);
3172 	loff_t end_pos;
3173 	int status;
3174 
3175 	if (!pnfs_layoutcommit_outstanding(inode))
3176 		return 0;
3177 
3178 	dprintk("--> %s inode %lu\n", __func__, inode->i_ino);
3179 
3180 	status = -EAGAIN;
3181 	if (test_and_set_bit(NFS_INO_LAYOUTCOMMITTING, &nfsi->flags)) {
3182 		if (!sync)
3183 			goto out;
3184 		status = wait_on_bit_lock_action(&nfsi->flags,
3185 				NFS_INO_LAYOUTCOMMITTING,
3186 				nfs_wait_bit_killable,
3187 				TASK_KILLABLE);
3188 		if (status)
3189 			goto out;
3190 	}
3191 
3192 	status = -ENOMEM;
3193 	/* Note kzalloc ensures data->res.seq_res.sr_slot == NULL */
3194 	data = kzalloc(sizeof(*data), nfs_io_gfp_mask());
3195 	if (!data)
3196 		goto clear_layoutcommitting;
3197 
3198 	status = 0;
3199 	spin_lock(&inode->i_lock);
3200 	if (!test_and_clear_bit(NFS_INO_LAYOUTCOMMIT, &nfsi->flags))
3201 		goto out_unlock;
3202 
3203 	INIT_LIST_HEAD(&data->lseg_list);
3204 	pnfs_list_write_lseg(inode, &data->lseg_list);
3205 
3206 	end_pos = nfsi->layout->plh_lwb;
3207 
3208 	nfs4_stateid_copy(&data->args.stateid, &nfsi->layout->plh_stateid);
3209 	data->cred = get_cred(nfsi->layout->plh_lc_cred);
3210 	spin_unlock(&inode->i_lock);
3211 
3212 	data->args.inode = inode;
3213 	nfs_fattr_init(&data->fattr);
3214 	data->args.bitmask = NFS_SERVER(inode)->cache_consistency_bitmask;
3215 	data->res.fattr = &data->fattr;
3216 	if (end_pos != 0)
3217 		data->args.lastbytewritten = end_pos - 1;
3218 	else
3219 		data->args.lastbytewritten = U64_MAX;
3220 	data->res.server = NFS_SERVER(inode);
3221 
3222 	if (ld->prepare_layoutcommit) {
3223 		status = ld->prepare_layoutcommit(&data->args);
3224 		if (status) {
3225 			put_cred(data->cred);
3226 			spin_lock(&inode->i_lock);
3227 			set_bit(NFS_INO_LAYOUTCOMMIT, &nfsi->flags);
3228 			if (end_pos > nfsi->layout->plh_lwb)
3229 				nfsi->layout->plh_lwb = end_pos;
3230 			goto out_unlock;
3231 		}
3232 	}
3233 
3234 
3235 	status = nfs4_proc_layoutcommit(data, sync);
3236 out:
3237 	if (status)
3238 		mark_inode_dirty_sync(inode);
3239 	dprintk("<-- %s status %d\n", __func__, status);
3240 	return status;
3241 out_unlock:
3242 	spin_unlock(&inode->i_lock);
3243 	kfree(data);
3244 clear_layoutcommitting:
3245 	pnfs_clear_layoutcommitting(inode);
3246 	goto out;
3247 }
3248 EXPORT_SYMBOL_GPL(pnfs_layoutcommit_inode);
3249 
3250 int
3251 pnfs_generic_sync(struct inode *inode, bool datasync)
3252 {
3253 	return pnfs_layoutcommit_inode(inode, true);
3254 }
3255 EXPORT_SYMBOL_GPL(pnfs_generic_sync);
3256 
3257 struct nfs4_threshold *pnfs_mdsthreshold_alloc(void)
3258 {
3259 	struct nfs4_threshold *thp;
3260 
3261 	thp = kzalloc(sizeof(*thp), nfs_io_gfp_mask());
3262 	if (!thp) {
3263 		dprintk("%s mdsthreshold allocation failed\n", __func__);
3264 		return NULL;
3265 	}
3266 	return thp;
3267 }
3268 
3269 #if IS_ENABLED(CONFIG_NFS_V4_2)
3270 int
3271 pnfs_report_layoutstat(struct inode *inode, gfp_t gfp_flags)
3272 {
3273 	struct pnfs_layoutdriver_type *ld = NFS_SERVER(inode)->pnfs_curr_ld;
3274 	struct nfs_server *server = NFS_SERVER(inode);
3275 	struct nfs_inode *nfsi = NFS_I(inode);
3276 	struct nfs42_layoutstat_data *data;
3277 	struct pnfs_layout_hdr *hdr;
3278 	int status = 0;
3279 
3280 	if (!pnfs_enabled_sb(server) || !ld->prepare_layoutstats)
3281 		goto out;
3282 
3283 	if (!nfs_server_capable(inode, NFS_CAP_LAYOUTSTATS))
3284 		goto out;
3285 
3286 	if (test_and_set_bit(NFS_INO_LAYOUTSTATS, &nfsi->flags))
3287 		goto out;
3288 
3289 	spin_lock(&inode->i_lock);
3290 	if (!NFS_I(inode)->layout) {
3291 		spin_unlock(&inode->i_lock);
3292 		goto out_clear_layoutstats;
3293 	}
3294 	hdr = NFS_I(inode)->layout;
3295 	pnfs_get_layout_hdr(hdr);
3296 	spin_unlock(&inode->i_lock);
3297 
3298 	data = kzalloc(sizeof(*data), gfp_flags);
3299 	if (!data) {
3300 		status = -ENOMEM;
3301 		goto out_put;
3302 	}
3303 
3304 	data->args.fh = NFS_FH(inode);
3305 	data->args.inode = inode;
3306 	status = ld->prepare_layoutstats(&data->args);
3307 	if (status)
3308 		goto out_free;
3309 
3310 	status = nfs42_proc_layoutstats_generic(NFS_SERVER(inode), data);
3311 
3312 out:
3313 	dprintk("%s returns %d\n", __func__, status);
3314 	return status;
3315 
3316 out_free:
3317 	kfree(data);
3318 out_put:
3319 	pnfs_put_layout_hdr(hdr);
3320 out_clear_layoutstats:
3321 	smp_mb__before_atomic();
3322 	clear_bit(NFS_INO_LAYOUTSTATS, &nfsi->flags);
3323 	smp_mb__after_atomic();
3324 	goto out;
3325 }
3326 EXPORT_SYMBOL_GPL(pnfs_report_layoutstat);
3327 #endif
3328 
3329 unsigned int layoutstats_timer;
3330 module_param(layoutstats_timer, uint, 0644);
3331 EXPORT_SYMBOL_GPL(layoutstats_timer);
3332