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