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