xref: /linux-6.15/fs/nfs/write.c (revision 2f1f3104)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * linux/fs/nfs/write.c
4  *
5  * Write file data over NFS.
6  *
7  * Copyright (C) 1996, 1997, Olaf Kirch <[email protected]>
8  */
9 
10 #include <linux/types.h>
11 #include <linux/slab.h>
12 #include <linux/mm.h>
13 #include <linux/pagemap.h>
14 #include <linux/file.h>
15 #include <linux/writeback.h>
16 #include <linux/swap.h>
17 #include <linux/migrate.h>
18 
19 #include <linux/sunrpc/clnt.h>
20 #include <linux/nfs_fs.h>
21 #include <linux/nfs_mount.h>
22 #include <linux/nfs_page.h>
23 #include <linux/backing-dev.h>
24 #include <linux/export.h>
25 #include <linux/freezer.h>
26 #include <linux/wait.h>
27 #include <linux/iversion.h>
28 #include <linux/filelock.h>
29 
30 #include <linux/uaccess.h>
31 #include <linux/sched/mm.h>
32 
33 #include "delegation.h"
34 #include "internal.h"
35 #include "iostat.h"
36 #include "nfs4_fs.h"
37 #include "fscache.h"
38 #include "pnfs.h"
39 
40 #include "nfstrace.h"
41 
42 #define NFSDBG_FACILITY		NFSDBG_PAGECACHE
43 
44 #define MIN_POOL_WRITE		(32)
45 #define MIN_POOL_COMMIT		(4)
46 
47 struct nfs_io_completion {
48 	void (*complete)(void *data);
49 	void *data;
50 	struct kref refcount;
51 };
52 
53 /*
54  * Local function declarations
55  */
56 static void nfs_redirty_request(struct nfs_page *req);
57 static const struct rpc_call_ops nfs_commit_ops;
58 static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops;
59 static const struct nfs_commit_completion_ops nfs_commit_completion_ops;
60 static const struct nfs_rw_ops nfs_rw_write_ops;
61 static void nfs_inode_remove_request(struct nfs_page *req);
62 static void nfs_clear_request_commit(struct nfs_commit_info *cinfo,
63 				     struct nfs_page *req);
64 static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
65 				      struct inode *inode);
66 static struct nfs_page *
67 nfs_page_search_commits_for_head_request_locked(struct nfs_inode *nfsi,
68 						struct folio *folio);
69 
70 static struct kmem_cache *nfs_wdata_cachep;
71 static mempool_t *nfs_wdata_mempool;
72 static struct kmem_cache *nfs_cdata_cachep;
73 static mempool_t *nfs_commit_mempool;
74 
75 struct nfs_commit_data *nfs_commitdata_alloc(void)
76 {
77 	struct nfs_commit_data *p;
78 
79 	p = kmem_cache_zalloc(nfs_cdata_cachep, nfs_io_gfp_mask());
80 	if (!p) {
81 		p = mempool_alloc(nfs_commit_mempool, GFP_NOWAIT);
82 		if (!p)
83 			return NULL;
84 		memset(p, 0, sizeof(*p));
85 	}
86 	INIT_LIST_HEAD(&p->pages);
87 	return p;
88 }
89 EXPORT_SYMBOL_GPL(nfs_commitdata_alloc);
90 
91 void nfs_commit_free(struct nfs_commit_data *p)
92 {
93 	mempool_free(p, nfs_commit_mempool);
94 }
95 EXPORT_SYMBOL_GPL(nfs_commit_free);
96 
97 static struct nfs_pgio_header *nfs_writehdr_alloc(void)
98 {
99 	struct nfs_pgio_header *p;
100 
101 	p = kmem_cache_zalloc(nfs_wdata_cachep, nfs_io_gfp_mask());
102 	if (!p) {
103 		p = mempool_alloc(nfs_wdata_mempool, GFP_NOWAIT);
104 		if (!p)
105 			return NULL;
106 		memset(p, 0, sizeof(*p));
107 	}
108 	p->rw_mode = FMODE_WRITE;
109 	return p;
110 }
111 
112 static void nfs_writehdr_free(struct nfs_pgio_header *hdr)
113 {
114 	mempool_free(hdr, nfs_wdata_mempool);
115 }
116 
117 static struct nfs_io_completion *nfs_io_completion_alloc(gfp_t gfp_flags)
118 {
119 	return kmalloc(sizeof(struct nfs_io_completion), gfp_flags);
120 }
121 
122 static void nfs_io_completion_init(struct nfs_io_completion *ioc,
123 		void (*complete)(void *), void *data)
124 {
125 	ioc->complete = complete;
126 	ioc->data = data;
127 	kref_init(&ioc->refcount);
128 }
129 
130 static void nfs_io_completion_release(struct kref *kref)
131 {
132 	struct nfs_io_completion *ioc = container_of(kref,
133 			struct nfs_io_completion, refcount);
134 	ioc->complete(ioc->data);
135 	kfree(ioc);
136 }
137 
138 static void nfs_io_completion_get(struct nfs_io_completion *ioc)
139 {
140 	if (ioc != NULL)
141 		kref_get(&ioc->refcount);
142 }
143 
144 static void nfs_io_completion_put(struct nfs_io_completion *ioc)
145 {
146 	if (ioc != NULL)
147 		kref_put(&ioc->refcount, nfs_io_completion_release);
148 }
149 
150 static void
151 nfs_page_set_inode_ref(struct nfs_page *req, struct inode *inode)
152 {
153 	if (!test_and_set_bit(PG_INODE_REF, &req->wb_flags)) {
154 		kref_get(&req->wb_kref);
155 		atomic_long_inc(&NFS_I(inode)->nrequests);
156 	}
157 }
158 
159 static int
160 nfs_cancel_remove_inode(struct nfs_page *req, struct inode *inode)
161 {
162 	int ret;
163 
164 	if (!test_bit(PG_REMOVE, &req->wb_flags))
165 		return 0;
166 	ret = nfs_page_group_lock(req);
167 	if (ret)
168 		return ret;
169 	if (test_and_clear_bit(PG_REMOVE, &req->wb_flags))
170 		nfs_page_set_inode_ref(req, inode);
171 	nfs_page_group_unlock(req);
172 	return 0;
173 }
174 
175 static struct nfs_page *nfs_folio_private_request(struct folio *folio)
176 {
177 	return folio_get_private(folio);
178 }
179 
180 /**
181  * nfs_folio_find_private_request - find head request associated with a folio
182  * @folio: pointer to folio
183  *
184  * must be called while holding the inode lock.
185  *
186  * returns matching head request with reference held, or NULL if not found.
187  */
188 static struct nfs_page *nfs_folio_find_private_request(struct folio *folio)
189 {
190 	struct address_space *mapping = folio_file_mapping(folio);
191 	struct nfs_page *req;
192 
193 	if (!folio_test_private(folio))
194 		return NULL;
195 	spin_lock(&mapping->i_private_lock);
196 	req = nfs_folio_private_request(folio);
197 	if (req) {
198 		WARN_ON_ONCE(req->wb_head != req);
199 		kref_get(&req->wb_kref);
200 	}
201 	spin_unlock(&mapping->i_private_lock);
202 	return req;
203 }
204 
205 static struct nfs_page *nfs_folio_find_swap_request(struct folio *folio)
206 {
207 	struct inode *inode = folio_file_mapping(folio)->host;
208 	struct nfs_inode *nfsi = NFS_I(inode);
209 	struct nfs_page *req = NULL;
210 	if (!folio_test_swapcache(folio))
211 		return NULL;
212 	mutex_lock(&nfsi->commit_mutex);
213 	if (folio_test_swapcache(folio)) {
214 		req = nfs_page_search_commits_for_head_request_locked(nfsi,
215 								      folio);
216 		if (req) {
217 			WARN_ON_ONCE(req->wb_head != req);
218 			kref_get(&req->wb_kref);
219 		}
220 	}
221 	mutex_unlock(&nfsi->commit_mutex);
222 	return req;
223 }
224 
225 /**
226  * nfs_folio_find_head_request - find head request associated with a folio
227  * @folio: pointer to folio
228  *
229  * returns matching head request with reference held, or NULL if not found.
230  */
231 static struct nfs_page *nfs_folio_find_head_request(struct folio *folio)
232 {
233 	struct nfs_page *req;
234 
235 	req = nfs_folio_find_private_request(folio);
236 	if (!req)
237 		req = nfs_folio_find_swap_request(folio);
238 	return req;
239 }
240 
241 static struct nfs_page *nfs_folio_find_and_lock_request(struct folio *folio)
242 {
243 	struct inode *inode = folio_file_mapping(folio)->host;
244 	struct nfs_page *req, *head;
245 	int ret;
246 
247 	for (;;) {
248 		req = nfs_folio_find_head_request(folio);
249 		if (!req)
250 			return req;
251 		head = nfs_page_group_lock_head(req);
252 		if (head != req)
253 			nfs_release_request(req);
254 		if (IS_ERR(head))
255 			return head;
256 		ret = nfs_cancel_remove_inode(head, inode);
257 		if (ret < 0) {
258 			nfs_unlock_and_release_request(head);
259 			return ERR_PTR(ret);
260 		}
261 		/* Ensure that nobody removed the request before we locked it */
262 		if (head == nfs_folio_private_request(folio))
263 			break;
264 		if (folio_test_swapcache(folio))
265 			break;
266 		nfs_unlock_and_release_request(head);
267 	}
268 	return head;
269 }
270 
271 /* Adjust the file length if we're writing beyond the end */
272 static void nfs_grow_file(struct folio *folio, unsigned int offset,
273 			  unsigned int count)
274 {
275 	struct inode *inode = folio_file_mapping(folio)->host;
276 	loff_t end, i_size;
277 	pgoff_t end_index;
278 
279 	spin_lock(&inode->i_lock);
280 	i_size = i_size_read(inode);
281 	end_index = ((i_size - 1) >> folio_shift(folio)) << folio_order(folio);
282 	if (i_size > 0 && folio_index(folio) < end_index)
283 		goto out;
284 	end = folio_file_pos(folio) + (loff_t)offset + (loff_t)count;
285 	if (i_size >= end)
286 		goto out;
287 	trace_nfs_size_grow(inode, end);
288 	i_size_write(inode, end);
289 	NFS_I(inode)->cache_validity &= ~NFS_INO_INVALID_SIZE;
290 	nfs_inc_stats(inode, NFSIOS_EXTENDWRITE);
291 out:
292 	/* Atomically update timestamps if they are delegated to us. */
293 	nfs_update_delegated_mtime_locked(inode);
294 	spin_unlock(&inode->i_lock);
295 	nfs_fscache_invalidate(inode, 0);
296 }
297 
298 /* A writeback failed: mark the page as bad, and invalidate the page cache */
299 static void nfs_set_pageerror(struct address_space *mapping)
300 {
301 	struct inode *inode = mapping->host;
302 
303 	nfs_zap_mapping(mapping->host, mapping);
304 	/* Force file size revalidation */
305 	spin_lock(&inode->i_lock);
306 	nfs_set_cache_invalid(inode, NFS_INO_REVAL_FORCED |
307 					     NFS_INO_INVALID_CHANGE |
308 					     NFS_INO_INVALID_SIZE);
309 	spin_unlock(&inode->i_lock);
310 }
311 
312 static void nfs_mapping_set_error(struct folio *folio, int error)
313 {
314 	struct address_space *mapping = folio_file_mapping(folio);
315 
316 	folio_set_error(folio);
317 	filemap_set_wb_err(mapping, error);
318 	if (mapping->host)
319 		errseq_set(&mapping->host->i_sb->s_wb_err,
320 			   error == -ENOSPC ? -ENOSPC : -EIO);
321 	nfs_set_pageerror(mapping);
322 }
323 
324 /*
325  * nfs_page_group_search_locked
326  * @head - head request of page group
327  * @page_offset - offset into page
328  *
329  * Search page group with head @head to find a request that contains the
330  * page offset @page_offset.
331  *
332  * Returns a pointer to the first matching nfs request, or NULL if no
333  * match is found.
334  *
335  * Must be called with the page group lock held
336  */
337 static struct nfs_page *
338 nfs_page_group_search_locked(struct nfs_page *head, unsigned int page_offset)
339 {
340 	struct nfs_page *req;
341 
342 	req = head;
343 	do {
344 		if (page_offset >= req->wb_pgbase &&
345 		    page_offset < (req->wb_pgbase + req->wb_bytes))
346 			return req;
347 
348 		req = req->wb_this_page;
349 	} while (req != head);
350 
351 	return NULL;
352 }
353 
354 /*
355  * nfs_page_group_covers_page
356  * @head - head request of page group
357  *
358  * Return true if the page group with head @head covers the whole page,
359  * returns false otherwise
360  */
361 static bool nfs_page_group_covers_page(struct nfs_page *req)
362 {
363 	unsigned int len = nfs_folio_length(nfs_page_to_folio(req));
364 	struct nfs_page *tmp;
365 	unsigned int pos = 0;
366 
367 	nfs_page_group_lock(req);
368 
369 	for (;;) {
370 		tmp = nfs_page_group_search_locked(req->wb_head, pos);
371 		if (!tmp)
372 			break;
373 		pos = tmp->wb_pgbase + tmp->wb_bytes;
374 	}
375 
376 	nfs_page_group_unlock(req);
377 	return pos >= len;
378 }
379 
380 /* We can set the PG_uptodate flag if we see that a write request
381  * covers the full page.
382  */
383 static void nfs_mark_uptodate(struct nfs_page *req)
384 {
385 	struct folio *folio = nfs_page_to_folio(req);
386 
387 	if (folio_test_uptodate(folio))
388 		return;
389 	if (!nfs_page_group_covers_page(req))
390 		return;
391 	folio_mark_uptodate(folio);
392 }
393 
394 static int wb_priority(struct writeback_control *wbc)
395 {
396 	int ret = 0;
397 
398 	if (wbc->sync_mode == WB_SYNC_ALL)
399 		ret = FLUSH_COND_STABLE;
400 	return ret;
401 }
402 
403 /*
404  * NFS congestion control
405  */
406 
407 int nfs_congestion_kb;
408 
409 #define NFS_CONGESTION_ON_THRESH 	(nfs_congestion_kb >> (PAGE_SHIFT-10))
410 #define NFS_CONGESTION_OFF_THRESH	\
411 	(NFS_CONGESTION_ON_THRESH - (NFS_CONGESTION_ON_THRESH >> 2))
412 
413 static void nfs_folio_set_writeback(struct folio *folio)
414 {
415 	struct nfs_server *nfss = NFS_SERVER(folio_file_mapping(folio)->host);
416 
417 	folio_start_writeback(folio);
418 	if (atomic_long_inc_return(&nfss->writeback) > NFS_CONGESTION_ON_THRESH)
419 		nfss->write_congested = 1;
420 }
421 
422 static void nfs_folio_end_writeback(struct folio *folio)
423 {
424 	struct nfs_server *nfss = NFS_SERVER(folio_file_mapping(folio)->host);
425 
426 	folio_end_writeback(folio);
427 	if (atomic_long_dec_return(&nfss->writeback) <
428 	    NFS_CONGESTION_OFF_THRESH) {
429 		nfss->write_congested = 0;
430 		wake_up_all(&nfss->write_congestion_wait);
431 	}
432 }
433 
434 static void nfs_page_end_writeback(struct nfs_page *req)
435 {
436 	if (nfs_page_group_sync_on_bit(req, PG_WB_END)) {
437 		nfs_unlock_request(req);
438 		nfs_folio_end_writeback(nfs_page_to_folio(req));
439 	} else
440 		nfs_unlock_request(req);
441 }
442 
443 /*
444  * nfs_destroy_unlinked_subrequests - destroy recently unlinked subrequests
445  *
446  * @destroy_list - request list (using wb_this_page) terminated by @old_head
447  * @old_head - the old head of the list
448  *
449  * All subrequests must be locked and removed from all lists, so at this point
450  * they are only "active" in this function, and possibly in nfs_wait_on_request
451  * with a reference held by some other context.
452  */
453 static void
454 nfs_destroy_unlinked_subrequests(struct nfs_page *destroy_list,
455 				 struct nfs_page *old_head,
456 				 struct inode *inode)
457 {
458 	while (destroy_list) {
459 		struct nfs_page *subreq = destroy_list;
460 
461 		destroy_list = (subreq->wb_this_page == old_head) ?
462 				   NULL : subreq->wb_this_page;
463 
464 		/* Note: lock subreq in order to change subreq->wb_head */
465 		nfs_page_set_headlock(subreq);
466 		WARN_ON_ONCE(old_head != subreq->wb_head);
467 
468 		/* make sure old group is not used */
469 		subreq->wb_this_page = subreq;
470 		subreq->wb_head = subreq;
471 
472 		clear_bit(PG_REMOVE, &subreq->wb_flags);
473 
474 		/* Note: races with nfs_page_group_destroy() */
475 		if (!kref_read(&subreq->wb_kref)) {
476 			/* Check if we raced with nfs_page_group_destroy() */
477 			if (test_and_clear_bit(PG_TEARDOWN, &subreq->wb_flags)) {
478 				nfs_page_clear_headlock(subreq);
479 				nfs_free_request(subreq);
480 			} else
481 				nfs_page_clear_headlock(subreq);
482 			continue;
483 		}
484 		nfs_page_clear_headlock(subreq);
485 
486 		nfs_release_request(old_head);
487 
488 		if (test_and_clear_bit(PG_INODE_REF, &subreq->wb_flags)) {
489 			nfs_release_request(subreq);
490 			atomic_long_dec(&NFS_I(inode)->nrequests);
491 		}
492 
493 		/* subreq is now totally disconnected from page group or any
494 		 * write / commit lists. last chance to wake any waiters */
495 		nfs_unlock_and_release_request(subreq);
496 	}
497 }
498 
499 /*
500  * nfs_join_page_group - destroy subrequests of the head req
501  * @head: the page used to lookup the "page group" of nfs_page structures
502  * @inode: Inode to which the request belongs.
503  *
504  * This function joins all sub requests to the head request by first
505  * locking all requests in the group, cancelling any pending operations
506  * and finally updating the head request to cover the whole range covered by
507  * the (former) group.  All subrequests are removed from any write or commit
508  * lists, unlinked from the group and destroyed.
509  */
510 void nfs_join_page_group(struct nfs_page *head, struct nfs_commit_info *cinfo,
511 			 struct inode *inode)
512 {
513 	struct nfs_page *subreq;
514 	struct nfs_page *destroy_list = NULL;
515 	unsigned int pgbase, off, bytes;
516 
517 	pgbase = head->wb_pgbase;
518 	bytes = head->wb_bytes;
519 	off = head->wb_offset;
520 	for (subreq = head->wb_this_page; subreq != head;
521 			subreq = subreq->wb_this_page) {
522 		/* Subrequests should always form a contiguous range */
523 		if (pgbase > subreq->wb_pgbase) {
524 			off -= pgbase - subreq->wb_pgbase;
525 			bytes += pgbase - subreq->wb_pgbase;
526 			pgbase = subreq->wb_pgbase;
527 		}
528 		bytes = max(subreq->wb_pgbase + subreq->wb_bytes
529 				- pgbase, bytes);
530 	}
531 
532 	/* Set the head request's range to cover the former page group */
533 	head->wb_pgbase = pgbase;
534 	head->wb_bytes = bytes;
535 	head->wb_offset = off;
536 
537 	/* Now that all requests are locked, make sure they aren't on any list.
538 	 * Commit list removal accounting is done after locks are dropped */
539 	subreq = head;
540 	do {
541 		nfs_clear_request_commit(cinfo, subreq);
542 		subreq = subreq->wb_this_page;
543 	} while (subreq != head);
544 
545 	/* unlink subrequests from head, destroy them later */
546 	if (head->wb_this_page != head) {
547 		/* destroy list will be terminated by head */
548 		destroy_list = head->wb_this_page;
549 		head->wb_this_page = head;
550 	}
551 
552 	nfs_destroy_unlinked_subrequests(destroy_list, head, inode);
553 }
554 
555 /*
556  * nfs_lock_and_join_requests - join all subreqs to the head req
557  * @folio: the folio used to lookup the "page group" of nfs_page structures
558  *
559  * This function joins all sub requests to the head request by first
560  * locking all requests in the group, cancelling any pending operations
561  * and finally updating the head request to cover the whole range covered by
562  * the (former) group.  All subrequests are removed from any write or commit
563  * lists, unlinked from the group and destroyed.
564  *
565  * Returns a locked, referenced pointer to the head request - which after
566  * this call is guaranteed to be the only request associated with the page.
567  * Returns NULL if no requests are found for @folio, or a ERR_PTR if an
568  * error was encountered.
569  */
570 static struct nfs_page *nfs_lock_and_join_requests(struct folio *folio)
571 {
572 	struct inode *inode = folio_file_mapping(folio)->host;
573 	struct nfs_page *head;
574 	struct nfs_commit_info cinfo;
575 	int ret;
576 
577 	nfs_init_cinfo_from_inode(&cinfo, inode);
578 	/*
579 	 * A reference is taken only on the head request which acts as a
580 	 * reference to the whole page group - the group will not be destroyed
581 	 * until the head reference is released.
582 	 */
583 	head = nfs_folio_find_and_lock_request(folio);
584 	if (IS_ERR_OR_NULL(head))
585 		return head;
586 
587 	/* lock each request in the page group */
588 	ret = nfs_page_group_lock_subrequests(head);
589 	if (ret < 0) {
590 		nfs_unlock_and_release_request(head);
591 		return ERR_PTR(ret);
592 	}
593 
594 	nfs_join_page_group(head, &cinfo, inode);
595 
596 	return head;
597 }
598 
599 static void nfs_write_error(struct nfs_page *req, int error)
600 {
601 	trace_nfs_write_error(nfs_page_to_inode(req), req, error);
602 	nfs_mapping_set_error(nfs_page_to_folio(req), error);
603 	nfs_inode_remove_request(req);
604 	nfs_page_end_writeback(req);
605 	nfs_release_request(req);
606 }
607 
608 /*
609  * Find an associated nfs write request, and prepare to flush it out
610  * May return an error if the user signalled nfs_wait_on_request().
611  */
612 static int nfs_page_async_flush(struct folio *folio,
613 				struct writeback_control *wbc,
614 				struct nfs_pageio_descriptor *pgio)
615 {
616 	struct nfs_page *req;
617 	int ret = 0;
618 
619 	req = nfs_lock_and_join_requests(folio);
620 	if (!req)
621 		goto out;
622 	ret = PTR_ERR(req);
623 	if (IS_ERR(req))
624 		goto out;
625 
626 	nfs_folio_set_writeback(folio);
627 	WARN_ON_ONCE(test_bit(PG_CLEAN, &req->wb_flags));
628 
629 	/* If there is a fatal error that covers this write, just exit */
630 	ret = pgio->pg_error;
631 	if (nfs_error_is_fatal_on_server(ret))
632 		goto out_launder;
633 
634 	ret = 0;
635 	if (!nfs_pageio_add_request(pgio, req)) {
636 		ret = pgio->pg_error;
637 		/*
638 		 * Remove the problematic req upon fatal errors on the server
639 		 */
640 		if (nfs_error_is_fatal_on_server(ret))
641 			goto out_launder;
642 		if (wbc->sync_mode == WB_SYNC_NONE)
643 			ret = AOP_WRITEPAGE_ACTIVATE;
644 		folio_redirty_for_writepage(wbc, folio);
645 		nfs_redirty_request(req);
646 		pgio->pg_error = 0;
647 	} else
648 		nfs_add_stats(folio_file_mapping(folio)->host,
649 			      NFSIOS_WRITEPAGES, 1);
650 out:
651 	return ret;
652 out_launder:
653 	nfs_write_error(req, ret);
654 	return 0;
655 }
656 
657 static int nfs_do_writepage(struct folio *folio, struct writeback_control *wbc,
658 			    struct nfs_pageio_descriptor *pgio)
659 {
660 	nfs_pageio_cond_complete(pgio, folio_index(folio));
661 	return nfs_page_async_flush(folio, wbc, pgio);
662 }
663 
664 /*
665  * Write an mmapped page to the server.
666  */
667 static int nfs_writepage_locked(struct folio *folio,
668 				struct writeback_control *wbc)
669 {
670 	struct nfs_pageio_descriptor pgio;
671 	struct inode *inode = folio_file_mapping(folio)->host;
672 	int err;
673 
674 	nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGE);
675 	nfs_pageio_init_write(&pgio, inode, 0, false,
676 			      &nfs_async_write_completion_ops);
677 	err = nfs_do_writepage(folio, wbc, &pgio);
678 	pgio.pg_error = 0;
679 	nfs_pageio_complete(&pgio);
680 	return err;
681 }
682 
683 static int nfs_writepages_callback(struct folio *folio,
684 				   struct writeback_control *wbc, void *data)
685 {
686 	int ret;
687 
688 	ret = nfs_do_writepage(folio, wbc, data);
689 	if (ret != AOP_WRITEPAGE_ACTIVATE)
690 		folio_unlock(folio);
691 	return ret;
692 }
693 
694 static void nfs_io_completion_commit(void *inode)
695 {
696 	nfs_commit_inode(inode, 0);
697 }
698 
699 int nfs_writepages(struct address_space *mapping, struct writeback_control *wbc)
700 {
701 	struct inode *inode = mapping->host;
702 	struct nfs_pageio_descriptor pgio;
703 	struct nfs_io_completion *ioc = NULL;
704 	unsigned int mntflags = NFS_SERVER(inode)->flags;
705 	struct nfs_server *nfss = NFS_SERVER(inode);
706 	int priority = 0;
707 	int err;
708 
709 	/* Wait with writeback until write congestion eases */
710 	if (wbc->sync_mode == WB_SYNC_NONE && nfss->write_congested) {
711 		err = wait_event_killable(nfss->write_congestion_wait,
712 					  nfss->write_congested == 0);
713 		if (err)
714 			return err;
715 	}
716 
717 	nfs_inc_stats(inode, NFSIOS_VFSWRITEPAGES);
718 
719 	if (!(mntflags & NFS_MOUNT_WRITE_EAGER) || wbc->for_kupdate ||
720 	    wbc->for_background || wbc->for_sync || wbc->for_reclaim) {
721 		ioc = nfs_io_completion_alloc(GFP_KERNEL);
722 		if (ioc)
723 			nfs_io_completion_init(ioc, nfs_io_completion_commit,
724 					       inode);
725 		priority = wb_priority(wbc);
726 	}
727 
728 	do {
729 		nfs_pageio_init_write(&pgio, inode, priority, false,
730 				      &nfs_async_write_completion_ops);
731 		pgio.pg_io_completion = ioc;
732 		err = write_cache_pages(mapping, wbc, nfs_writepages_callback,
733 					&pgio);
734 		pgio.pg_error = 0;
735 		nfs_pageio_complete(&pgio);
736 		if (err == -EAGAIN && mntflags & NFS_MOUNT_SOFTERR)
737 			break;
738 	} while (err < 0 && !nfs_error_is_fatal(err));
739 	nfs_io_completion_put(ioc);
740 
741 	if (err < 0)
742 		goto out_err;
743 	return 0;
744 out_err:
745 	return err;
746 }
747 
748 /*
749  * Insert a write request into an inode
750  */
751 static void nfs_inode_add_request(struct nfs_page *req)
752 {
753 	struct folio *folio = nfs_page_to_folio(req);
754 	struct address_space *mapping = folio_file_mapping(folio);
755 	struct nfs_inode *nfsi = NFS_I(mapping->host);
756 
757 	WARN_ON_ONCE(req->wb_this_page != req);
758 
759 	/* Lock the request! */
760 	nfs_lock_request(req);
761 
762 	/*
763 	 * Swap-space should not get truncated. Hence no need to plug the race
764 	 * with invalidate/truncate.
765 	 */
766 	spin_lock(&mapping->i_private_lock);
767 	if (likely(!folio_test_swapcache(folio))) {
768 		set_bit(PG_MAPPED, &req->wb_flags);
769 		folio_set_private(folio);
770 		folio->private = req;
771 	}
772 	spin_unlock(&mapping->i_private_lock);
773 	atomic_long_inc(&nfsi->nrequests);
774 	/* this a head request for a page group - mark it as having an
775 	 * extra reference so sub groups can follow suit.
776 	 * This flag also informs pgio layer when to bump nrequests when
777 	 * adding subrequests. */
778 	WARN_ON(test_and_set_bit(PG_INODE_REF, &req->wb_flags));
779 	kref_get(&req->wb_kref);
780 }
781 
782 /*
783  * Remove a write request from an inode
784  */
785 static void nfs_inode_remove_request(struct nfs_page *req)
786 {
787 	struct nfs_inode *nfsi = NFS_I(nfs_page_to_inode(req));
788 
789 	if (nfs_page_group_sync_on_bit(req, PG_REMOVE)) {
790 		struct folio *folio = nfs_page_to_folio(req->wb_head);
791 		struct address_space *mapping = folio_file_mapping(folio);
792 
793 		spin_lock(&mapping->i_private_lock);
794 		if (likely(folio && !folio_test_swapcache(folio))) {
795 			folio->private = NULL;
796 			folio_clear_private(folio);
797 			clear_bit(PG_MAPPED, &req->wb_head->wb_flags);
798 		}
799 		spin_unlock(&mapping->i_private_lock);
800 	}
801 
802 	if (test_and_clear_bit(PG_INODE_REF, &req->wb_flags)) {
803 		atomic_long_dec(&nfsi->nrequests);
804 		nfs_release_request(req);
805 	}
806 }
807 
808 static void nfs_mark_request_dirty(struct nfs_page *req)
809 {
810 	struct folio *folio = nfs_page_to_folio(req);
811 	if (folio)
812 		filemap_dirty_folio(folio_mapping(folio), folio);
813 }
814 
815 /*
816  * nfs_page_search_commits_for_head_request_locked
817  *
818  * Search through commit lists on @inode for the head request for @folio.
819  * Must be called while holding the inode (which is cinfo) lock.
820  *
821  * Returns the head request if found, or NULL if not found.
822  */
823 static struct nfs_page *
824 nfs_page_search_commits_for_head_request_locked(struct nfs_inode *nfsi,
825 						struct folio *folio)
826 {
827 	struct nfs_page *freq, *t;
828 	struct nfs_commit_info cinfo;
829 	struct inode *inode = &nfsi->vfs_inode;
830 
831 	nfs_init_cinfo_from_inode(&cinfo, inode);
832 
833 	/* search through pnfs commit lists */
834 	freq = pnfs_search_commit_reqs(inode, &cinfo, folio);
835 	if (freq)
836 		return freq->wb_head;
837 
838 	/* Linearly search the commit list for the correct request */
839 	list_for_each_entry_safe(freq, t, &cinfo.mds->list, wb_list) {
840 		if (nfs_page_to_folio(freq) == folio)
841 			return freq->wb_head;
842 	}
843 
844 	return NULL;
845 }
846 
847 /**
848  * nfs_request_add_commit_list_locked - add request to a commit list
849  * @req: pointer to a struct nfs_page
850  * @dst: commit list head
851  * @cinfo: holds list lock and accounting info
852  *
853  * This sets the PG_CLEAN bit, updates the cinfo count of
854  * number of outstanding requests requiring a commit as well as
855  * the MM page stats.
856  *
857  * The caller must hold NFS_I(cinfo->inode)->commit_mutex, and the
858  * nfs_page lock.
859  */
860 void
861 nfs_request_add_commit_list_locked(struct nfs_page *req, struct list_head *dst,
862 			    struct nfs_commit_info *cinfo)
863 {
864 	set_bit(PG_CLEAN, &req->wb_flags);
865 	nfs_list_add_request(req, dst);
866 	atomic_long_inc(&cinfo->mds->ncommit);
867 }
868 EXPORT_SYMBOL_GPL(nfs_request_add_commit_list_locked);
869 
870 /**
871  * nfs_request_add_commit_list - add request to a commit list
872  * @req: pointer to a struct nfs_page
873  * @cinfo: holds list lock and accounting info
874  *
875  * This sets the PG_CLEAN bit, updates the cinfo count of
876  * number of outstanding requests requiring a commit as well as
877  * the MM page stats.
878  *
879  * The caller must _not_ hold the cinfo->lock, but must be
880  * holding the nfs_page lock.
881  */
882 void
883 nfs_request_add_commit_list(struct nfs_page *req, struct nfs_commit_info *cinfo)
884 {
885 	mutex_lock(&NFS_I(cinfo->inode)->commit_mutex);
886 	nfs_request_add_commit_list_locked(req, &cinfo->mds->list, cinfo);
887 	mutex_unlock(&NFS_I(cinfo->inode)->commit_mutex);
888 	nfs_folio_mark_unstable(nfs_page_to_folio(req), cinfo);
889 }
890 EXPORT_SYMBOL_GPL(nfs_request_add_commit_list);
891 
892 /**
893  * nfs_request_remove_commit_list - Remove request from a commit list
894  * @req: pointer to a nfs_page
895  * @cinfo: holds list lock and accounting info
896  *
897  * This clears the PG_CLEAN bit, and updates the cinfo's count of
898  * number of outstanding requests requiring a commit
899  * It does not update the MM page stats.
900  *
901  * The caller _must_ hold the cinfo->lock and the nfs_page lock.
902  */
903 void
904 nfs_request_remove_commit_list(struct nfs_page *req,
905 			       struct nfs_commit_info *cinfo)
906 {
907 	if (!test_and_clear_bit(PG_CLEAN, &(req)->wb_flags))
908 		return;
909 	nfs_list_remove_request(req);
910 	atomic_long_dec(&cinfo->mds->ncommit);
911 }
912 EXPORT_SYMBOL_GPL(nfs_request_remove_commit_list);
913 
914 static void nfs_init_cinfo_from_inode(struct nfs_commit_info *cinfo,
915 				      struct inode *inode)
916 {
917 	cinfo->inode = inode;
918 	cinfo->mds = &NFS_I(inode)->commit_info;
919 	cinfo->ds = pnfs_get_ds_info(inode);
920 	cinfo->dreq = NULL;
921 	cinfo->completion_ops = &nfs_commit_completion_ops;
922 }
923 
924 void nfs_init_cinfo(struct nfs_commit_info *cinfo,
925 		    struct inode *inode,
926 		    struct nfs_direct_req *dreq)
927 {
928 	if (dreq)
929 		nfs_init_cinfo_from_dreq(cinfo, dreq);
930 	else
931 		nfs_init_cinfo_from_inode(cinfo, inode);
932 }
933 EXPORT_SYMBOL_GPL(nfs_init_cinfo);
934 
935 /*
936  * Add a request to the inode's commit list.
937  */
938 void
939 nfs_mark_request_commit(struct nfs_page *req, struct pnfs_layout_segment *lseg,
940 			struct nfs_commit_info *cinfo, u32 ds_commit_idx)
941 {
942 	if (pnfs_mark_request_commit(req, lseg, cinfo, ds_commit_idx))
943 		return;
944 	nfs_request_add_commit_list(req, cinfo);
945 }
946 
947 static void nfs_folio_clear_commit(struct folio *folio)
948 {
949 	if (folio) {
950 		long nr = folio_nr_pages(folio);
951 
952 		node_stat_mod_folio(folio, NR_WRITEBACK, -nr);
953 		wb_stat_mod(&inode_to_bdi(folio_file_mapping(folio)->host)->wb,
954 			    WB_WRITEBACK, -nr);
955 	}
956 }
957 
958 /* Called holding the request lock on @req */
959 static void nfs_clear_request_commit(struct nfs_commit_info *cinfo,
960 				     struct nfs_page *req)
961 {
962 	if (test_bit(PG_CLEAN, &req->wb_flags)) {
963 		struct nfs_open_context *ctx = nfs_req_openctx(req);
964 		struct inode *inode = d_inode(ctx->dentry);
965 
966 		mutex_lock(&NFS_I(inode)->commit_mutex);
967 		if (!pnfs_clear_request_commit(req, cinfo)) {
968 			nfs_request_remove_commit_list(req, cinfo);
969 		}
970 		mutex_unlock(&NFS_I(inode)->commit_mutex);
971 		nfs_folio_clear_commit(nfs_page_to_folio(req));
972 	}
973 }
974 
975 int nfs_write_need_commit(struct nfs_pgio_header *hdr)
976 {
977 	if (hdr->verf.committed == NFS_DATA_SYNC)
978 		return hdr->lseg == NULL;
979 	return hdr->verf.committed != NFS_FILE_SYNC;
980 }
981 
982 static void nfs_async_write_init(struct nfs_pgio_header *hdr)
983 {
984 	nfs_io_completion_get(hdr->io_completion);
985 }
986 
987 static void nfs_write_completion(struct nfs_pgio_header *hdr)
988 {
989 	struct nfs_commit_info cinfo;
990 	unsigned long bytes = 0;
991 
992 	if (test_bit(NFS_IOHDR_REDO, &hdr->flags))
993 		goto out;
994 	nfs_init_cinfo_from_inode(&cinfo, hdr->inode);
995 	while (!list_empty(&hdr->pages)) {
996 		struct nfs_page *req = nfs_list_entry(hdr->pages.next);
997 
998 		bytes += req->wb_bytes;
999 		nfs_list_remove_request(req);
1000 		if (test_bit(NFS_IOHDR_ERROR, &hdr->flags) &&
1001 		    (hdr->good_bytes < bytes)) {
1002 			trace_nfs_comp_error(hdr->inode, req, hdr->error);
1003 			nfs_mapping_set_error(nfs_page_to_folio(req),
1004 					      hdr->error);
1005 			goto remove_req;
1006 		}
1007 		if (nfs_write_need_commit(hdr)) {
1008 			/* Reset wb_nio, since the write was successful. */
1009 			req->wb_nio = 0;
1010 			memcpy(&req->wb_verf, &hdr->verf.verifier, sizeof(req->wb_verf));
1011 			nfs_mark_request_commit(req, hdr->lseg, &cinfo,
1012 				hdr->pgio_mirror_idx);
1013 			goto next;
1014 		}
1015 remove_req:
1016 		nfs_inode_remove_request(req);
1017 next:
1018 		nfs_page_end_writeback(req);
1019 		nfs_release_request(req);
1020 	}
1021 out:
1022 	nfs_io_completion_put(hdr->io_completion);
1023 	hdr->release(hdr);
1024 }
1025 
1026 unsigned long
1027 nfs_reqs_to_commit(struct nfs_commit_info *cinfo)
1028 {
1029 	return atomic_long_read(&cinfo->mds->ncommit);
1030 }
1031 
1032 /* NFS_I(cinfo->inode)->commit_mutex held by caller */
1033 int
1034 nfs_scan_commit_list(struct list_head *src, struct list_head *dst,
1035 		     struct nfs_commit_info *cinfo, int max)
1036 {
1037 	struct nfs_page *req, *tmp;
1038 	int ret = 0;
1039 
1040 	list_for_each_entry_safe(req, tmp, src, wb_list) {
1041 		kref_get(&req->wb_kref);
1042 		if (!nfs_lock_request(req)) {
1043 			nfs_release_request(req);
1044 			continue;
1045 		}
1046 		nfs_request_remove_commit_list(req, cinfo);
1047 		clear_bit(PG_COMMIT_TO_DS, &req->wb_flags);
1048 		nfs_list_add_request(req, dst);
1049 		ret++;
1050 		if ((ret == max) && !cinfo->dreq)
1051 			break;
1052 		cond_resched();
1053 	}
1054 	return ret;
1055 }
1056 EXPORT_SYMBOL_GPL(nfs_scan_commit_list);
1057 
1058 /*
1059  * nfs_scan_commit - Scan an inode for commit requests
1060  * @inode: NFS inode to scan
1061  * @dst: mds destination list
1062  * @cinfo: mds and ds lists of reqs ready to commit
1063  *
1064  * Moves requests from the inode's 'commit' request list.
1065  * The requests are *not* checked to ensure that they form a contiguous set.
1066  */
1067 int
1068 nfs_scan_commit(struct inode *inode, struct list_head *dst,
1069 		struct nfs_commit_info *cinfo)
1070 {
1071 	int ret = 0;
1072 
1073 	if (!atomic_long_read(&cinfo->mds->ncommit))
1074 		return 0;
1075 	mutex_lock(&NFS_I(cinfo->inode)->commit_mutex);
1076 	if (atomic_long_read(&cinfo->mds->ncommit) > 0) {
1077 		const int max = INT_MAX;
1078 
1079 		ret = nfs_scan_commit_list(&cinfo->mds->list, dst,
1080 					   cinfo, max);
1081 		ret += pnfs_scan_commit_lists(inode, cinfo, max - ret);
1082 	}
1083 	mutex_unlock(&NFS_I(cinfo->inode)->commit_mutex);
1084 	return ret;
1085 }
1086 
1087 /*
1088  * Search for an existing write request, and attempt to update
1089  * it to reflect a new dirty region on a given page.
1090  *
1091  * If the attempt fails, then the existing request is flushed out
1092  * to disk.
1093  */
1094 static struct nfs_page *nfs_try_to_update_request(struct folio *folio,
1095 						  unsigned int offset,
1096 						  unsigned int bytes)
1097 {
1098 	struct nfs_page *req;
1099 	unsigned int rqend;
1100 	unsigned int end;
1101 	int error;
1102 
1103 	end = offset + bytes;
1104 
1105 	req = nfs_lock_and_join_requests(folio);
1106 	if (IS_ERR_OR_NULL(req))
1107 		return req;
1108 
1109 	rqend = req->wb_offset + req->wb_bytes;
1110 	/*
1111 	 * Tell the caller to flush out the request if
1112 	 * the offsets are non-contiguous.
1113 	 * Note: nfs_flush_incompatible() will already
1114 	 * have flushed out requests having wrong owners.
1115 	 */
1116 	if (offset > rqend || end < req->wb_offset)
1117 		goto out_flushme;
1118 
1119 	/* Okay, the request matches. Update the region */
1120 	if (offset < req->wb_offset) {
1121 		req->wb_offset = offset;
1122 		req->wb_pgbase = offset;
1123 	}
1124 	if (end > rqend)
1125 		req->wb_bytes = end - req->wb_offset;
1126 	else
1127 		req->wb_bytes = rqend - req->wb_offset;
1128 	req->wb_nio = 0;
1129 	return req;
1130 out_flushme:
1131 	/*
1132 	 * Note: we mark the request dirty here because
1133 	 * nfs_lock_and_join_requests() cannot preserve
1134 	 * commit flags, so we have to replay the write.
1135 	 */
1136 	nfs_mark_request_dirty(req);
1137 	nfs_unlock_and_release_request(req);
1138 	error = nfs_wb_folio(folio_file_mapping(folio)->host, folio);
1139 	return (error < 0) ? ERR_PTR(error) : NULL;
1140 }
1141 
1142 /*
1143  * Try to update an existing write request, or create one if there is none.
1144  *
1145  * Note: Should always be called with the Page Lock held to prevent races
1146  * if we have to add a new request. Also assumes that the caller has
1147  * already called nfs_flush_incompatible() if necessary.
1148  */
1149 static struct nfs_page *nfs_setup_write_request(struct nfs_open_context *ctx,
1150 						struct folio *folio,
1151 						unsigned int offset,
1152 						unsigned int bytes)
1153 {
1154 	struct nfs_page *req;
1155 
1156 	req = nfs_try_to_update_request(folio, offset, bytes);
1157 	if (req != NULL)
1158 		goto out;
1159 	req = nfs_page_create_from_folio(ctx, folio, offset, bytes);
1160 	if (IS_ERR(req))
1161 		goto out;
1162 	nfs_inode_add_request(req);
1163 out:
1164 	return req;
1165 }
1166 
1167 static int nfs_writepage_setup(struct nfs_open_context *ctx,
1168 			       struct folio *folio, unsigned int offset,
1169 			       unsigned int count)
1170 {
1171 	struct nfs_page *req;
1172 
1173 	req = nfs_setup_write_request(ctx, folio, offset, count);
1174 	if (IS_ERR(req))
1175 		return PTR_ERR(req);
1176 	/* Update file length */
1177 	nfs_grow_file(folio, offset, count);
1178 	nfs_mark_uptodate(req);
1179 	nfs_mark_request_dirty(req);
1180 	nfs_unlock_and_release_request(req);
1181 	return 0;
1182 }
1183 
1184 int nfs_flush_incompatible(struct file *file, struct folio *folio)
1185 {
1186 	struct nfs_open_context *ctx = nfs_file_open_context(file);
1187 	struct nfs_lock_context *l_ctx;
1188 	struct file_lock_context *flctx = locks_inode_context(file_inode(file));
1189 	struct nfs_page	*req;
1190 	int do_flush, status;
1191 	/*
1192 	 * Look for a request corresponding to this page. If there
1193 	 * is one, and it belongs to another file, we flush it out
1194 	 * before we try to copy anything into the page. Do this
1195 	 * due to the lack of an ACCESS-type call in NFSv2.
1196 	 * Also do the same if we find a request from an existing
1197 	 * dropped page.
1198 	 */
1199 	do {
1200 		req = nfs_folio_find_head_request(folio);
1201 		if (req == NULL)
1202 			return 0;
1203 		l_ctx = req->wb_lock_context;
1204 		do_flush = nfs_page_to_folio(req) != folio ||
1205 			   !nfs_match_open_context(nfs_req_openctx(req), ctx);
1206 		if (l_ctx && flctx &&
1207 		    !(list_empty_careful(&flctx->flc_posix) &&
1208 		      list_empty_careful(&flctx->flc_flock))) {
1209 			do_flush |= l_ctx->lockowner != current->files;
1210 		}
1211 		nfs_release_request(req);
1212 		if (!do_flush)
1213 			return 0;
1214 		status = nfs_wb_folio(folio_file_mapping(folio)->host, folio);
1215 	} while (status == 0);
1216 	return status;
1217 }
1218 
1219 /*
1220  * Avoid buffered writes when a open context credential's key would
1221  * expire soon.
1222  *
1223  * Returns -EACCES if the key will expire within RPC_KEY_EXPIRE_FAIL.
1224  *
1225  * Return 0 and set a credential flag which triggers the inode to flush
1226  * and performs  NFS_FILE_SYNC writes if the key will expired within
1227  * RPC_KEY_EXPIRE_TIMEO.
1228  */
1229 int
1230 nfs_key_timeout_notify(struct file *filp, struct inode *inode)
1231 {
1232 	struct nfs_open_context *ctx = nfs_file_open_context(filp);
1233 
1234 	if (nfs_ctx_key_to_expire(ctx, inode) &&
1235 	    !rcu_access_pointer(ctx->ll_cred))
1236 		/* Already expired! */
1237 		return -EACCES;
1238 	return 0;
1239 }
1240 
1241 /*
1242  * Test if the open context credential key is marked to expire soon.
1243  */
1244 bool nfs_ctx_key_to_expire(struct nfs_open_context *ctx, struct inode *inode)
1245 {
1246 	struct rpc_auth *auth = NFS_SERVER(inode)->client->cl_auth;
1247 	struct rpc_cred *cred, *new, *old = NULL;
1248 	struct auth_cred acred = {
1249 		.cred = ctx->cred,
1250 	};
1251 	bool ret = false;
1252 
1253 	rcu_read_lock();
1254 	cred = rcu_dereference(ctx->ll_cred);
1255 	if (cred && !(cred->cr_ops->crkey_timeout &&
1256 		      cred->cr_ops->crkey_timeout(cred)))
1257 		goto out;
1258 	rcu_read_unlock();
1259 
1260 	new = auth->au_ops->lookup_cred(auth, &acred, 0);
1261 	if (new == cred) {
1262 		put_rpccred(new);
1263 		return true;
1264 	}
1265 	if (IS_ERR_OR_NULL(new)) {
1266 		new = NULL;
1267 		ret = true;
1268 	} else if (new->cr_ops->crkey_timeout &&
1269 		   new->cr_ops->crkey_timeout(new))
1270 		ret = true;
1271 
1272 	rcu_read_lock();
1273 	old = rcu_dereference_protected(xchg(&ctx->ll_cred,
1274 					     RCU_INITIALIZER(new)), 1);
1275 out:
1276 	rcu_read_unlock();
1277 	put_rpccred(old);
1278 	return ret;
1279 }
1280 
1281 /*
1282  * If the page cache is marked as unsafe or invalid, then we can't rely on
1283  * the PageUptodate() flag. In this case, we will need to turn off
1284  * write optimisations that depend on the page contents being correct.
1285  */
1286 static bool nfs_folio_write_uptodate(struct folio *folio, unsigned int pagelen)
1287 {
1288 	struct inode *inode = folio_file_mapping(folio)->host;
1289 	struct nfs_inode *nfsi = NFS_I(inode);
1290 
1291 	if (nfs_have_delegated_attributes(inode))
1292 		goto out;
1293 	if (nfsi->cache_validity &
1294 	    (NFS_INO_INVALID_CHANGE | NFS_INO_INVALID_SIZE))
1295 		return false;
1296 	smp_rmb();
1297 	if (test_bit(NFS_INO_INVALIDATING, &nfsi->flags) && pagelen != 0)
1298 		return false;
1299 out:
1300 	if (nfsi->cache_validity & NFS_INO_INVALID_DATA && pagelen != 0)
1301 		return false;
1302 	return folio_test_uptodate(folio) != 0;
1303 }
1304 
1305 static bool
1306 is_whole_file_wrlock(struct file_lock *fl)
1307 {
1308 	return fl->fl_start == 0 && fl->fl_end == OFFSET_MAX &&
1309 			lock_is_write(fl);
1310 }
1311 
1312 /* If we know the page is up to date, and we're not using byte range locks (or
1313  * if we have the whole file locked for writing), it may be more efficient to
1314  * extend the write to cover the entire page in order to avoid fragmentation
1315  * inefficiencies.
1316  *
1317  * If the file is opened for synchronous writes then we can just skip the rest
1318  * of the checks.
1319  */
1320 static int nfs_can_extend_write(struct file *file, struct folio *folio,
1321 				unsigned int pagelen)
1322 {
1323 	struct inode *inode = file_inode(file);
1324 	struct file_lock_context *flctx = locks_inode_context(inode);
1325 	struct file_lock *fl;
1326 	int ret;
1327 
1328 	if (file->f_flags & O_DSYNC)
1329 		return 0;
1330 	if (!nfs_folio_write_uptodate(folio, pagelen))
1331 		return 0;
1332 	if (nfs_have_write_delegation(inode))
1333 		return 1;
1334 	if (!flctx || (list_empty_careful(&flctx->flc_flock) &&
1335 		       list_empty_careful(&flctx->flc_posix)))
1336 		return 1;
1337 
1338 	/* Check to see if there are whole file write locks */
1339 	ret = 0;
1340 	spin_lock(&flctx->flc_lock);
1341 	if (!list_empty(&flctx->flc_posix)) {
1342 		fl = list_first_entry(&flctx->flc_posix, struct file_lock,
1343 					c.flc_list);
1344 		if (is_whole_file_wrlock(fl))
1345 			ret = 1;
1346 	} else if (!list_empty(&flctx->flc_flock)) {
1347 		fl = list_first_entry(&flctx->flc_flock, struct file_lock,
1348 					c.flc_list);
1349 		if (lock_is_write(fl))
1350 			ret = 1;
1351 	}
1352 	spin_unlock(&flctx->flc_lock);
1353 	return ret;
1354 }
1355 
1356 /*
1357  * Update and possibly write a cached page of an NFS file.
1358  *
1359  * XXX: Keep an eye on generic_file_read to make sure it doesn't do bad
1360  * things with a page scheduled for an RPC call (e.g. invalidate it).
1361  */
1362 int nfs_update_folio(struct file *file, struct folio *folio,
1363 		     unsigned int offset, unsigned int count)
1364 {
1365 	struct nfs_open_context *ctx = nfs_file_open_context(file);
1366 	struct address_space *mapping = folio_file_mapping(folio);
1367 	struct inode *inode = mapping->host;
1368 	unsigned int pagelen = nfs_folio_length(folio);
1369 	int		status = 0;
1370 
1371 	nfs_inc_stats(inode, NFSIOS_VFSUPDATEPAGE);
1372 
1373 	dprintk("NFS:       nfs_update_folio(%pD2 %d@%lld)\n", file, count,
1374 		(long long)(folio_file_pos(folio) + offset));
1375 
1376 	if (!count)
1377 		goto out;
1378 
1379 	if (nfs_can_extend_write(file, folio, pagelen)) {
1380 		count = max(count + offset, pagelen);
1381 		offset = 0;
1382 	}
1383 
1384 	status = nfs_writepage_setup(ctx, folio, offset, count);
1385 	if (status < 0)
1386 		nfs_set_pageerror(mapping);
1387 out:
1388 	dprintk("NFS:       nfs_update_folio returns %d (isize %lld)\n",
1389 			status, (long long)i_size_read(inode));
1390 	return status;
1391 }
1392 
1393 static int flush_task_priority(int how)
1394 {
1395 	switch (how & (FLUSH_HIGHPRI|FLUSH_LOWPRI)) {
1396 		case FLUSH_HIGHPRI:
1397 			return RPC_PRIORITY_HIGH;
1398 		case FLUSH_LOWPRI:
1399 			return RPC_PRIORITY_LOW;
1400 	}
1401 	return RPC_PRIORITY_NORMAL;
1402 }
1403 
1404 static void nfs_initiate_write(struct nfs_pgio_header *hdr,
1405 			       struct rpc_message *msg,
1406 			       const struct nfs_rpc_ops *rpc_ops,
1407 			       struct rpc_task_setup *task_setup_data, int how)
1408 {
1409 	int priority = flush_task_priority(how);
1410 
1411 	if (IS_SWAPFILE(hdr->inode))
1412 		task_setup_data->flags |= RPC_TASK_SWAPPER;
1413 	task_setup_data->priority = priority;
1414 	rpc_ops->write_setup(hdr, msg, &task_setup_data->rpc_client);
1415 	trace_nfs_initiate_write(hdr);
1416 }
1417 
1418 /* If a nfs_flush_* function fails, it should remove reqs from @head and
1419  * call this on each, which will prepare them to be retried on next
1420  * writeback using standard nfs.
1421  */
1422 static void nfs_redirty_request(struct nfs_page *req)
1423 {
1424 	struct nfs_inode *nfsi = NFS_I(nfs_page_to_inode(req));
1425 
1426 	/* Bump the transmission count */
1427 	req->wb_nio++;
1428 	nfs_mark_request_dirty(req);
1429 	atomic_long_inc(&nfsi->redirtied_pages);
1430 	nfs_page_end_writeback(req);
1431 	nfs_release_request(req);
1432 }
1433 
1434 static void nfs_async_write_error(struct list_head *head, int error)
1435 {
1436 	struct nfs_page	*req;
1437 
1438 	while (!list_empty(head)) {
1439 		req = nfs_list_entry(head->next);
1440 		nfs_list_remove_request(req);
1441 		if (nfs_error_is_fatal_on_server(error))
1442 			nfs_write_error(req, error);
1443 		else
1444 			nfs_redirty_request(req);
1445 	}
1446 }
1447 
1448 static void nfs_async_write_reschedule_io(struct nfs_pgio_header *hdr)
1449 {
1450 	nfs_async_write_error(&hdr->pages, 0);
1451 }
1452 
1453 static const struct nfs_pgio_completion_ops nfs_async_write_completion_ops = {
1454 	.init_hdr = nfs_async_write_init,
1455 	.error_cleanup = nfs_async_write_error,
1456 	.completion = nfs_write_completion,
1457 	.reschedule_io = nfs_async_write_reschedule_io,
1458 };
1459 
1460 void nfs_pageio_init_write(struct nfs_pageio_descriptor *pgio,
1461 			       struct inode *inode, int ioflags, bool force_mds,
1462 			       const struct nfs_pgio_completion_ops *compl_ops)
1463 {
1464 	struct nfs_server *server = NFS_SERVER(inode);
1465 	const struct nfs_pageio_ops *pg_ops = &nfs_pgio_rw_ops;
1466 
1467 #ifdef CONFIG_NFS_V4_1
1468 	if (server->pnfs_curr_ld && !force_mds)
1469 		pg_ops = server->pnfs_curr_ld->pg_write_ops;
1470 #endif
1471 	nfs_pageio_init(pgio, inode, pg_ops, compl_ops, &nfs_rw_write_ops,
1472 			server->wsize, ioflags);
1473 }
1474 EXPORT_SYMBOL_GPL(nfs_pageio_init_write);
1475 
1476 void nfs_pageio_reset_write_mds(struct nfs_pageio_descriptor *pgio)
1477 {
1478 	struct nfs_pgio_mirror *mirror;
1479 
1480 	if (pgio->pg_ops && pgio->pg_ops->pg_cleanup)
1481 		pgio->pg_ops->pg_cleanup(pgio);
1482 
1483 	pgio->pg_ops = &nfs_pgio_rw_ops;
1484 
1485 	nfs_pageio_stop_mirroring(pgio);
1486 
1487 	mirror = &pgio->pg_mirrors[0];
1488 	mirror->pg_bsize = NFS_SERVER(pgio->pg_inode)->wsize;
1489 }
1490 EXPORT_SYMBOL_GPL(nfs_pageio_reset_write_mds);
1491 
1492 
1493 void nfs_commit_prepare(struct rpc_task *task, void *calldata)
1494 {
1495 	struct nfs_commit_data *data = calldata;
1496 
1497 	NFS_PROTO(data->inode)->commit_rpc_prepare(task, data);
1498 }
1499 
1500 static void nfs_writeback_check_extend(struct nfs_pgio_header *hdr,
1501 		struct nfs_fattr *fattr)
1502 {
1503 	struct nfs_pgio_args *argp = &hdr->args;
1504 	struct nfs_pgio_res *resp = &hdr->res;
1505 	u64 size = argp->offset + resp->count;
1506 
1507 	if (!(fattr->valid & NFS_ATTR_FATTR_SIZE))
1508 		fattr->size = size;
1509 	if (nfs_size_to_loff_t(fattr->size) < i_size_read(hdr->inode)) {
1510 		fattr->valid &= ~NFS_ATTR_FATTR_SIZE;
1511 		return;
1512 	}
1513 	if (size != fattr->size)
1514 		return;
1515 	/* Set attribute barrier */
1516 	nfs_fattr_set_barrier(fattr);
1517 	/* ...and update size */
1518 	fattr->valid |= NFS_ATTR_FATTR_SIZE;
1519 }
1520 
1521 void nfs_writeback_update_inode(struct nfs_pgio_header *hdr)
1522 {
1523 	struct nfs_fattr *fattr = &hdr->fattr;
1524 	struct inode *inode = hdr->inode;
1525 
1526 	if (nfs_have_delegated_mtime(inode)) {
1527 		spin_lock(&inode->i_lock);
1528 		nfs_set_cache_invalid(inode, NFS_INO_INVALID_BLOCKS);
1529 		spin_unlock(&inode->i_lock);
1530 		return;
1531 	}
1532 
1533 	spin_lock(&inode->i_lock);
1534 	nfs_writeback_check_extend(hdr, fattr);
1535 	nfs_post_op_update_inode_force_wcc_locked(inode, fattr);
1536 	spin_unlock(&inode->i_lock);
1537 }
1538 EXPORT_SYMBOL_GPL(nfs_writeback_update_inode);
1539 
1540 /*
1541  * This function is called when the WRITE call is complete.
1542  */
1543 static int nfs_writeback_done(struct rpc_task *task,
1544 			      struct nfs_pgio_header *hdr,
1545 			      struct inode *inode)
1546 {
1547 	int status;
1548 
1549 	/*
1550 	 * ->write_done will attempt to use post-op attributes to detect
1551 	 * conflicting writes by other clients.  A strict interpretation
1552 	 * of close-to-open would allow us to continue caching even if
1553 	 * another writer had changed the file, but some applications
1554 	 * depend on tighter cache coherency when writing.
1555 	 */
1556 	status = NFS_PROTO(inode)->write_done(task, hdr);
1557 	if (status != 0)
1558 		return status;
1559 
1560 	nfs_add_stats(inode, NFSIOS_SERVERWRITTENBYTES, hdr->res.count);
1561 	trace_nfs_writeback_done(task, hdr);
1562 
1563 	if (task->tk_status >= 0) {
1564 		enum nfs3_stable_how committed = hdr->res.verf->committed;
1565 
1566 		if (committed == NFS_UNSTABLE) {
1567 			/*
1568 			 * We have some uncommitted data on the server at
1569 			 * this point, so ensure that we keep track of that
1570 			 * fact irrespective of what later writes do.
1571 			 */
1572 			set_bit(NFS_IOHDR_UNSTABLE_WRITES, &hdr->flags);
1573 		}
1574 
1575 		if (committed < hdr->args.stable) {
1576 			/* We tried a write call, but the server did not
1577 			 * commit data to stable storage even though we
1578 			 * requested it.
1579 			 * Note: There is a known bug in Tru64 < 5.0 in which
1580 			 *	 the server reports NFS_DATA_SYNC, but performs
1581 			 *	 NFS_FILE_SYNC. We therefore implement this checking
1582 			 *	 as a dprintk() in order to avoid filling syslog.
1583 			 */
1584 			static unsigned long    complain;
1585 
1586 			/* Note this will print the MDS for a DS write */
1587 			if (time_before(complain, jiffies)) {
1588 				dprintk("NFS:       faulty NFS server %s:"
1589 					" (committed = %d) != (stable = %d)\n",
1590 					NFS_SERVER(inode)->nfs_client->cl_hostname,
1591 					committed, hdr->args.stable);
1592 				complain = jiffies + 300 * HZ;
1593 			}
1594 		}
1595 	}
1596 
1597 	/* Deal with the suid/sgid bit corner case */
1598 	if (nfs_should_remove_suid(inode)) {
1599 		spin_lock(&inode->i_lock);
1600 		nfs_set_cache_invalid(inode, NFS_INO_INVALID_MODE);
1601 		spin_unlock(&inode->i_lock);
1602 	}
1603 	return 0;
1604 }
1605 
1606 /*
1607  * This function is called when the WRITE call is complete.
1608  */
1609 static void nfs_writeback_result(struct rpc_task *task,
1610 				 struct nfs_pgio_header *hdr)
1611 {
1612 	struct nfs_pgio_args	*argp = &hdr->args;
1613 	struct nfs_pgio_res	*resp = &hdr->res;
1614 
1615 	if (resp->count < argp->count) {
1616 		static unsigned long    complain;
1617 
1618 		/* This a short write! */
1619 		nfs_inc_stats(hdr->inode, NFSIOS_SHORTWRITE);
1620 
1621 		/* Has the server at least made some progress? */
1622 		if (resp->count == 0) {
1623 			if (time_before(complain, jiffies)) {
1624 				printk(KERN_WARNING
1625 				       "NFS: Server wrote zero bytes, expected %u.\n",
1626 				       argp->count);
1627 				complain = jiffies + 300 * HZ;
1628 			}
1629 			nfs_set_pgio_error(hdr, -EIO, argp->offset);
1630 			task->tk_status = -EIO;
1631 			return;
1632 		}
1633 
1634 		/* For non rpc-based layout drivers, retry-through-MDS */
1635 		if (!task->tk_ops) {
1636 			hdr->pnfs_error = -EAGAIN;
1637 			return;
1638 		}
1639 
1640 		/* Was this an NFSv2 write or an NFSv3 stable write? */
1641 		if (resp->verf->committed != NFS_UNSTABLE) {
1642 			/* Resend from where the server left off */
1643 			hdr->mds_offset += resp->count;
1644 			argp->offset += resp->count;
1645 			argp->pgbase += resp->count;
1646 			argp->count -= resp->count;
1647 		} else {
1648 			/* Resend as a stable write in order to avoid
1649 			 * headaches in the case of a server crash.
1650 			 */
1651 			argp->stable = NFS_FILE_SYNC;
1652 		}
1653 		resp->count = 0;
1654 		resp->verf->committed = 0;
1655 		rpc_restart_call_prepare(task);
1656 	}
1657 }
1658 
1659 static int wait_on_commit(struct nfs_mds_commit_info *cinfo)
1660 {
1661 	return wait_var_event_killable(&cinfo->rpcs_out,
1662 				       !atomic_read(&cinfo->rpcs_out));
1663 }
1664 
1665 void nfs_commit_begin(struct nfs_mds_commit_info *cinfo)
1666 {
1667 	atomic_inc(&cinfo->rpcs_out);
1668 }
1669 
1670 bool nfs_commit_end(struct nfs_mds_commit_info *cinfo)
1671 {
1672 	if (atomic_dec_and_test(&cinfo->rpcs_out)) {
1673 		wake_up_var(&cinfo->rpcs_out);
1674 		return true;
1675 	}
1676 	return false;
1677 }
1678 
1679 void nfs_commitdata_release(struct nfs_commit_data *data)
1680 {
1681 	put_nfs_open_context(data->context);
1682 	nfs_commit_free(data);
1683 }
1684 EXPORT_SYMBOL_GPL(nfs_commitdata_release);
1685 
1686 int nfs_initiate_commit(struct rpc_clnt *clnt, struct nfs_commit_data *data,
1687 			const struct nfs_rpc_ops *nfs_ops,
1688 			const struct rpc_call_ops *call_ops,
1689 			int how, int flags)
1690 {
1691 	struct rpc_task *task;
1692 	int priority = flush_task_priority(how);
1693 	struct rpc_message msg = {
1694 		.rpc_argp = &data->args,
1695 		.rpc_resp = &data->res,
1696 		.rpc_cred = data->cred,
1697 	};
1698 	struct rpc_task_setup task_setup_data = {
1699 		.task = &data->task,
1700 		.rpc_client = clnt,
1701 		.rpc_message = &msg,
1702 		.callback_ops = call_ops,
1703 		.callback_data = data,
1704 		.workqueue = nfsiod_workqueue,
1705 		.flags = RPC_TASK_ASYNC | flags,
1706 		.priority = priority,
1707 	};
1708 
1709 	if (nfs_server_capable(data->inode, NFS_CAP_MOVEABLE))
1710 		task_setup_data.flags |= RPC_TASK_MOVEABLE;
1711 
1712 	/* Set up the initial task struct.  */
1713 	nfs_ops->commit_setup(data, &msg, &task_setup_data.rpc_client);
1714 	trace_nfs_initiate_commit(data);
1715 
1716 	dprintk("NFS: initiated commit call\n");
1717 
1718 	task = rpc_run_task(&task_setup_data);
1719 	if (IS_ERR(task))
1720 		return PTR_ERR(task);
1721 	if (how & FLUSH_SYNC)
1722 		rpc_wait_for_completion_task(task);
1723 	rpc_put_task(task);
1724 	return 0;
1725 }
1726 EXPORT_SYMBOL_GPL(nfs_initiate_commit);
1727 
1728 static loff_t nfs_get_lwb(struct list_head *head)
1729 {
1730 	loff_t lwb = 0;
1731 	struct nfs_page *req;
1732 
1733 	list_for_each_entry(req, head, wb_list)
1734 		if (lwb < (req_offset(req) + req->wb_bytes))
1735 			lwb = req_offset(req) + req->wb_bytes;
1736 
1737 	return lwb;
1738 }
1739 
1740 /*
1741  * Set up the argument/result storage required for the RPC call.
1742  */
1743 void nfs_init_commit(struct nfs_commit_data *data,
1744 		     struct list_head *head,
1745 		     struct pnfs_layout_segment *lseg,
1746 		     struct nfs_commit_info *cinfo)
1747 {
1748 	struct nfs_page *first;
1749 	struct nfs_open_context *ctx;
1750 	struct inode *inode;
1751 
1752 	/* Set up the RPC argument and reply structs
1753 	 * NB: take care not to mess about with data->commit et al. */
1754 
1755 	if (head)
1756 		list_splice_init(head, &data->pages);
1757 
1758 	first = nfs_list_entry(data->pages.next);
1759 	ctx = nfs_req_openctx(first);
1760 	inode = d_inode(ctx->dentry);
1761 
1762 	data->inode	  = inode;
1763 	data->cred	  = ctx->cred;
1764 	data->lseg	  = lseg; /* reference transferred */
1765 	/* only set lwb for pnfs commit */
1766 	if (lseg)
1767 		data->lwb = nfs_get_lwb(&data->pages);
1768 	data->mds_ops     = &nfs_commit_ops;
1769 	data->completion_ops = cinfo->completion_ops;
1770 	data->dreq	  = cinfo->dreq;
1771 
1772 	data->args.fh     = NFS_FH(data->inode);
1773 	/* Note: we always request a commit of the entire inode */
1774 	data->args.offset = 0;
1775 	data->args.count  = 0;
1776 	data->context     = get_nfs_open_context(ctx);
1777 	data->res.fattr   = &data->fattr;
1778 	data->res.verf    = &data->verf;
1779 	nfs_fattr_init(&data->fattr);
1780 	nfs_commit_begin(cinfo->mds);
1781 }
1782 EXPORT_SYMBOL_GPL(nfs_init_commit);
1783 
1784 void nfs_retry_commit(struct list_head *page_list,
1785 		      struct pnfs_layout_segment *lseg,
1786 		      struct nfs_commit_info *cinfo,
1787 		      u32 ds_commit_idx)
1788 {
1789 	struct nfs_page *req;
1790 
1791 	while (!list_empty(page_list)) {
1792 		req = nfs_list_entry(page_list->next);
1793 		nfs_list_remove_request(req);
1794 		nfs_mark_request_commit(req, lseg, cinfo, ds_commit_idx);
1795 		nfs_folio_clear_commit(nfs_page_to_folio(req));
1796 		nfs_unlock_and_release_request(req);
1797 	}
1798 }
1799 EXPORT_SYMBOL_GPL(nfs_retry_commit);
1800 
1801 static void nfs_commit_resched_write(struct nfs_commit_info *cinfo,
1802 				     struct nfs_page *req)
1803 {
1804 	struct folio *folio = nfs_page_to_folio(req);
1805 
1806 	filemap_dirty_folio(folio_mapping(folio), folio);
1807 }
1808 
1809 /*
1810  * Commit dirty pages
1811  */
1812 static int
1813 nfs_commit_list(struct inode *inode, struct list_head *head, int how,
1814 		struct nfs_commit_info *cinfo)
1815 {
1816 	struct nfs_commit_data	*data;
1817 	unsigned short task_flags = 0;
1818 
1819 	/* another commit raced with us */
1820 	if (list_empty(head))
1821 		return 0;
1822 
1823 	data = nfs_commitdata_alloc();
1824 	if (!data) {
1825 		nfs_retry_commit(head, NULL, cinfo, -1);
1826 		return -ENOMEM;
1827 	}
1828 
1829 	/* Set up the argument struct */
1830 	nfs_init_commit(data, head, NULL, cinfo);
1831 	if (NFS_SERVER(inode)->nfs_client->cl_minorversion)
1832 		task_flags = RPC_TASK_MOVEABLE;
1833 	return nfs_initiate_commit(NFS_CLIENT(inode), data, NFS_PROTO(inode),
1834 				   data->mds_ops, how,
1835 				   RPC_TASK_CRED_NOREF | task_flags);
1836 }
1837 
1838 /*
1839  * COMMIT call returned
1840  */
1841 static void nfs_commit_done(struct rpc_task *task, void *calldata)
1842 {
1843 	struct nfs_commit_data	*data = calldata;
1844 
1845 	/* Call the NFS version-specific code */
1846 	NFS_PROTO(data->inode)->commit_done(task, data);
1847 	trace_nfs_commit_done(task, data);
1848 }
1849 
1850 static void nfs_commit_release_pages(struct nfs_commit_data *data)
1851 {
1852 	const struct nfs_writeverf *verf = data->res.verf;
1853 	struct nfs_page	*req;
1854 	int status = data->task.tk_status;
1855 	struct nfs_commit_info cinfo;
1856 	struct folio *folio;
1857 
1858 	while (!list_empty(&data->pages)) {
1859 		req = nfs_list_entry(data->pages.next);
1860 		nfs_list_remove_request(req);
1861 		folio = nfs_page_to_folio(req);
1862 		nfs_folio_clear_commit(folio);
1863 
1864 		dprintk("NFS:       commit (%s/%llu %d@%lld)",
1865 			nfs_req_openctx(req)->dentry->d_sb->s_id,
1866 			(unsigned long long)NFS_FILEID(d_inode(nfs_req_openctx(req)->dentry)),
1867 			req->wb_bytes,
1868 			(long long)req_offset(req));
1869 		if (status < 0) {
1870 			if (folio) {
1871 				trace_nfs_commit_error(data->inode, req,
1872 						       status);
1873 				nfs_mapping_set_error(folio, status);
1874 				nfs_inode_remove_request(req);
1875 			}
1876 			dprintk_cont(", error = %d\n", status);
1877 			goto next;
1878 		}
1879 
1880 		/* Okay, COMMIT succeeded, apparently. Check the verifier
1881 		 * returned by the server against all stored verfs. */
1882 		if (nfs_write_match_verf(verf, req)) {
1883 			/* We have a match */
1884 			if (folio)
1885 				nfs_inode_remove_request(req);
1886 			dprintk_cont(" OK\n");
1887 			goto next;
1888 		}
1889 		/* We have a mismatch. Write the page again */
1890 		dprintk_cont(" mismatch\n");
1891 		nfs_mark_request_dirty(req);
1892 		atomic_long_inc(&NFS_I(data->inode)->redirtied_pages);
1893 	next:
1894 		nfs_unlock_and_release_request(req);
1895 		/* Latency breaker */
1896 		cond_resched();
1897 	}
1898 
1899 	nfs_init_cinfo(&cinfo, data->inode, data->dreq);
1900 	nfs_commit_end(cinfo.mds);
1901 }
1902 
1903 static void nfs_commit_release(void *calldata)
1904 {
1905 	struct nfs_commit_data *data = calldata;
1906 
1907 	data->completion_ops->completion(data);
1908 	nfs_commitdata_release(calldata);
1909 }
1910 
1911 static const struct rpc_call_ops nfs_commit_ops = {
1912 	.rpc_call_prepare = nfs_commit_prepare,
1913 	.rpc_call_done = nfs_commit_done,
1914 	.rpc_release = nfs_commit_release,
1915 };
1916 
1917 static const struct nfs_commit_completion_ops nfs_commit_completion_ops = {
1918 	.completion = nfs_commit_release_pages,
1919 	.resched_write = nfs_commit_resched_write,
1920 };
1921 
1922 int nfs_generic_commit_list(struct inode *inode, struct list_head *head,
1923 			    int how, struct nfs_commit_info *cinfo)
1924 {
1925 	int status;
1926 
1927 	status = pnfs_commit_list(inode, head, how, cinfo);
1928 	if (status == PNFS_NOT_ATTEMPTED)
1929 		status = nfs_commit_list(inode, head, how, cinfo);
1930 	return status;
1931 }
1932 
1933 static int __nfs_commit_inode(struct inode *inode, int how,
1934 		struct writeback_control *wbc)
1935 {
1936 	LIST_HEAD(head);
1937 	struct nfs_commit_info cinfo;
1938 	int may_wait = how & FLUSH_SYNC;
1939 	int ret, nscan;
1940 
1941 	how &= ~FLUSH_SYNC;
1942 	nfs_init_cinfo_from_inode(&cinfo, inode);
1943 	nfs_commit_begin(cinfo.mds);
1944 	for (;;) {
1945 		ret = nscan = nfs_scan_commit(inode, &head, &cinfo);
1946 		if (ret <= 0)
1947 			break;
1948 		ret = nfs_generic_commit_list(inode, &head, how, &cinfo);
1949 		if (ret < 0)
1950 			break;
1951 		ret = 0;
1952 		if (wbc && wbc->sync_mode == WB_SYNC_NONE) {
1953 			if (nscan < wbc->nr_to_write)
1954 				wbc->nr_to_write -= nscan;
1955 			else
1956 				wbc->nr_to_write = 0;
1957 		}
1958 		if (nscan < INT_MAX)
1959 			break;
1960 		cond_resched();
1961 	}
1962 	nfs_commit_end(cinfo.mds);
1963 	if (ret || !may_wait)
1964 		return ret;
1965 	return wait_on_commit(cinfo.mds);
1966 }
1967 
1968 int nfs_commit_inode(struct inode *inode, int how)
1969 {
1970 	return __nfs_commit_inode(inode, how, NULL);
1971 }
1972 EXPORT_SYMBOL_GPL(nfs_commit_inode);
1973 
1974 int nfs_write_inode(struct inode *inode, struct writeback_control *wbc)
1975 {
1976 	struct nfs_inode *nfsi = NFS_I(inode);
1977 	int flags = FLUSH_SYNC;
1978 	int ret = 0;
1979 
1980 	if (wbc->sync_mode == WB_SYNC_NONE) {
1981 		/* no commits means nothing needs to be done */
1982 		if (!atomic_long_read(&nfsi->commit_info.ncommit))
1983 			goto check_requests_outstanding;
1984 
1985 		/* Don't commit yet if this is a non-blocking flush and there
1986 		 * are a lot of outstanding writes for this mapping.
1987 		 */
1988 		if (mapping_tagged(inode->i_mapping, PAGECACHE_TAG_WRITEBACK))
1989 			goto out_mark_dirty;
1990 
1991 		/* don't wait for the COMMIT response */
1992 		flags = 0;
1993 	}
1994 
1995 	ret = __nfs_commit_inode(inode, flags, wbc);
1996 	if (!ret) {
1997 		if (flags & FLUSH_SYNC)
1998 			return 0;
1999 	} else if (atomic_long_read(&nfsi->commit_info.ncommit))
2000 		goto out_mark_dirty;
2001 
2002 check_requests_outstanding:
2003 	if (!atomic_read(&nfsi->commit_info.rpcs_out))
2004 		return ret;
2005 out_mark_dirty:
2006 	__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
2007 	return ret;
2008 }
2009 EXPORT_SYMBOL_GPL(nfs_write_inode);
2010 
2011 /*
2012  * Wrapper for filemap_write_and_wait_range()
2013  *
2014  * Needed for pNFS in order to ensure data becomes visible to the
2015  * client.
2016  */
2017 int nfs_filemap_write_and_wait_range(struct address_space *mapping,
2018 		loff_t lstart, loff_t lend)
2019 {
2020 	int ret;
2021 
2022 	ret = filemap_write_and_wait_range(mapping, lstart, lend);
2023 	if (ret == 0)
2024 		ret = pnfs_sync_inode(mapping->host, true);
2025 	return ret;
2026 }
2027 EXPORT_SYMBOL_GPL(nfs_filemap_write_and_wait_range);
2028 
2029 /*
2030  * flush the inode to disk.
2031  */
2032 int nfs_wb_all(struct inode *inode)
2033 {
2034 	int ret;
2035 
2036 	trace_nfs_writeback_inode_enter(inode);
2037 
2038 	ret = filemap_write_and_wait(inode->i_mapping);
2039 	if (ret)
2040 		goto out;
2041 	ret = nfs_commit_inode(inode, FLUSH_SYNC);
2042 	if (ret < 0)
2043 		goto out;
2044 	pnfs_sync_inode(inode, true);
2045 	ret = 0;
2046 
2047 out:
2048 	trace_nfs_writeback_inode_exit(inode, ret);
2049 	return ret;
2050 }
2051 EXPORT_SYMBOL_GPL(nfs_wb_all);
2052 
2053 int nfs_wb_folio_cancel(struct inode *inode, struct folio *folio)
2054 {
2055 	struct nfs_page *req;
2056 	int ret = 0;
2057 
2058 	folio_wait_writeback(folio);
2059 
2060 	/* blocking call to cancel all requests and join to a single (head)
2061 	 * request */
2062 	req = nfs_lock_and_join_requests(folio);
2063 
2064 	if (IS_ERR(req)) {
2065 		ret = PTR_ERR(req);
2066 	} else if (req) {
2067 		/* all requests from this folio have been cancelled by
2068 		 * nfs_lock_and_join_requests, so just remove the head
2069 		 * request from the inode / page_private pointer and
2070 		 * release it */
2071 		nfs_inode_remove_request(req);
2072 		nfs_unlock_and_release_request(req);
2073 	}
2074 
2075 	return ret;
2076 }
2077 
2078 /**
2079  * nfs_wb_folio - Write back all requests on one page
2080  * @inode: pointer to page
2081  * @folio: pointer to folio
2082  *
2083  * Assumes that the folio has been locked by the caller, and will
2084  * not unlock it.
2085  */
2086 int nfs_wb_folio(struct inode *inode, struct folio *folio)
2087 {
2088 	loff_t range_start = folio_file_pos(folio);
2089 	loff_t range_end = range_start + (loff_t)folio_size(folio) - 1;
2090 	struct writeback_control wbc = {
2091 		.sync_mode = WB_SYNC_ALL,
2092 		.nr_to_write = 0,
2093 		.range_start = range_start,
2094 		.range_end = range_end,
2095 	};
2096 	int ret;
2097 
2098 	trace_nfs_writeback_folio(inode, folio);
2099 
2100 	for (;;) {
2101 		folio_wait_writeback(folio);
2102 		if (folio_clear_dirty_for_io(folio)) {
2103 			ret = nfs_writepage_locked(folio, &wbc);
2104 			if (ret < 0)
2105 				goto out_error;
2106 			continue;
2107 		}
2108 		ret = 0;
2109 		if (!folio_test_private(folio))
2110 			break;
2111 		ret = nfs_commit_inode(inode, FLUSH_SYNC);
2112 		if (ret < 0)
2113 			goto out_error;
2114 	}
2115 out_error:
2116 	trace_nfs_writeback_folio_done(inode, folio, ret);
2117 	return ret;
2118 }
2119 
2120 #ifdef CONFIG_MIGRATION
2121 int nfs_migrate_folio(struct address_space *mapping, struct folio *dst,
2122 		struct folio *src, enum migrate_mode mode)
2123 {
2124 	/*
2125 	 * If the private flag is set, the folio is currently associated with
2126 	 * an in-progress read or write request. Don't try to migrate it.
2127 	 *
2128 	 * FIXME: we could do this in principle, but we'll need a way to ensure
2129 	 *        that we can safely release the inode reference while holding
2130 	 *        the folio lock.
2131 	 */
2132 	if (folio_test_private(src))
2133 		return -EBUSY;
2134 
2135 	if (folio_test_private_2(src)) { /* [DEPRECATED] */
2136 		if (mode == MIGRATE_ASYNC)
2137 			return -EBUSY;
2138 		folio_wait_private_2(src);
2139 	}
2140 
2141 	return migrate_folio(mapping, dst, src, mode);
2142 }
2143 #endif
2144 
2145 int __init nfs_init_writepagecache(void)
2146 {
2147 	nfs_wdata_cachep = kmem_cache_create("nfs_write_data",
2148 					     sizeof(struct nfs_pgio_header),
2149 					     0, SLAB_HWCACHE_ALIGN,
2150 					     NULL);
2151 	if (nfs_wdata_cachep == NULL)
2152 		return -ENOMEM;
2153 
2154 	nfs_wdata_mempool = mempool_create_slab_pool(MIN_POOL_WRITE,
2155 						     nfs_wdata_cachep);
2156 	if (nfs_wdata_mempool == NULL)
2157 		goto out_destroy_write_cache;
2158 
2159 	nfs_cdata_cachep = kmem_cache_create("nfs_commit_data",
2160 					     sizeof(struct nfs_commit_data),
2161 					     0, SLAB_HWCACHE_ALIGN,
2162 					     NULL);
2163 	if (nfs_cdata_cachep == NULL)
2164 		goto out_destroy_write_mempool;
2165 
2166 	nfs_commit_mempool = mempool_create_slab_pool(MIN_POOL_COMMIT,
2167 						      nfs_cdata_cachep);
2168 	if (nfs_commit_mempool == NULL)
2169 		goto out_destroy_commit_cache;
2170 
2171 	/*
2172 	 * NFS congestion size, scale with available memory.
2173 	 *
2174 	 *  64MB:    8192k
2175 	 * 128MB:   11585k
2176 	 * 256MB:   16384k
2177 	 * 512MB:   23170k
2178 	 *   1GB:   32768k
2179 	 *   2GB:   46340k
2180 	 *   4GB:   65536k
2181 	 *   8GB:   92681k
2182 	 *  16GB:  131072k
2183 	 *
2184 	 * This allows larger machines to have larger/more transfers.
2185 	 * Limit the default to 256M
2186 	 */
2187 	nfs_congestion_kb = (16*int_sqrt(totalram_pages())) << (PAGE_SHIFT-10);
2188 	if (nfs_congestion_kb > 256*1024)
2189 		nfs_congestion_kb = 256*1024;
2190 
2191 	return 0;
2192 
2193 out_destroy_commit_cache:
2194 	kmem_cache_destroy(nfs_cdata_cachep);
2195 out_destroy_write_mempool:
2196 	mempool_destroy(nfs_wdata_mempool);
2197 out_destroy_write_cache:
2198 	kmem_cache_destroy(nfs_wdata_cachep);
2199 	return -ENOMEM;
2200 }
2201 
2202 void nfs_destroy_writepagecache(void)
2203 {
2204 	mempool_destroy(nfs_commit_mempool);
2205 	kmem_cache_destroy(nfs_cdata_cachep);
2206 	mempool_destroy(nfs_wdata_mempool);
2207 	kmem_cache_destroy(nfs_wdata_cachep);
2208 }
2209 
2210 static const struct nfs_rw_ops nfs_rw_write_ops = {
2211 	.rw_alloc_header	= nfs_writehdr_alloc,
2212 	.rw_free_header		= nfs_writehdr_free,
2213 	.rw_done		= nfs_writeback_done,
2214 	.rw_result		= nfs_writeback_result,
2215 	.rw_initiate		= nfs_initiate_write,
2216 };
2217