xref: /linux/fs/nfs/pnfs.c (revision 3f0a50f345f78183f6e9b39c2f45ca5dcaa511ca)
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 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2004 				 PNFS_UPDATE_LAYOUT_NOMEM);
2005 		goto out;
2006 	}
2007 
2008 	/* Do we even need to bother with this? */
2009 	if (test_bit(NFS_LAYOUT_BULK_RECALL, &lo->plh_flags)) {
2010 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2011 				 PNFS_UPDATE_LAYOUT_BULK_RECALL);
2012 		dprintk("%s matches recall, use MDS\n", __func__);
2013 		goto out_unlock;
2014 	}
2015 
2016 	/* if LAYOUTGET already failed once we don't try again */
2017 	if (pnfs_layout_io_test_failed(lo, iomode)) {
2018 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2019 				 PNFS_UPDATE_LAYOUT_IO_TEST_FAIL);
2020 		goto out_unlock;
2021 	}
2022 
2023 	/*
2024 	 * If the layout segment list is empty, but there are outstanding
2025 	 * layoutget calls, then they might be subject to a layoutrecall.
2026 	 */
2027 	if ((list_empty(&lo->plh_segs) || !pnfs_layout_is_valid(lo)) &&
2028 	    atomic_read(&lo->plh_outstanding) != 0) {
2029 		spin_unlock(&ino->i_lock);
2030 		lseg = ERR_PTR(wait_var_event_killable(&lo->plh_outstanding,
2031 					!atomic_read(&lo->plh_outstanding)));
2032 		if (IS_ERR(lseg))
2033 			goto out_put_layout_hdr;
2034 		pnfs_put_layout_hdr(lo);
2035 		goto lookup_again;
2036 	}
2037 
2038 	/*
2039 	 * Because we free lsegs when sending LAYOUTRETURN, we need to wait
2040 	 * for LAYOUTRETURN.
2041 	 */
2042 	if (test_bit(NFS_LAYOUT_RETURN, &lo->plh_flags)) {
2043 		spin_unlock(&ino->i_lock);
2044 		dprintk("%s wait for layoutreturn\n", __func__);
2045 		lseg = ERR_PTR(pnfs_prepare_to_retry_layoutget(lo));
2046 		if (!IS_ERR(lseg)) {
2047 			pnfs_put_layout_hdr(lo);
2048 			dprintk("%s retrying\n", __func__);
2049 			trace_pnfs_update_layout(ino, pos, count, iomode, lo,
2050 						 lseg,
2051 						 PNFS_UPDATE_LAYOUT_RETRY);
2052 			goto lookup_again;
2053 		}
2054 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2055 					 PNFS_UPDATE_LAYOUT_RETURN);
2056 		goto out_put_layout_hdr;
2057 	}
2058 
2059 	lseg = pnfs_find_lseg(lo, &arg, strict_iomode);
2060 	if (lseg) {
2061 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2062 				PNFS_UPDATE_LAYOUT_FOUND_CACHED);
2063 		goto out_unlock;
2064 	}
2065 
2066 	/*
2067 	 * Choose a stateid for the LAYOUTGET. If we don't have a layout
2068 	 * stateid, or it has been invalidated, then we must use the open
2069 	 * stateid.
2070 	 */
2071 	if (test_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags)) {
2072 		int status;
2073 
2074 		/*
2075 		 * The first layoutget for the file. Need to serialize per
2076 		 * RFC 5661 Errata 3208.
2077 		 */
2078 		if (test_and_set_bit(NFS_LAYOUT_FIRST_LAYOUTGET,
2079 				     &lo->plh_flags)) {
2080 			spin_unlock(&ino->i_lock);
2081 			lseg = ERR_PTR(wait_on_bit(&lo->plh_flags,
2082 						NFS_LAYOUT_FIRST_LAYOUTGET,
2083 						TASK_KILLABLE));
2084 			if (IS_ERR(lseg))
2085 				goto out_put_layout_hdr;
2086 			pnfs_put_layout_hdr(lo);
2087 			dprintk("%s retrying\n", __func__);
2088 			goto lookup_again;
2089 		}
2090 
2091 		spin_unlock(&ino->i_lock);
2092 		first = true;
2093 		status = nfs4_select_rw_stateid(ctx->state,
2094 					iomode == IOMODE_RW ? FMODE_WRITE : FMODE_READ,
2095 					NULL, &stateid, NULL);
2096 		if (status != 0) {
2097 			lseg = ERR_PTR(status);
2098 			trace_pnfs_update_layout(ino, pos, count,
2099 					iomode, lo, lseg,
2100 					PNFS_UPDATE_LAYOUT_INVALID_OPEN);
2101 			nfs4_schedule_stateid_recovery(server, ctx->state);
2102 			pnfs_clear_first_layoutget(lo);
2103 			pnfs_put_layout_hdr(lo);
2104 			goto lookup_again;
2105 		}
2106 		spin_lock(&ino->i_lock);
2107 	} else {
2108 		nfs4_stateid_copy(&stateid, &lo->plh_stateid);
2109 	}
2110 
2111 	if (pnfs_layoutgets_blocked(lo)) {
2112 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2113 				PNFS_UPDATE_LAYOUT_BLOCKED);
2114 		goto out_unlock;
2115 	}
2116 	nfs_layoutget_begin(lo);
2117 	spin_unlock(&ino->i_lock);
2118 
2119 	_add_to_server_list(lo, server);
2120 
2121 	pg_offset = arg.offset & ~PAGE_MASK;
2122 	if (pg_offset) {
2123 		arg.offset -= pg_offset;
2124 		arg.length += pg_offset;
2125 	}
2126 	if (arg.length != NFS4_MAX_UINT64)
2127 		arg.length = PAGE_ALIGN(arg.length);
2128 
2129 	lgp = pnfs_alloc_init_layoutget_args(ino, ctx, &stateid, &arg, gfp_flags);
2130 	if (!lgp) {
2131 		trace_pnfs_update_layout(ino, pos, count, iomode, lo, NULL,
2132 					 PNFS_UPDATE_LAYOUT_NOMEM);
2133 		nfs_layoutget_end(lo);
2134 		goto out_put_layout_hdr;
2135 	}
2136 
2137 	lgp->lo = lo;
2138 	pnfs_get_layout_hdr(lo);
2139 
2140 	lseg = nfs4_proc_layoutget(lgp, &timeout);
2141 	trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2142 				 PNFS_UPDATE_LAYOUT_SEND_LAYOUTGET);
2143 	nfs_layoutget_end(lo);
2144 	if (IS_ERR(lseg)) {
2145 		switch(PTR_ERR(lseg)) {
2146 		case -EBUSY:
2147 			if (time_after(jiffies, giveup))
2148 				lseg = NULL;
2149 			break;
2150 		case -ERECALLCONFLICT:
2151 		case -EAGAIN:
2152 			break;
2153 		default:
2154 			if (!nfs_error_is_fatal(PTR_ERR(lseg))) {
2155 				pnfs_layout_clear_fail_bit(lo, pnfs_iomode_to_fail_bit(iomode));
2156 				lseg = NULL;
2157 			}
2158 			goto out_put_layout_hdr;
2159 		}
2160 		if (lseg) {
2161 			if (first)
2162 				pnfs_clear_first_layoutget(lo);
2163 			trace_pnfs_update_layout(ino, pos, count,
2164 				iomode, lo, lseg, PNFS_UPDATE_LAYOUT_RETRY);
2165 			pnfs_put_layout_hdr(lo);
2166 			goto lookup_again;
2167 		}
2168 	} else {
2169 		pnfs_layout_clear_fail_bit(lo, pnfs_iomode_to_fail_bit(iomode));
2170 	}
2171 
2172 out_put_layout_hdr:
2173 	if (first)
2174 		pnfs_clear_first_layoutget(lo);
2175 	trace_pnfs_update_layout(ino, pos, count, iomode, lo, lseg,
2176 				 PNFS_UPDATE_LAYOUT_EXIT);
2177 	pnfs_put_layout_hdr(lo);
2178 out:
2179 	dprintk("%s: inode %s/%llu pNFS layout segment %s for "
2180 			"(%s, offset: %llu, length: %llu)\n",
2181 			__func__, ino->i_sb->s_id,
2182 			(unsigned long long)NFS_FILEID(ino),
2183 			IS_ERR_OR_NULL(lseg) ? "not found" : "found",
2184 			iomode==IOMODE_RW ?  "read/write" : "read-only",
2185 			(unsigned long long)pos,
2186 			(unsigned long long)count);
2187 	return lseg;
2188 out_unlock:
2189 	spin_unlock(&ino->i_lock);
2190 	goto out_put_layout_hdr;
2191 }
2192 EXPORT_SYMBOL_GPL(pnfs_update_layout);
2193 
2194 static bool
2195 pnfs_sanity_check_layout_range(struct pnfs_layout_range *range)
2196 {
2197 	switch (range->iomode) {
2198 	case IOMODE_READ:
2199 	case IOMODE_RW:
2200 		break;
2201 	default:
2202 		return false;
2203 	}
2204 	if (range->offset == NFS4_MAX_UINT64)
2205 		return false;
2206 	if (range->length == 0)
2207 		return false;
2208 	if (range->length != NFS4_MAX_UINT64 &&
2209 	    range->length > NFS4_MAX_UINT64 - range->offset)
2210 		return false;
2211 	return true;
2212 }
2213 
2214 static struct pnfs_layout_hdr *
2215 _pnfs_grab_empty_layout(struct inode *ino, struct nfs_open_context *ctx)
2216 {
2217 	struct pnfs_layout_hdr *lo;
2218 
2219 	spin_lock(&ino->i_lock);
2220 	lo = pnfs_find_alloc_layout(ino, ctx, nfs_io_gfp_mask());
2221 	if (!lo)
2222 		goto out_unlock;
2223 	if (!test_bit(NFS_LAYOUT_INVALID_STID, &lo->plh_flags))
2224 		goto out_unlock;
2225 	if (test_bit(NFS_LAYOUT_RETURN, &lo->plh_flags))
2226 		goto out_unlock;
2227 	if (pnfs_layoutgets_blocked(lo))
2228 		goto out_unlock;
2229 	if (test_and_set_bit(NFS_LAYOUT_FIRST_LAYOUTGET, &lo->plh_flags))
2230 		goto out_unlock;
2231 	nfs_layoutget_begin(lo);
2232 	spin_unlock(&ino->i_lock);
2233 	_add_to_server_list(lo, NFS_SERVER(ino));
2234 	return lo;
2235 
2236 out_unlock:
2237 	spin_unlock(&ino->i_lock);
2238 	pnfs_put_layout_hdr(lo);
2239 	return NULL;
2240 }
2241 
2242 static void _lgopen_prepare_attached(struct nfs4_opendata *data,
2243 				     struct nfs_open_context *ctx)
2244 {
2245 	struct inode *ino = data->dentry->d_inode;
2246 	struct pnfs_layout_range rng = {
2247 		.iomode = (data->o_arg.fmode & FMODE_WRITE) ?
2248 			  IOMODE_RW: IOMODE_READ,
2249 		.offset = 0,
2250 		.length = NFS4_MAX_UINT64,
2251 	};
2252 	struct nfs4_layoutget *lgp;
2253 	struct pnfs_layout_hdr *lo;
2254 
2255 	/* Heuristic: don't send layoutget if we have cached data */
2256 	if (rng.iomode == IOMODE_READ &&
2257 	   (i_size_read(ino) == 0 || ino->i_mapping->nrpages != 0))
2258 		return;
2259 
2260 	lo = _pnfs_grab_empty_layout(ino, ctx);
2261 	if (!lo)
2262 		return;
2263 	lgp = pnfs_alloc_init_layoutget_args(ino, ctx, &current_stateid, &rng,
2264 					     nfs_io_gfp_mask());
2265 	if (!lgp) {
2266 		pnfs_clear_first_layoutget(lo);
2267 		nfs_layoutget_end(lo);
2268 		pnfs_put_layout_hdr(lo);
2269 		return;
2270 	}
2271 	lgp->lo = lo;
2272 	data->lgp = lgp;
2273 	data->o_arg.lg_args = &lgp->args;
2274 	data->o_res.lg_res = &lgp->res;
2275 }
2276 
2277 static void _lgopen_prepare_floating(struct nfs4_opendata *data,
2278 				     struct nfs_open_context *ctx)
2279 {
2280 	struct inode *ino = data->dentry->d_inode;
2281 	struct pnfs_layout_range rng = {
2282 		.iomode = (data->o_arg.fmode & FMODE_WRITE) ?
2283 			  IOMODE_RW: IOMODE_READ,
2284 		.offset = 0,
2285 		.length = NFS4_MAX_UINT64,
2286 	};
2287 	struct nfs4_layoutget *lgp;
2288 
2289 	lgp = pnfs_alloc_init_layoutget_args(ino, ctx, &current_stateid, &rng,
2290 					     nfs_io_gfp_mask());
2291 	if (!lgp)
2292 		return;
2293 	data->lgp = lgp;
2294 	data->o_arg.lg_args = &lgp->args;
2295 	data->o_res.lg_res = &lgp->res;
2296 }
2297 
2298 void pnfs_lgopen_prepare(struct nfs4_opendata *data,
2299 			 struct nfs_open_context *ctx)
2300 {
2301 	struct nfs_server *server = NFS_SERVER(data->dir->d_inode);
2302 
2303 	if (!(pnfs_enabled_sb(server) &&
2304 	      server->pnfs_curr_ld->flags & PNFS_LAYOUTGET_ON_OPEN))
2305 		return;
2306 	/* Could check on max_ops, but currently hardcoded high enough */
2307 	if (!nfs_server_capable(data->dir->d_inode, NFS_CAP_LGOPEN))
2308 		return;
2309 	if (data->lgp)
2310 		return;
2311 	if (data->state)
2312 		_lgopen_prepare_attached(data, ctx);
2313 	else
2314 		_lgopen_prepare_floating(data, ctx);
2315 }
2316 
2317 void pnfs_parse_lgopen(struct inode *ino, struct nfs4_layoutget *lgp,
2318 		       struct nfs_open_context *ctx)
2319 {
2320 	struct pnfs_layout_hdr *lo;
2321 	struct pnfs_layout_segment *lseg;
2322 	struct nfs_server *srv = NFS_SERVER(ino);
2323 	u32 iomode;
2324 
2325 	if (!lgp)
2326 		return;
2327 	dprintk("%s: entered with status %i\n", __func__, lgp->res.status);
2328 	if (lgp->res.status) {
2329 		switch (lgp->res.status) {
2330 		default:
2331 			break;
2332 		/*
2333 		 * Halt lgopen attempts if the server doesn't recognise
2334 		 * the "current stateid" value, the layout type, or the
2335 		 * layoutget operation as being valid.
2336 		 * Also if it complains about too many ops in the compound
2337 		 * or of the request/reply being too big.
2338 		 */
2339 		case -NFS4ERR_BAD_STATEID:
2340 		case -NFS4ERR_NOTSUPP:
2341 		case -NFS4ERR_REP_TOO_BIG:
2342 		case -NFS4ERR_REP_TOO_BIG_TO_CACHE:
2343 		case -NFS4ERR_REQ_TOO_BIG:
2344 		case -NFS4ERR_TOO_MANY_OPS:
2345 		case -NFS4ERR_UNKNOWN_LAYOUTTYPE:
2346 			srv->caps &= ~NFS_CAP_LGOPEN;
2347 		}
2348 		return;
2349 	}
2350 	if (!lgp->lo) {
2351 		lo = _pnfs_grab_empty_layout(ino, ctx);
2352 		if (!lo)
2353 			return;
2354 		lgp->lo = lo;
2355 	} else
2356 		lo = lgp->lo;
2357 
2358 	lseg = pnfs_layout_process(lgp);
2359 	if (!IS_ERR(lseg)) {
2360 		iomode = lgp->args.range.iomode;
2361 		pnfs_layout_clear_fail_bit(lo, pnfs_iomode_to_fail_bit(iomode));
2362 		pnfs_put_lseg(lseg);
2363 	}
2364 }
2365 
2366 void nfs4_lgopen_release(struct nfs4_layoutget *lgp)
2367 {
2368 	if (lgp != NULL) {
2369 		if (lgp->lo) {
2370 			pnfs_clear_first_layoutget(lgp->lo);
2371 			nfs_layoutget_end(lgp->lo);
2372 		}
2373 		pnfs_layoutget_free(lgp);
2374 	}
2375 }
2376 
2377 struct pnfs_layout_segment *
2378 pnfs_layout_process(struct nfs4_layoutget *lgp)
2379 {
2380 	struct pnfs_layout_hdr *lo = lgp->lo;
2381 	struct nfs4_layoutget_res *res = &lgp->res;
2382 	struct pnfs_layout_segment *lseg;
2383 	struct inode *ino = lo->plh_inode;
2384 	LIST_HEAD(free_me);
2385 
2386 	if (!pnfs_sanity_check_layout_range(&res->range))
2387 		return ERR_PTR(-EINVAL);
2388 
2389 	/* Inject layout blob into I/O device driver */
2390 	lseg = NFS_SERVER(ino)->pnfs_curr_ld->alloc_lseg(lo, res, lgp->gfp_flags);
2391 	if (IS_ERR_OR_NULL(lseg)) {
2392 		if (!lseg)
2393 			lseg = ERR_PTR(-ENOMEM);
2394 
2395 		dprintk("%s: Could not allocate layout: error %ld\n",
2396 		       __func__, PTR_ERR(lseg));
2397 		return lseg;
2398 	}
2399 
2400 	pnfs_init_lseg(lo, lseg, &res->range, &res->stateid);
2401 
2402 	spin_lock(&ino->i_lock);
2403 	if (pnfs_layoutgets_blocked(lo)) {
2404 		dprintk("%s forget reply due to state\n", __func__);
2405 		goto out_forget;
2406 	}
2407 
2408 	if (!pnfs_layout_is_valid(lo) && !pnfs_is_first_layoutget(lo))
2409 		goto out_forget;
2410 
2411 	if (nfs4_stateid_match_other(&lo->plh_stateid, &res->stateid)) {
2412 		/* existing state ID, make sure the sequence number matches. */
2413 		if (pnfs_layout_stateid_blocked(lo, &res->stateid)) {
2414 			if (!pnfs_layout_is_valid(lo))
2415 				lo->plh_barrier = 0;
2416 			dprintk("%s forget reply due to sequence\n", __func__);
2417 			goto out_forget;
2418 		}
2419 		pnfs_set_layout_stateid(lo, &res->stateid, lgp->cred, false);
2420 	} else if (pnfs_layout_is_valid(lo)) {
2421 		/*
2422 		 * We got an entirely new state ID.  Mark all segments for the
2423 		 * inode invalid, and retry the layoutget
2424 		 */
2425 		struct pnfs_layout_range range = {
2426 			.iomode = IOMODE_ANY,
2427 			.length = NFS4_MAX_UINT64,
2428 		};
2429 		pnfs_mark_matching_lsegs_return(lo, &free_me, &range, 0);
2430 		goto out_forget;
2431 	} else {
2432 		/* We have a completely new layout */
2433 		pnfs_set_layout_stateid(lo, &res->stateid, lgp->cred, true);
2434 	}
2435 
2436 	pnfs_get_lseg(lseg);
2437 	pnfs_layout_insert_lseg(lo, lseg, &free_me);
2438 
2439 
2440 	if (res->return_on_close)
2441 		set_bit(NFS_LSEG_ROC, &lseg->pls_flags);
2442 
2443 	spin_unlock(&ino->i_lock);
2444 	pnfs_free_lseg_list(&free_me);
2445 	return lseg;
2446 
2447 out_forget:
2448 	spin_unlock(&ino->i_lock);
2449 	lseg->pls_layout = lo;
2450 	NFS_SERVER(ino)->pnfs_curr_ld->free_lseg(lseg);
2451 	return ERR_PTR(-EAGAIN);
2452 }
2453 
2454 /**
2455  * pnfs_mark_matching_lsegs_return - Free or return matching layout segments
2456  * @lo: pointer to layout header
2457  * @tmp_list: list header to be used with pnfs_free_lseg_list()
2458  * @return_range: describe layout segment ranges to be returned
2459  * @seq: stateid seqid to match
2460  *
2461  * This function is mainly intended for use by layoutrecall. It attempts
2462  * to free the layout segment immediately, or else to mark it for return
2463  * as soon as its reference count drops to zero.
2464  *
2465  * Returns
2466  * - 0: a layoutreturn needs to be scheduled.
2467  * - EBUSY: there are layout segment that are still in use.
2468  * - ENOENT: there are no layout segments that need to be returned.
2469  */
2470 int
2471 pnfs_mark_matching_lsegs_return(struct pnfs_layout_hdr *lo,
2472 				struct list_head *tmp_list,
2473 				const struct pnfs_layout_range *return_range,
2474 				u32 seq)
2475 {
2476 	struct pnfs_layout_segment *lseg, *next;
2477 	int remaining = 0;
2478 
2479 	dprintk("%s:Begin lo %p\n", __func__, lo);
2480 
2481 	assert_spin_locked(&lo->plh_inode->i_lock);
2482 
2483 	if (test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags))
2484 		tmp_list = &lo->plh_return_segs;
2485 
2486 	list_for_each_entry_safe(lseg, next, &lo->plh_segs, pls_list)
2487 		if (pnfs_match_lseg_recall(lseg, return_range, seq)) {
2488 			dprintk("%s: marking lseg %p iomode %d "
2489 				"offset %llu length %llu\n", __func__,
2490 				lseg, lseg->pls_range.iomode,
2491 				lseg->pls_range.offset,
2492 				lseg->pls_range.length);
2493 			if (test_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags))
2494 				tmp_list = &lo->plh_return_segs;
2495 			if (mark_lseg_invalid(lseg, tmp_list))
2496 				continue;
2497 			remaining++;
2498 			set_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags);
2499 		}
2500 
2501 	if (remaining) {
2502 		pnfs_set_plh_return_info(lo, return_range->iomode, seq);
2503 		return -EBUSY;
2504 	}
2505 
2506 	if (!list_empty(&lo->plh_return_segs)) {
2507 		pnfs_set_plh_return_info(lo, return_range->iomode, seq);
2508 		return 0;
2509 	}
2510 
2511 	return -ENOENT;
2512 }
2513 
2514 static void
2515 pnfs_mark_layout_for_return(struct inode *inode,
2516 			    const struct pnfs_layout_range *range)
2517 {
2518 	struct pnfs_layout_hdr *lo;
2519 	bool return_now = false;
2520 
2521 	spin_lock(&inode->i_lock);
2522 	lo = NFS_I(inode)->layout;
2523 	if (!pnfs_layout_is_valid(lo)) {
2524 		spin_unlock(&inode->i_lock);
2525 		return;
2526 	}
2527 	pnfs_set_plh_return_info(lo, range->iomode, 0);
2528 	/*
2529 	 * mark all matching lsegs so that we are sure to have no live
2530 	 * segments at hand when sending layoutreturn. See pnfs_put_lseg()
2531 	 * for how it works.
2532 	 */
2533 	if (pnfs_mark_matching_lsegs_return(lo, &lo->plh_return_segs, range, 0) != -EBUSY) {
2534 		const struct cred *cred;
2535 		nfs4_stateid stateid;
2536 		enum pnfs_iomode iomode;
2537 
2538 		return_now = pnfs_prepare_layoutreturn(lo, &stateid, &cred, &iomode);
2539 		spin_unlock(&inode->i_lock);
2540 		if (return_now)
2541 			pnfs_send_layoutreturn(lo, &stateid, &cred, iomode, false);
2542 	} else {
2543 		spin_unlock(&inode->i_lock);
2544 		nfs_commit_inode(inode, 0);
2545 	}
2546 }
2547 
2548 void pnfs_error_mark_layout_for_return(struct inode *inode,
2549 				       struct pnfs_layout_segment *lseg)
2550 {
2551 	struct pnfs_layout_range range = {
2552 		.iomode = lseg->pls_range.iomode,
2553 		.offset = 0,
2554 		.length = NFS4_MAX_UINT64,
2555 	};
2556 
2557 	pnfs_mark_layout_for_return(inode, &range);
2558 }
2559 EXPORT_SYMBOL_GPL(pnfs_error_mark_layout_for_return);
2560 
2561 static bool
2562 pnfs_layout_can_be_returned(struct pnfs_layout_hdr *lo)
2563 {
2564 	return pnfs_layout_is_valid(lo) &&
2565 		!test_bit(NFS_LAYOUT_INODE_FREEING, &lo->plh_flags) &&
2566 		!test_bit(NFS_LAYOUT_RETURN, &lo->plh_flags);
2567 }
2568 
2569 static struct pnfs_layout_segment *
2570 pnfs_find_first_lseg(struct pnfs_layout_hdr *lo,
2571 		     const struct pnfs_layout_range *range,
2572 		     enum pnfs_iomode iomode)
2573 {
2574 	struct pnfs_layout_segment *lseg;
2575 
2576 	list_for_each_entry(lseg, &lo->plh_segs, pls_list) {
2577 		if (!test_bit(NFS_LSEG_VALID, &lseg->pls_flags))
2578 			continue;
2579 		if (test_bit(NFS_LSEG_LAYOUTRETURN, &lseg->pls_flags))
2580 			continue;
2581 		if (lseg->pls_range.iomode != iomode && iomode != IOMODE_ANY)
2582 			continue;
2583 		if (pnfs_lseg_range_intersecting(&lseg->pls_range, range))
2584 			return lseg;
2585 	}
2586 	return NULL;
2587 }
2588 
2589 /* Find open file states whose mode matches that of the range */
2590 static bool
2591 pnfs_should_return_unused_layout(struct pnfs_layout_hdr *lo,
2592 				 const struct pnfs_layout_range *range)
2593 {
2594 	struct list_head *head;
2595 	struct nfs_open_context *ctx;
2596 	fmode_t mode = 0;
2597 
2598 	if (!pnfs_layout_can_be_returned(lo) ||
2599 	    !pnfs_find_first_lseg(lo, range, range->iomode))
2600 		return false;
2601 
2602 	head = &NFS_I(lo->plh_inode)->open_files;
2603 	list_for_each_entry_rcu(ctx, head, list) {
2604 		if (ctx->state)
2605 			mode |= ctx->state->state & (FMODE_READ|FMODE_WRITE);
2606 	}
2607 
2608 	switch (range->iomode) {
2609 	default:
2610 		break;
2611 	case IOMODE_READ:
2612 		mode &= ~FMODE_WRITE;
2613 		break;
2614 	case IOMODE_RW:
2615 		if (pnfs_find_first_lseg(lo, range, IOMODE_READ))
2616 			mode &= ~FMODE_READ;
2617 	}
2618 	return mode == 0;
2619 }
2620 
2621 static int
2622 pnfs_layout_return_unused_byserver(struct nfs_server *server, void *data)
2623 {
2624 	const struct pnfs_layout_range *range = data;
2625 	struct pnfs_layout_hdr *lo;
2626 	struct inode *inode;
2627 restart:
2628 	rcu_read_lock();
2629 	list_for_each_entry_rcu(lo, &server->layouts, plh_layouts) {
2630 		if (!pnfs_layout_can_be_returned(lo) ||
2631 		    test_bit(NFS_LAYOUT_RETURN_REQUESTED, &lo->plh_flags))
2632 			continue;
2633 		inode = lo->plh_inode;
2634 		spin_lock(&inode->i_lock);
2635 		if (!pnfs_should_return_unused_layout(lo, range)) {
2636 			spin_unlock(&inode->i_lock);
2637 			continue;
2638 		}
2639 		spin_unlock(&inode->i_lock);
2640 		inode = pnfs_grab_inode_layout_hdr(lo);
2641 		if (!inode)
2642 			continue;
2643 		rcu_read_unlock();
2644 		pnfs_mark_layout_for_return(inode, range);
2645 		iput(inode);
2646 		cond_resched();
2647 		goto restart;
2648 	}
2649 	rcu_read_unlock();
2650 	return 0;
2651 }
2652 
2653 void
2654 pnfs_layout_return_unused_byclid(struct nfs_client *clp,
2655 				 enum pnfs_iomode iomode)
2656 {
2657 	struct pnfs_layout_range range = {
2658 		.iomode = iomode,
2659 		.offset = 0,
2660 		.length = NFS4_MAX_UINT64,
2661 	};
2662 
2663 	nfs_client_for_each_server(clp, pnfs_layout_return_unused_byserver,
2664 			&range);
2665 }
2666 
2667 void
2668 pnfs_generic_pg_check_layout(struct nfs_pageio_descriptor *pgio)
2669 {
2670 	if (pgio->pg_lseg == NULL ||
2671 	    test_bit(NFS_LSEG_VALID, &pgio->pg_lseg->pls_flags))
2672 		return;
2673 	pnfs_put_lseg(pgio->pg_lseg);
2674 	pgio->pg_lseg = NULL;
2675 }
2676 EXPORT_SYMBOL_GPL(pnfs_generic_pg_check_layout);
2677 
2678 /*
2679  * Check for any intersection between the request and the pgio->pg_lseg,
2680  * and if none, put this pgio->pg_lseg away.
2681  */
2682 void
2683 pnfs_generic_pg_check_range(struct nfs_pageio_descriptor *pgio, struct nfs_page *req)
2684 {
2685 	if (pgio->pg_lseg && !pnfs_lseg_request_intersecting(pgio->pg_lseg, req)) {
2686 		pnfs_put_lseg(pgio->pg_lseg);
2687 		pgio->pg_lseg = NULL;
2688 	}
2689 }
2690 EXPORT_SYMBOL_GPL(pnfs_generic_pg_check_range);
2691 
2692 void
2693 pnfs_generic_pg_init_read(struct nfs_pageio_descriptor *pgio, struct nfs_page *req)
2694 {
2695 	u64 rd_size;
2696 
2697 	pnfs_generic_pg_check_layout(pgio);
2698 	pnfs_generic_pg_check_range(pgio, req);
2699 	if (pgio->pg_lseg == NULL) {
2700 		if (pgio->pg_dreq == NULL)
2701 			rd_size = i_size_read(pgio->pg_inode) - req_offset(req);
2702 		else
2703 			rd_size = nfs_dreq_bytes_left(pgio->pg_dreq);
2704 
2705 		pgio->pg_lseg =
2706 			pnfs_update_layout(pgio->pg_inode, nfs_req_openctx(req),
2707 					   req_offset(req), rd_size,
2708 					   IOMODE_READ, false,
2709 					   nfs_io_gfp_mask());
2710 		if (IS_ERR(pgio->pg_lseg)) {
2711 			pgio->pg_error = PTR_ERR(pgio->pg_lseg);
2712 			pgio->pg_lseg = NULL;
2713 			return;
2714 		}
2715 	}
2716 	/* If no lseg, fall back to read through mds */
2717 	if (pgio->pg_lseg == NULL)
2718 		nfs_pageio_reset_read_mds(pgio);
2719 
2720 }
2721 EXPORT_SYMBOL_GPL(pnfs_generic_pg_init_read);
2722 
2723 void
2724 pnfs_generic_pg_init_write(struct nfs_pageio_descriptor *pgio,
2725 			   struct nfs_page *req, u64 wb_size)
2726 {
2727 	pnfs_generic_pg_check_layout(pgio);
2728 	pnfs_generic_pg_check_range(pgio, req);
2729 	if (pgio->pg_lseg == NULL) {
2730 		pgio->pg_lseg =
2731 			pnfs_update_layout(pgio->pg_inode, nfs_req_openctx(req),
2732 					   req_offset(req), wb_size, IOMODE_RW,
2733 					   false, nfs_io_gfp_mask());
2734 		if (IS_ERR(pgio->pg_lseg)) {
2735 			pgio->pg_error = PTR_ERR(pgio->pg_lseg);
2736 			pgio->pg_lseg = NULL;
2737 			return;
2738 		}
2739 	}
2740 	/* If no lseg, fall back to write through mds */
2741 	if (pgio->pg_lseg == NULL)
2742 		nfs_pageio_reset_write_mds(pgio);
2743 }
2744 EXPORT_SYMBOL_GPL(pnfs_generic_pg_init_write);
2745 
2746 void
2747 pnfs_generic_pg_cleanup(struct nfs_pageio_descriptor *desc)
2748 {
2749 	if (desc->pg_lseg) {
2750 		pnfs_put_lseg(desc->pg_lseg);
2751 		desc->pg_lseg = NULL;
2752 	}
2753 }
2754 EXPORT_SYMBOL_GPL(pnfs_generic_pg_cleanup);
2755 
2756 /*
2757  * Return 0 if @req cannot be coalesced into @pgio, otherwise return the number
2758  * of bytes (maximum @req->wb_bytes) that can be coalesced.
2759  */
2760 size_t
2761 pnfs_generic_pg_test(struct nfs_pageio_descriptor *pgio,
2762 		     struct nfs_page *prev, struct nfs_page *req)
2763 {
2764 	unsigned int size;
2765 	u64 seg_end, req_start, seg_left;
2766 
2767 	size = nfs_generic_pg_test(pgio, prev, req);
2768 	if (!size)
2769 		return 0;
2770 
2771 	/*
2772 	 * 'size' contains the number of bytes left in the current page (up
2773 	 * to the original size asked for in @req->wb_bytes).
2774 	 *
2775 	 * Calculate how many bytes are left in the layout segment
2776 	 * and if there are less bytes than 'size', return that instead.
2777 	 *
2778 	 * Please also note that 'end_offset' is actually the offset of the
2779 	 * first byte that lies outside the pnfs_layout_range. FIXME?
2780 	 *
2781 	 */
2782 	if (pgio->pg_lseg) {
2783 		seg_end = pnfs_end_offset(pgio->pg_lseg->pls_range.offset,
2784 				     pgio->pg_lseg->pls_range.length);
2785 		req_start = req_offset(req);
2786 
2787 		/* start of request is past the last byte of this segment */
2788 		if (req_start >= seg_end)
2789 			return 0;
2790 
2791 		/* adjust 'size' iff there are fewer bytes left in the
2792 		 * segment than what nfs_generic_pg_test returned */
2793 		seg_left = seg_end - req_start;
2794 		if (seg_left < size)
2795 			size = (unsigned int)seg_left;
2796 	}
2797 
2798 	return size;
2799 }
2800 EXPORT_SYMBOL_GPL(pnfs_generic_pg_test);
2801 
2802 int pnfs_write_done_resend_to_mds(struct nfs_pgio_header *hdr)
2803 {
2804 	struct nfs_pageio_descriptor pgio;
2805 
2806 	/* Resend all requests through the MDS */
2807 	nfs_pageio_init_write(&pgio, hdr->inode, FLUSH_STABLE, true,
2808 			      hdr->completion_ops);
2809 	set_bit(NFS_CONTEXT_RESEND_WRITES, &hdr->args.context->flags);
2810 	return nfs_pageio_resend(&pgio, hdr);
2811 }
2812 EXPORT_SYMBOL_GPL(pnfs_write_done_resend_to_mds);
2813 
2814 static void pnfs_ld_handle_write_error(struct nfs_pgio_header *hdr)
2815 {
2816 
2817 	dprintk("pnfs write error = %d\n", hdr->pnfs_error);
2818 	if (NFS_SERVER(hdr->inode)->pnfs_curr_ld->flags &
2819 	    PNFS_LAYOUTRET_ON_ERROR) {
2820 		pnfs_return_layout(hdr->inode);
2821 	}
2822 	if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags))
2823 		hdr->task.tk_status = pnfs_write_done_resend_to_mds(hdr);
2824 }
2825 
2826 /*
2827  * Called by non rpc-based layout drivers
2828  */
2829 void pnfs_ld_write_done(struct nfs_pgio_header *hdr)
2830 {
2831 	if (likely(!hdr->pnfs_error)) {
2832 		pnfs_set_layoutcommit(hdr->inode, hdr->lseg,
2833 				hdr->mds_offset + hdr->res.count);
2834 		hdr->mds_ops->rpc_call_done(&hdr->task, hdr);
2835 	}
2836 	trace_nfs4_pnfs_write(hdr, hdr->pnfs_error);
2837 	if (unlikely(hdr->pnfs_error))
2838 		pnfs_ld_handle_write_error(hdr);
2839 	hdr->mds_ops->rpc_release(hdr);
2840 }
2841 EXPORT_SYMBOL_GPL(pnfs_ld_write_done);
2842 
2843 static void
2844 pnfs_write_through_mds(struct nfs_pageio_descriptor *desc,
2845 		struct nfs_pgio_header *hdr)
2846 {
2847 	struct nfs_pgio_mirror *mirror = nfs_pgio_current_mirror(desc);
2848 
2849 	if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
2850 		list_splice_tail_init(&hdr->pages, &mirror->pg_list);
2851 		nfs_pageio_reset_write_mds(desc);
2852 		mirror->pg_recoalesce = 1;
2853 	}
2854 	hdr->completion_ops->completion(hdr);
2855 }
2856 
2857 static enum pnfs_try_status
2858 pnfs_try_to_write_data(struct nfs_pgio_header *hdr,
2859 			const struct rpc_call_ops *call_ops,
2860 			struct pnfs_layout_segment *lseg,
2861 			int how)
2862 {
2863 	struct inode *inode = hdr->inode;
2864 	enum pnfs_try_status trypnfs;
2865 	struct nfs_server *nfss = NFS_SERVER(inode);
2866 
2867 	hdr->mds_ops = call_ops;
2868 
2869 	dprintk("%s: Writing ino:%lu %u@%llu (how %d)\n", __func__,
2870 		inode->i_ino, hdr->args.count, hdr->args.offset, how);
2871 	trypnfs = nfss->pnfs_curr_ld->write_pagelist(hdr, how);
2872 	if (trypnfs != PNFS_NOT_ATTEMPTED)
2873 		nfs_inc_stats(inode, NFSIOS_PNFS_WRITE);
2874 	dprintk("%s End (trypnfs:%d)\n", __func__, trypnfs);
2875 	return trypnfs;
2876 }
2877 
2878 static void
2879 pnfs_do_write(struct nfs_pageio_descriptor *desc,
2880 	      struct nfs_pgio_header *hdr, int how)
2881 {
2882 	const struct rpc_call_ops *call_ops = desc->pg_rpc_callops;
2883 	struct pnfs_layout_segment *lseg = desc->pg_lseg;
2884 	enum pnfs_try_status trypnfs;
2885 
2886 	trypnfs = pnfs_try_to_write_data(hdr, call_ops, lseg, how);
2887 	switch (trypnfs) {
2888 	case PNFS_NOT_ATTEMPTED:
2889 		pnfs_write_through_mds(desc, hdr);
2890 		break;
2891 	case PNFS_ATTEMPTED:
2892 		break;
2893 	case PNFS_TRY_AGAIN:
2894 		/* cleanup hdr and prepare to redo pnfs */
2895 		if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
2896 			struct nfs_pgio_mirror *mirror = nfs_pgio_current_mirror(desc);
2897 			list_splice_init(&hdr->pages, &mirror->pg_list);
2898 			mirror->pg_recoalesce = 1;
2899 		}
2900 		hdr->mds_ops->rpc_release(hdr);
2901 	}
2902 }
2903 
2904 static void pnfs_writehdr_free(struct nfs_pgio_header *hdr)
2905 {
2906 	pnfs_put_lseg(hdr->lseg);
2907 	nfs_pgio_header_free(hdr);
2908 }
2909 
2910 int
2911 pnfs_generic_pg_writepages(struct nfs_pageio_descriptor *desc)
2912 {
2913 	struct nfs_pgio_header *hdr;
2914 	int ret;
2915 
2916 	hdr = nfs_pgio_header_alloc(desc->pg_rw_ops);
2917 	if (!hdr) {
2918 		desc->pg_error = -ENOMEM;
2919 		return desc->pg_error;
2920 	}
2921 	nfs_pgheader_init(desc, hdr, pnfs_writehdr_free);
2922 
2923 	hdr->lseg = pnfs_get_lseg(desc->pg_lseg);
2924 	ret = nfs_generic_pgio(desc, hdr);
2925 	if (!ret)
2926 		pnfs_do_write(desc, hdr, desc->pg_ioflags);
2927 
2928 	return ret;
2929 }
2930 EXPORT_SYMBOL_GPL(pnfs_generic_pg_writepages);
2931 
2932 int pnfs_read_done_resend_to_mds(struct nfs_pgio_header *hdr)
2933 {
2934 	struct nfs_pageio_descriptor pgio;
2935 
2936 	/* Resend all requests through the MDS */
2937 	nfs_pageio_init_read(&pgio, hdr->inode, true, hdr->completion_ops);
2938 	return nfs_pageio_resend(&pgio, hdr);
2939 }
2940 EXPORT_SYMBOL_GPL(pnfs_read_done_resend_to_mds);
2941 
2942 static void pnfs_ld_handle_read_error(struct nfs_pgio_header *hdr)
2943 {
2944 	dprintk("pnfs read error = %d\n", hdr->pnfs_error);
2945 	if (NFS_SERVER(hdr->inode)->pnfs_curr_ld->flags &
2946 	    PNFS_LAYOUTRET_ON_ERROR) {
2947 		pnfs_return_layout(hdr->inode);
2948 	}
2949 	if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags))
2950 		hdr->task.tk_status = pnfs_read_done_resend_to_mds(hdr);
2951 }
2952 
2953 /*
2954  * Called by non rpc-based layout drivers
2955  */
2956 void pnfs_ld_read_done(struct nfs_pgio_header *hdr)
2957 {
2958 	if (likely(!hdr->pnfs_error))
2959 		hdr->mds_ops->rpc_call_done(&hdr->task, hdr);
2960 	trace_nfs4_pnfs_read(hdr, hdr->pnfs_error);
2961 	if (unlikely(hdr->pnfs_error))
2962 		pnfs_ld_handle_read_error(hdr);
2963 	hdr->mds_ops->rpc_release(hdr);
2964 }
2965 EXPORT_SYMBOL_GPL(pnfs_ld_read_done);
2966 
2967 static void
2968 pnfs_read_through_mds(struct nfs_pageio_descriptor *desc,
2969 		struct nfs_pgio_header *hdr)
2970 {
2971 	struct nfs_pgio_mirror *mirror = nfs_pgio_current_mirror(desc);
2972 
2973 	if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
2974 		list_splice_tail_init(&hdr->pages, &mirror->pg_list);
2975 		nfs_pageio_reset_read_mds(desc);
2976 		mirror->pg_recoalesce = 1;
2977 	}
2978 	hdr->completion_ops->completion(hdr);
2979 }
2980 
2981 /*
2982  * Call the appropriate parallel I/O subsystem read function.
2983  */
2984 static enum pnfs_try_status
2985 pnfs_try_to_read_data(struct nfs_pgio_header *hdr,
2986 		       const struct rpc_call_ops *call_ops,
2987 		       struct pnfs_layout_segment *lseg)
2988 {
2989 	struct inode *inode = hdr->inode;
2990 	struct nfs_server *nfss = NFS_SERVER(inode);
2991 	enum pnfs_try_status trypnfs;
2992 
2993 	hdr->mds_ops = call_ops;
2994 
2995 	dprintk("%s: Reading ino:%lu %u@%llu\n",
2996 		__func__, inode->i_ino, hdr->args.count, hdr->args.offset);
2997 
2998 	trypnfs = nfss->pnfs_curr_ld->read_pagelist(hdr);
2999 	if (trypnfs != PNFS_NOT_ATTEMPTED)
3000 		nfs_inc_stats(inode, NFSIOS_PNFS_READ);
3001 	dprintk("%s End (trypnfs:%d)\n", __func__, trypnfs);
3002 	return trypnfs;
3003 }
3004 
3005 /* Resend all requests through pnfs. */
3006 void pnfs_read_resend_pnfs(struct nfs_pgio_header *hdr,
3007 			   unsigned int mirror_idx)
3008 {
3009 	struct nfs_pageio_descriptor pgio;
3010 
3011 	if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
3012 		/* Prevent deadlocks with layoutreturn! */
3013 		pnfs_put_lseg(hdr->lseg);
3014 		hdr->lseg = NULL;
3015 
3016 		nfs_pageio_init_read(&pgio, hdr->inode, false,
3017 					hdr->completion_ops);
3018 		pgio.pg_mirror_idx = mirror_idx;
3019 		hdr->task.tk_status = nfs_pageio_resend(&pgio, hdr);
3020 	}
3021 }
3022 EXPORT_SYMBOL_GPL(pnfs_read_resend_pnfs);
3023 
3024 static void
3025 pnfs_do_read(struct nfs_pageio_descriptor *desc, struct nfs_pgio_header *hdr)
3026 {
3027 	const struct rpc_call_ops *call_ops = desc->pg_rpc_callops;
3028 	struct pnfs_layout_segment *lseg = desc->pg_lseg;
3029 	enum pnfs_try_status trypnfs;
3030 
3031 	trypnfs = pnfs_try_to_read_data(hdr, call_ops, lseg);
3032 	switch (trypnfs) {
3033 	case PNFS_NOT_ATTEMPTED:
3034 		pnfs_read_through_mds(desc, hdr);
3035 		break;
3036 	case PNFS_ATTEMPTED:
3037 		break;
3038 	case PNFS_TRY_AGAIN:
3039 		/* cleanup hdr and prepare to redo pnfs */
3040 		if (!test_and_set_bit(NFS_IOHDR_REDO, &hdr->flags)) {
3041 			struct nfs_pgio_mirror *mirror = nfs_pgio_current_mirror(desc);
3042 			list_splice_init(&hdr->pages, &mirror->pg_list);
3043 			mirror->pg_recoalesce = 1;
3044 		}
3045 		hdr->mds_ops->rpc_release(hdr);
3046 	}
3047 }
3048 
3049 static void pnfs_readhdr_free(struct nfs_pgio_header *hdr)
3050 {
3051 	pnfs_put_lseg(hdr->lseg);
3052 	nfs_pgio_header_free(hdr);
3053 }
3054 
3055 int
3056 pnfs_generic_pg_readpages(struct nfs_pageio_descriptor *desc)
3057 {
3058 	struct nfs_pgio_header *hdr;
3059 	int ret;
3060 
3061 	hdr = nfs_pgio_header_alloc(desc->pg_rw_ops);
3062 	if (!hdr) {
3063 		desc->pg_error = -ENOMEM;
3064 		return desc->pg_error;
3065 	}
3066 	nfs_pgheader_init(desc, hdr, pnfs_readhdr_free);
3067 	hdr->lseg = pnfs_get_lseg(desc->pg_lseg);
3068 	ret = nfs_generic_pgio(desc, hdr);
3069 	if (!ret)
3070 		pnfs_do_read(desc, hdr);
3071 	return ret;
3072 }
3073 EXPORT_SYMBOL_GPL(pnfs_generic_pg_readpages);
3074 
3075 static void pnfs_clear_layoutcommitting(struct inode *inode)
3076 {
3077 	unsigned long *bitlock = &NFS_I(inode)->flags;
3078 
3079 	clear_bit_unlock(NFS_INO_LAYOUTCOMMITTING, bitlock);
3080 	smp_mb__after_atomic();
3081 	wake_up_bit(bitlock, NFS_INO_LAYOUTCOMMITTING);
3082 }
3083 
3084 /*
3085  * There can be multiple RW segments.
3086  */
3087 static void pnfs_list_write_lseg(struct inode *inode, struct list_head *listp)
3088 {
3089 	struct pnfs_layout_segment *lseg;
3090 
3091 	list_for_each_entry(lseg, &NFS_I(inode)->layout->plh_segs, pls_list) {
3092 		if (lseg->pls_range.iomode == IOMODE_RW &&
3093 		    test_and_clear_bit(NFS_LSEG_LAYOUTCOMMIT, &lseg->pls_flags))
3094 			list_add(&lseg->pls_lc_list, listp);
3095 	}
3096 }
3097 
3098 static void pnfs_list_write_lseg_done(struct inode *inode, struct list_head *listp)
3099 {
3100 	struct pnfs_layout_segment *lseg, *tmp;
3101 
3102 	/* Matched by references in pnfs_set_layoutcommit */
3103 	list_for_each_entry_safe(lseg, tmp, listp, pls_lc_list) {
3104 		list_del_init(&lseg->pls_lc_list);
3105 		pnfs_put_lseg(lseg);
3106 	}
3107 
3108 	pnfs_clear_layoutcommitting(inode);
3109 }
3110 
3111 void pnfs_set_lo_fail(struct pnfs_layout_segment *lseg)
3112 {
3113 	pnfs_layout_io_set_failed(lseg->pls_layout, lseg->pls_range.iomode);
3114 }
3115 EXPORT_SYMBOL_GPL(pnfs_set_lo_fail);
3116 
3117 void
3118 pnfs_set_layoutcommit(struct inode *inode, struct pnfs_layout_segment *lseg,
3119 		loff_t end_pos)
3120 {
3121 	struct nfs_inode *nfsi = NFS_I(inode);
3122 	bool mark_as_dirty = false;
3123 
3124 	spin_lock(&inode->i_lock);
3125 	if (!test_and_set_bit(NFS_INO_LAYOUTCOMMIT, &nfsi->flags)) {
3126 		nfsi->layout->plh_lwb = end_pos;
3127 		mark_as_dirty = true;
3128 		dprintk("%s: Set layoutcommit for inode %lu ",
3129 			__func__, inode->i_ino);
3130 	} else if (end_pos > nfsi->layout->plh_lwb)
3131 		nfsi->layout->plh_lwb = end_pos;
3132 	if (!test_and_set_bit(NFS_LSEG_LAYOUTCOMMIT, &lseg->pls_flags)) {
3133 		/* references matched in nfs4_layoutcommit_release */
3134 		pnfs_get_lseg(lseg);
3135 	}
3136 	spin_unlock(&inode->i_lock);
3137 	dprintk("%s: lseg %p end_pos %llu\n",
3138 		__func__, lseg, nfsi->layout->plh_lwb);
3139 
3140 	/* if pnfs_layoutcommit_inode() runs between inode locks, the next one
3141 	 * will be a noop because NFS_INO_LAYOUTCOMMIT will not be set */
3142 	if (mark_as_dirty)
3143 		mark_inode_dirty_sync(inode);
3144 }
3145 EXPORT_SYMBOL_GPL(pnfs_set_layoutcommit);
3146 
3147 void pnfs_cleanup_layoutcommit(struct nfs4_layoutcommit_data *data)
3148 {
3149 	struct nfs_server *nfss = NFS_SERVER(data->args.inode);
3150 
3151 	if (nfss->pnfs_curr_ld->cleanup_layoutcommit)
3152 		nfss->pnfs_curr_ld->cleanup_layoutcommit(data);
3153 	pnfs_list_write_lseg_done(data->args.inode, &data->lseg_list);
3154 }
3155 
3156 /*
3157  * For the LAYOUT4_NFSV4_1_FILES layout type, NFS_DATA_SYNC WRITEs and
3158  * NFS_UNSTABLE WRITEs with a COMMIT to data servers must store enough
3159  * data to disk to allow the server to recover the data if it crashes.
3160  * LAYOUTCOMMIT is only needed when the NFL4_UFLG_COMMIT_THRU_MDS flag
3161  * is off, and a COMMIT is sent to a data server, or
3162  * if WRITEs to a data server return NFS_DATA_SYNC.
3163  */
3164 int
3165 pnfs_layoutcommit_inode(struct inode *inode, bool sync)
3166 {
3167 	struct pnfs_layoutdriver_type *ld = NFS_SERVER(inode)->pnfs_curr_ld;
3168 	struct nfs4_layoutcommit_data *data;
3169 	struct nfs_inode *nfsi = NFS_I(inode);
3170 	loff_t end_pos;
3171 	int status;
3172 
3173 	if (!pnfs_layoutcommit_outstanding(inode))
3174 		return 0;
3175 
3176 	dprintk("--> %s inode %lu\n", __func__, inode->i_ino);
3177 
3178 	status = -EAGAIN;
3179 	if (test_and_set_bit(NFS_INO_LAYOUTCOMMITTING, &nfsi->flags)) {
3180 		if (!sync)
3181 			goto out;
3182 		status = wait_on_bit_lock_action(&nfsi->flags,
3183 				NFS_INO_LAYOUTCOMMITTING,
3184 				nfs_wait_bit_killable,
3185 				TASK_KILLABLE);
3186 		if (status)
3187 			goto out;
3188 	}
3189 
3190 	status = -ENOMEM;
3191 	/* Note kzalloc ensures data->res.seq_res.sr_slot == NULL */
3192 	data = kzalloc(sizeof(*data), nfs_io_gfp_mask());
3193 	if (!data)
3194 		goto clear_layoutcommitting;
3195 
3196 	status = 0;
3197 	spin_lock(&inode->i_lock);
3198 	if (!test_and_clear_bit(NFS_INO_LAYOUTCOMMIT, &nfsi->flags))
3199 		goto out_unlock;
3200 
3201 	INIT_LIST_HEAD(&data->lseg_list);
3202 	pnfs_list_write_lseg(inode, &data->lseg_list);
3203 
3204 	end_pos = nfsi->layout->plh_lwb;
3205 
3206 	nfs4_stateid_copy(&data->args.stateid, &nfsi->layout->plh_stateid);
3207 	data->cred = get_cred(nfsi->layout->plh_lc_cred);
3208 	spin_unlock(&inode->i_lock);
3209 
3210 	data->args.inode = inode;
3211 	nfs_fattr_init(&data->fattr);
3212 	data->args.bitmask = NFS_SERVER(inode)->cache_consistency_bitmask;
3213 	data->res.fattr = &data->fattr;
3214 	if (end_pos != 0)
3215 		data->args.lastbytewritten = end_pos - 1;
3216 	else
3217 		data->args.lastbytewritten = U64_MAX;
3218 	data->res.server = NFS_SERVER(inode);
3219 
3220 	if (ld->prepare_layoutcommit) {
3221 		status = ld->prepare_layoutcommit(&data->args);
3222 		if (status) {
3223 			put_cred(data->cred);
3224 			spin_lock(&inode->i_lock);
3225 			set_bit(NFS_INO_LAYOUTCOMMIT, &nfsi->flags);
3226 			if (end_pos > nfsi->layout->plh_lwb)
3227 				nfsi->layout->plh_lwb = end_pos;
3228 			goto out_unlock;
3229 		}
3230 	}
3231 
3232 
3233 	status = nfs4_proc_layoutcommit(data, sync);
3234 out:
3235 	if (status)
3236 		mark_inode_dirty_sync(inode);
3237 	dprintk("<-- %s status %d\n", __func__, status);
3238 	return status;
3239 out_unlock:
3240 	spin_unlock(&inode->i_lock);
3241 	kfree(data);
3242 clear_layoutcommitting:
3243 	pnfs_clear_layoutcommitting(inode);
3244 	goto out;
3245 }
3246 EXPORT_SYMBOL_GPL(pnfs_layoutcommit_inode);
3247 
3248 int
3249 pnfs_generic_sync(struct inode *inode, bool datasync)
3250 {
3251 	return pnfs_layoutcommit_inode(inode, true);
3252 }
3253 EXPORT_SYMBOL_GPL(pnfs_generic_sync);
3254 
3255 struct nfs4_threshold *pnfs_mdsthreshold_alloc(void)
3256 {
3257 	struct nfs4_threshold *thp;
3258 
3259 	thp = kzalloc(sizeof(*thp), nfs_io_gfp_mask());
3260 	if (!thp) {
3261 		dprintk("%s mdsthreshold allocation failed\n", __func__);
3262 		return NULL;
3263 	}
3264 	return thp;
3265 }
3266 
3267 #if IS_ENABLED(CONFIG_NFS_V4_2)
3268 int
3269 pnfs_report_layoutstat(struct inode *inode, gfp_t gfp_flags)
3270 {
3271 	struct pnfs_layoutdriver_type *ld = NFS_SERVER(inode)->pnfs_curr_ld;
3272 	struct nfs_server *server = NFS_SERVER(inode);
3273 	struct nfs_inode *nfsi = NFS_I(inode);
3274 	struct nfs42_layoutstat_data *data;
3275 	struct pnfs_layout_hdr *hdr;
3276 	int status = 0;
3277 
3278 	if (!pnfs_enabled_sb(server) || !ld->prepare_layoutstats)
3279 		goto out;
3280 
3281 	if (!nfs_server_capable(inode, NFS_CAP_LAYOUTSTATS))
3282 		goto out;
3283 
3284 	if (test_and_set_bit(NFS_INO_LAYOUTSTATS, &nfsi->flags))
3285 		goto out;
3286 
3287 	spin_lock(&inode->i_lock);
3288 	if (!NFS_I(inode)->layout) {
3289 		spin_unlock(&inode->i_lock);
3290 		goto out_clear_layoutstats;
3291 	}
3292 	hdr = NFS_I(inode)->layout;
3293 	pnfs_get_layout_hdr(hdr);
3294 	spin_unlock(&inode->i_lock);
3295 
3296 	data = kzalloc(sizeof(*data), gfp_flags);
3297 	if (!data) {
3298 		status = -ENOMEM;
3299 		goto out_put;
3300 	}
3301 
3302 	data->args.fh = NFS_FH(inode);
3303 	data->args.inode = inode;
3304 	status = ld->prepare_layoutstats(&data->args);
3305 	if (status)
3306 		goto out_free;
3307 
3308 	status = nfs42_proc_layoutstats_generic(NFS_SERVER(inode), data);
3309 
3310 out:
3311 	dprintk("%s returns %d\n", __func__, status);
3312 	return status;
3313 
3314 out_free:
3315 	kfree(data);
3316 out_put:
3317 	pnfs_put_layout_hdr(hdr);
3318 out_clear_layoutstats:
3319 	smp_mb__before_atomic();
3320 	clear_bit(NFS_INO_LAYOUTSTATS, &nfsi->flags);
3321 	smp_mb__after_atomic();
3322 	goto out;
3323 }
3324 EXPORT_SYMBOL_GPL(pnfs_report_layoutstat);
3325 #endif
3326 
3327 unsigned int layoutstats_timer;
3328 module_param(layoutstats_timer, uint, 0644);
3329 EXPORT_SYMBOL_GPL(layoutstats_timer);
3330