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