xref: /linux/mm/page_io.c (revision c7546e2c3cb739a3c1a2f5acaf9bb629d401afe5)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/mm/page_io.c
4  *
5  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
6  *
7  *  Swap reorganised 29.12.95,
8  *  Asynchronous swapping added 30.12.95. Stephen Tweedie
9  *  Removed race in async swapping. 14.4.1996. Bruno Haible
10  *  Add swap of shared pages through the page cache. 20.2.1998. Stephen Tweedie
11  *  Always use brw_page, life becomes simpler. 12 May 1998 Eric Biederman
12  */
13 
14 #include <linux/mm.h>
15 #include <linux/kernel_stat.h>
16 #include <linux/gfp.h>
17 #include <linux/pagemap.h>
18 #include <linux/swap.h>
19 #include <linux/bio.h>
20 #include <linux/swapops.h>
21 #include <linux/writeback.h>
22 #include <linux/blkdev.h>
23 #include <linux/psi.h>
24 #include <linux/uio.h>
25 #include <linux/sched/task.h>
26 #include <linux/delayacct.h>
27 #include <linux/zswap.h>
28 #include "swap.h"
29 
30 static void __end_swap_bio_write(struct bio *bio)
31 {
32 	struct folio *folio = bio_first_folio_all(bio);
33 
34 	if (bio->bi_status) {
35 		/*
36 		 * We failed to write the page out to swap-space.
37 		 * Re-dirty the page in order to avoid it being reclaimed.
38 		 * Also print a dire warning that things will go BAD (tm)
39 		 * very quickly.
40 		 *
41 		 * Also clear PG_reclaim to avoid folio_rotate_reclaimable()
42 		 */
43 		folio_mark_dirty(folio);
44 		pr_alert_ratelimited("Write-error on swap-device (%u:%u:%llu)\n",
45 				     MAJOR(bio_dev(bio)), MINOR(bio_dev(bio)),
46 				     (unsigned long long)bio->bi_iter.bi_sector);
47 		folio_clear_reclaim(folio);
48 	}
49 	folio_end_writeback(folio);
50 }
51 
52 static void end_swap_bio_write(struct bio *bio)
53 {
54 	__end_swap_bio_write(bio);
55 	bio_put(bio);
56 }
57 
58 static void __end_swap_bio_read(struct bio *bio)
59 {
60 	struct folio *folio = bio_first_folio_all(bio);
61 
62 	if (bio->bi_status) {
63 		pr_alert_ratelimited("Read-error on swap-device (%u:%u:%llu)\n",
64 				     MAJOR(bio_dev(bio)), MINOR(bio_dev(bio)),
65 				     (unsigned long long)bio->bi_iter.bi_sector);
66 	} else {
67 		folio_mark_uptodate(folio);
68 	}
69 	folio_unlock(folio);
70 }
71 
72 static void end_swap_bio_read(struct bio *bio)
73 {
74 	__end_swap_bio_read(bio);
75 	bio_put(bio);
76 }
77 
78 int generic_swapfile_activate(struct swap_info_struct *sis,
79 				struct file *swap_file,
80 				sector_t *span)
81 {
82 	struct address_space *mapping = swap_file->f_mapping;
83 	struct inode *inode = mapping->host;
84 	unsigned blocks_per_page;
85 	unsigned long page_no;
86 	unsigned blkbits;
87 	sector_t probe_block;
88 	sector_t last_block;
89 	sector_t lowest_block = -1;
90 	sector_t highest_block = 0;
91 	int nr_extents = 0;
92 	int ret;
93 
94 	blkbits = inode->i_blkbits;
95 	blocks_per_page = PAGE_SIZE >> blkbits;
96 
97 	/*
98 	 * Map all the blocks into the extent tree.  This code doesn't try
99 	 * to be very smart.
100 	 */
101 	probe_block = 0;
102 	page_no = 0;
103 	last_block = i_size_read(inode) >> blkbits;
104 	while ((probe_block + blocks_per_page) <= last_block &&
105 			page_no < sis->max) {
106 		unsigned block_in_page;
107 		sector_t first_block;
108 
109 		cond_resched();
110 
111 		first_block = probe_block;
112 		ret = bmap(inode, &first_block);
113 		if (ret || !first_block)
114 			goto bad_bmap;
115 
116 		/*
117 		 * It must be PAGE_SIZE aligned on-disk
118 		 */
119 		if (first_block & (blocks_per_page - 1)) {
120 			probe_block++;
121 			goto reprobe;
122 		}
123 
124 		for (block_in_page = 1; block_in_page < blocks_per_page;
125 					block_in_page++) {
126 			sector_t block;
127 
128 			block = probe_block + block_in_page;
129 			ret = bmap(inode, &block);
130 			if (ret || !block)
131 				goto bad_bmap;
132 
133 			if (block != first_block + block_in_page) {
134 				/* Discontiguity */
135 				probe_block++;
136 				goto reprobe;
137 			}
138 		}
139 
140 		first_block >>= (PAGE_SHIFT - blkbits);
141 		if (page_no) {	/* exclude the header page */
142 			if (first_block < lowest_block)
143 				lowest_block = first_block;
144 			if (first_block > highest_block)
145 				highest_block = first_block;
146 		}
147 
148 		/*
149 		 * We found a PAGE_SIZE-length, PAGE_SIZE-aligned run of blocks
150 		 */
151 		ret = add_swap_extent(sis, page_no, 1, first_block);
152 		if (ret < 0)
153 			goto out;
154 		nr_extents += ret;
155 		page_no++;
156 		probe_block += blocks_per_page;
157 reprobe:
158 		continue;
159 	}
160 	ret = nr_extents;
161 	*span = 1 + highest_block - lowest_block;
162 	if (page_no == 0)
163 		page_no = 1;	/* force Empty message */
164 	sis->max = page_no;
165 	sis->pages = page_no - 1;
166 	sis->highest_bit = page_no - 1;
167 out:
168 	return ret;
169 bad_bmap:
170 	pr_err("swapon: swapfile has holes\n");
171 	ret = -EINVAL;
172 	goto out;
173 }
174 
175 static bool is_folio_zero_filled(struct folio *folio)
176 {
177 	unsigned int pos, last_pos;
178 	unsigned long *data;
179 	unsigned int i;
180 
181 	last_pos = PAGE_SIZE / sizeof(*data) - 1;
182 	for (i = 0; i < folio_nr_pages(folio); i++) {
183 		data = kmap_local_folio(folio, i * PAGE_SIZE);
184 		/*
185 		 * Check last word first, incase the page is zero-filled at
186 		 * the start and has non-zero data at the end, which is common
187 		 * in real-world workloads.
188 		 */
189 		if (data[last_pos]) {
190 			kunmap_local(data);
191 			return false;
192 		}
193 		for (pos = 0; pos < last_pos; pos++) {
194 			if (data[pos]) {
195 				kunmap_local(data);
196 				return false;
197 			}
198 		}
199 		kunmap_local(data);
200 	}
201 
202 	return true;
203 }
204 
205 static void swap_zeromap_folio_set(struct folio *folio)
206 {
207 	struct swap_info_struct *sis = swp_swap_info(folio->swap);
208 	swp_entry_t entry;
209 	unsigned int i;
210 
211 	for (i = 0; i < folio_nr_pages(folio); i++) {
212 		entry = page_swap_entry(folio_page(folio, i));
213 		set_bit(swp_offset(entry), sis->zeromap);
214 	}
215 }
216 
217 static void swap_zeromap_folio_clear(struct folio *folio)
218 {
219 	struct swap_info_struct *sis = swp_swap_info(folio->swap);
220 	swp_entry_t entry;
221 	unsigned int i;
222 
223 	for (i = 0; i < folio_nr_pages(folio); i++) {
224 		entry = page_swap_entry(folio_page(folio, i));
225 		clear_bit(swp_offset(entry), sis->zeromap);
226 	}
227 }
228 
229 /*
230  * We may have stale swap cache pages in memory: notice
231  * them here and get rid of the unnecessary final write.
232  */
233 int swap_writepage(struct page *page, struct writeback_control *wbc)
234 {
235 	struct folio *folio = page_folio(page);
236 	int ret;
237 
238 	if (folio_free_swap(folio)) {
239 		folio_unlock(folio);
240 		return 0;
241 	}
242 	/*
243 	 * Arch code may have to preserve more data than just the page
244 	 * contents, e.g. memory tags.
245 	 */
246 	ret = arch_prepare_to_swap(folio);
247 	if (ret) {
248 		folio_mark_dirty(folio);
249 		folio_unlock(folio);
250 		return ret;
251 	}
252 
253 	/*
254 	 * Use a bitmap (zeromap) to avoid doing IO for zero-filled pages.
255 	 * The bits in zeromap are protected by the locked swapcache folio
256 	 * and atomic updates are used to protect against read-modify-write
257 	 * corruption due to other zero swap entries seeing concurrent updates.
258 	 */
259 	if (is_folio_zero_filled(folio)) {
260 		swap_zeromap_folio_set(folio);
261 		folio_unlock(folio);
262 		return 0;
263 	} else {
264 		/*
265 		 * Clear bits this folio occupies in the zeromap to prevent
266 		 * zero data being read in from any previous zero writes that
267 		 * occupied the same swap entries.
268 		 */
269 		swap_zeromap_folio_clear(folio);
270 	}
271 	if (zswap_store(folio)) {
272 		folio_unlock(folio);
273 		return 0;
274 	}
275 	if (!mem_cgroup_zswap_writeback_enabled(folio_memcg(folio))) {
276 		folio_mark_dirty(folio);
277 		return AOP_WRITEPAGE_ACTIVATE;
278 	}
279 
280 	__swap_writepage(folio, wbc);
281 	return 0;
282 }
283 
284 static inline void count_swpout_vm_event(struct folio *folio)
285 {
286 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
287 	if (unlikely(folio_test_pmd_mappable(folio))) {
288 		count_memcg_folio_events(folio, THP_SWPOUT, 1);
289 		count_vm_event(THP_SWPOUT);
290 	}
291 	count_mthp_stat(folio_order(folio), MTHP_STAT_SWPOUT);
292 #endif
293 	count_vm_events(PSWPOUT, folio_nr_pages(folio));
294 }
295 
296 #if defined(CONFIG_MEMCG) && defined(CONFIG_BLK_CGROUP)
297 static void bio_associate_blkg_from_page(struct bio *bio, struct folio *folio)
298 {
299 	struct cgroup_subsys_state *css;
300 	struct mem_cgroup *memcg;
301 
302 	memcg = folio_memcg(folio);
303 	if (!memcg)
304 		return;
305 
306 	rcu_read_lock();
307 	css = cgroup_e_css(memcg->css.cgroup, &io_cgrp_subsys);
308 	bio_associate_blkg_from_css(bio, css);
309 	rcu_read_unlock();
310 }
311 #else
312 #define bio_associate_blkg_from_page(bio, folio)		do { } while (0)
313 #endif /* CONFIG_MEMCG && CONFIG_BLK_CGROUP */
314 
315 struct swap_iocb {
316 	struct kiocb		iocb;
317 	struct bio_vec		bvec[SWAP_CLUSTER_MAX];
318 	int			pages;
319 	int			len;
320 };
321 static mempool_t *sio_pool;
322 
323 int sio_pool_init(void)
324 {
325 	if (!sio_pool) {
326 		mempool_t *pool = mempool_create_kmalloc_pool(
327 			SWAP_CLUSTER_MAX, sizeof(struct swap_iocb));
328 		if (cmpxchg(&sio_pool, NULL, pool))
329 			mempool_destroy(pool);
330 	}
331 	if (!sio_pool)
332 		return -ENOMEM;
333 	return 0;
334 }
335 
336 static void sio_write_complete(struct kiocb *iocb, long ret)
337 {
338 	struct swap_iocb *sio = container_of(iocb, struct swap_iocb, iocb);
339 	struct page *page = sio->bvec[0].bv_page;
340 	int p;
341 
342 	if (ret != sio->len) {
343 		/*
344 		 * In the case of swap-over-nfs, this can be a
345 		 * temporary failure if the system has limited
346 		 * memory for allocating transmit buffers.
347 		 * Mark the page dirty and avoid
348 		 * folio_rotate_reclaimable but rate-limit the
349 		 * messages.
350 		 */
351 		pr_err_ratelimited("Write error %ld on dio swapfile (%llu)\n",
352 				   ret, swap_dev_pos(page_swap_entry(page)));
353 		for (p = 0; p < sio->pages; p++) {
354 			page = sio->bvec[p].bv_page;
355 			set_page_dirty(page);
356 			ClearPageReclaim(page);
357 		}
358 	}
359 
360 	for (p = 0; p < sio->pages; p++)
361 		end_page_writeback(sio->bvec[p].bv_page);
362 
363 	mempool_free(sio, sio_pool);
364 }
365 
366 static void swap_writepage_fs(struct folio *folio, struct writeback_control *wbc)
367 {
368 	struct swap_iocb *sio = NULL;
369 	struct swap_info_struct *sis = swp_swap_info(folio->swap);
370 	struct file *swap_file = sis->swap_file;
371 	loff_t pos = swap_dev_pos(folio->swap);
372 
373 	count_swpout_vm_event(folio);
374 	folio_start_writeback(folio);
375 	folio_unlock(folio);
376 	if (wbc->swap_plug)
377 		sio = *wbc->swap_plug;
378 	if (sio) {
379 		if (sio->iocb.ki_filp != swap_file ||
380 		    sio->iocb.ki_pos + sio->len != pos) {
381 			swap_write_unplug(sio);
382 			sio = NULL;
383 		}
384 	}
385 	if (!sio) {
386 		sio = mempool_alloc(sio_pool, GFP_NOIO);
387 		init_sync_kiocb(&sio->iocb, swap_file);
388 		sio->iocb.ki_complete = sio_write_complete;
389 		sio->iocb.ki_pos = pos;
390 		sio->pages = 0;
391 		sio->len = 0;
392 	}
393 	bvec_set_folio(&sio->bvec[sio->pages], folio, folio_size(folio), 0);
394 	sio->len += folio_size(folio);
395 	sio->pages += 1;
396 	if (sio->pages == ARRAY_SIZE(sio->bvec) || !wbc->swap_plug) {
397 		swap_write_unplug(sio);
398 		sio = NULL;
399 	}
400 	if (wbc->swap_plug)
401 		*wbc->swap_plug = sio;
402 }
403 
404 static void swap_writepage_bdev_sync(struct folio *folio,
405 		struct writeback_control *wbc, struct swap_info_struct *sis)
406 {
407 	struct bio_vec bv;
408 	struct bio bio;
409 
410 	bio_init(&bio, sis->bdev, &bv, 1,
411 		 REQ_OP_WRITE | REQ_SWAP | wbc_to_write_flags(wbc));
412 	bio.bi_iter.bi_sector = swap_folio_sector(folio);
413 	bio_add_folio_nofail(&bio, folio, folio_size(folio), 0);
414 
415 	bio_associate_blkg_from_page(&bio, folio);
416 	count_swpout_vm_event(folio);
417 
418 	folio_start_writeback(folio);
419 	folio_unlock(folio);
420 
421 	submit_bio_wait(&bio);
422 	__end_swap_bio_write(&bio);
423 }
424 
425 static void swap_writepage_bdev_async(struct folio *folio,
426 		struct writeback_control *wbc, struct swap_info_struct *sis)
427 {
428 	struct bio *bio;
429 
430 	bio = bio_alloc(sis->bdev, 1,
431 			REQ_OP_WRITE | REQ_SWAP | wbc_to_write_flags(wbc),
432 			GFP_NOIO);
433 	bio->bi_iter.bi_sector = swap_folio_sector(folio);
434 	bio->bi_end_io = end_swap_bio_write;
435 	bio_add_folio_nofail(bio, folio, folio_size(folio), 0);
436 
437 	bio_associate_blkg_from_page(bio, folio);
438 	count_swpout_vm_event(folio);
439 	folio_start_writeback(folio);
440 	folio_unlock(folio);
441 	submit_bio(bio);
442 }
443 
444 void __swap_writepage(struct folio *folio, struct writeback_control *wbc)
445 {
446 	struct swap_info_struct *sis = swp_swap_info(folio->swap);
447 
448 	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio), folio);
449 	/*
450 	 * ->flags can be updated non-atomicially (scan_swap_map_slots),
451 	 * but that will never affect SWP_FS_OPS, so the data_race
452 	 * is safe.
453 	 */
454 	if (data_race(sis->flags & SWP_FS_OPS))
455 		swap_writepage_fs(folio, wbc);
456 	/*
457 	 * ->flags can be updated non-atomicially (scan_swap_map_slots),
458 	 * but that will never affect SWP_SYNCHRONOUS_IO, so the data_race
459 	 * is safe.
460 	 */
461 	else if (data_race(sis->flags & SWP_SYNCHRONOUS_IO))
462 		swap_writepage_bdev_sync(folio, wbc, sis);
463 	else
464 		swap_writepage_bdev_async(folio, wbc, sis);
465 }
466 
467 void swap_write_unplug(struct swap_iocb *sio)
468 {
469 	struct iov_iter from;
470 	struct address_space *mapping = sio->iocb.ki_filp->f_mapping;
471 	int ret;
472 
473 	iov_iter_bvec(&from, ITER_SOURCE, sio->bvec, sio->pages, sio->len);
474 	ret = mapping->a_ops->swap_rw(&sio->iocb, &from);
475 	if (ret != -EIOCBQUEUED)
476 		sio_write_complete(&sio->iocb, ret);
477 }
478 
479 static void sio_read_complete(struct kiocb *iocb, long ret)
480 {
481 	struct swap_iocb *sio = container_of(iocb, struct swap_iocb, iocb);
482 	int p;
483 
484 	if (ret == sio->len) {
485 		for (p = 0; p < sio->pages; p++) {
486 			struct folio *folio = page_folio(sio->bvec[p].bv_page);
487 
488 			folio_mark_uptodate(folio);
489 			folio_unlock(folio);
490 		}
491 		count_vm_events(PSWPIN, sio->pages);
492 	} else {
493 		for (p = 0; p < sio->pages; p++) {
494 			struct folio *folio = page_folio(sio->bvec[p].bv_page);
495 
496 			folio_unlock(folio);
497 		}
498 		pr_alert_ratelimited("Read-error on swap-device\n");
499 	}
500 	mempool_free(sio, sio_pool);
501 }
502 
503 static bool swap_read_folio_zeromap(struct folio *folio)
504 {
505 	int nr_pages = folio_nr_pages(folio);
506 	bool is_zeromap;
507 
508 	/*
509 	 * Swapping in a large folio that is partially in the zeromap is not
510 	 * currently handled. Return true without marking the folio uptodate so
511 	 * that an IO error is emitted (e.g. do_swap_page() will sigbus).
512 	 */
513 	if (WARN_ON_ONCE(swap_zeromap_batch(folio->swap, nr_pages,
514 			&is_zeromap) != nr_pages))
515 		return true;
516 
517 	if (!is_zeromap)
518 		return false;
519 
520 	folio_zero_range(folio, 0, folio_size(folio));
521 	folio_mark_uptodate(folio);
522 	return true;
523 }
524 
525 static void swap_read_folio_fs(struct folio *folio, struct swap_iocb **plug)
526 {
527 	struct swap_info_struct *sis = swp_swap_info(folio->swap);
528 	struct swap_iocb *sio = NULL;
529 	loff_t pos = swap_dev_pos(folio->swap);
530 
531 	if (plug)
532 		sio = *plug;
533 	if (sio) {
534 		if (sio->iocb.ki_filp != sis->swap_file ||
535 		    sio->iocb.ki_pos + sio->len != pos) {
536 			swap_read_unplug(sio);
537 			sio = NULL;
538 		}
539 	}
540 	if (!sio) {
541 		sio = mempool_alloc(sio_pool, GFP_KERNEL);
542 		init_sync_kiocb(&sio->iocb, sis->swap_file);
543 		sio->iocb.ki_pos = pos;
544 		sio->iocb.ki_complete = sio_read_complete;
545 		sio->pages = 0;
546 		sio->len = 0;
547 	}
548 	bvec_set_folio(&sio->bvec[sio->pages], folio, folio_size(folio), 0);
549 	sio->len += folio_size(folio);
550 	sio->pages += 1;
551 	if (sio->pages == ARRAY_SIZE(sio->bvec) || !plug) {
552 		swap_read_unplug(sio);
553 		sio = NULL;
554 	}
555 	if (plug)
556 		*plug = sio;
557 }
558 
559 static void swap_read_folio_bdev_sync(struct folio *folio,
560 		struct swap_info_struct *sis)
561 {
562 	struct bio_vec bv;
563 	struct bio bio;
564 
565 	bio_init(&bio, sis->bdev, &bv, 1, REQ_OP_READ);
566 	bio.bi_iter.bi_sector = swap_folio_sector(folio);
567 	bio_add_folio_nofail(&bio, folio, folio_size(folio), 0);
568 	/*
569 	 * Keep this task valid during swap readpage because the oom killer may
570 	 * attempt to access it in the page fault retry time check.
571 	 */
572 	get_task_struct(current);
573 	count_vm_event(PSWPIN);
574 	submit_bio_wait(&bio);
575 	__end_swap_bio_read(&bio);
576 	put_task_struct(current);
577 }
578 
579 static void swap_read_folio_bdev_async(struct folio *folio,
580 		struct swap_info_struct *sis)
581 {
582 	struct bio *bio;
583 
584 	bio = bio_alloc(sis->bdev, 1, REQ_OP_READ, GFP_KERNEL);
585 	bio->bi_iter.bi_sector = swap_folio_sector(folio);
586 	bio->bi_end_io = end_swap_bio_read;
587 	bio_add_folio_nofail(bio, folio, folio_size(folio), 0);
588 	count_vm_event(PSWPIN);
589 	submit_bio(bio);
590 }
591 
592 void swap_read_folio(struct folio *folio, struct swap_iocb **plug)
593 {
594 	struct swap_info_struct *sis = swp_swap_info(folio->swap);
595 	bool synchronous = sis->flags & SWP_SYNCHRONOUS_IO;
596 	bool workingset = folio_test_workingset(folio);
597 	unsigned long pflags;
598 	bool in_thrashing;
599 
600 	VM_BUG_ON_FOLIO(!folio_test_swapcache(folio) && !synchronous, folio);
601 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
602 	VM_BUG_ON_FOLIO(folio_test_uptodate(folio), folio);
603 
604 	/*
605 	 * Count submission time as memory stall and delay. When the device
606 	 * is congested, or the submitting cgroup IO-throttled, submission
607 	 * can be a significant part of overall IO time.
608 	 */
609 	if (workingset) {
610 		delayacct_thrashing_start(&in_thrashing);
611 		psi_memstall_enter(&pflags);
612 	}
613 	delayacct_swapin_start();
614 
615 	if (swap_read_folio_zeromap(folio)) {
616 		folio_unlock(folio);
617 		goto finish;
618 	} else if (zswap_load(folio)) {
619 		folio_unlock(folio);
620 		goto finish;
621 	}
622 
623 	/* We have to read from slower devices. Increase zswap protection. */
624 	zswap_folio_swapin(folio);
625 
626 	if (data_race(sis->flags & SWP_FS_OPS)) {
627 		swap_read_folio_fs(folio, plug);
628 	} else if (synchronous) {
629 		swap_read_folio_bdev_sync(folio, sis);
630 	} else {
631 		swap_read_folio_bdev_async(folio, sis);
632 	}
633 
634 finish:
635 	if (workingset) {
636 		delayacct_thrashing_end(&in_thrashing);
637 		psi_memstall_leave(&pflags);
638 	}
639 	delayacct_swapin_end();
640 }
641 
642 void __swap_read_unplug(struct swap_iocb *sio)
643 {
644 	struct iov_iter from;
645 	struct address_space *mapping = sio->iocb.ki_filp->f_mapping;
646 	int ret;
647 
648 	iov_iter_bvec(&from, ITER_DEST, sio->bvec, sio->pages, sio->len);
649 	ret = mapping->a_ops->swap_rw(&sio->iocb, &from);
650 	if (ret != -EIOCBQUEUED)
651 		sio_read_complete(&sio->iocb, ret);
652 }
653