xref: /linux/fs/dax.c (revision ab5193e919bbc2577bf404983b2c0ee3c6d3ef83)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * fs/dax.c - Direct Access filesystem code
4  * Copyright (c) 2013-2014 Intel Corporation
5  * Author: Matthew Wilcox <matthew.r.wilcox@intel.com>
6  * Author: Ross Zwisler <ross.zwisler@linux.intel.com>
7  */
8 
9 #include <linux/atomic.h>
10 #include <linux/blkdev.h>
11 #include <linux/buffer_head.h>
12 #include <linux/dax.h>
13 #include <linux/fs.h>
14 #include <linux/highmem.h>
15 #include <linux/memcontrol.h>
16 #include <linux/mm.h>
17 #include <linux/mutex.h>
18 #include <linux/sched.h>
19 #include <linux/sched/signal.h>
20 #include <linux/uio.h>
21 #include <linux/vmstat.h>
22 #include <linux/sizes.h>
23 #include <linux/mmu_notifier.h>
24 #include <linux/iomap.h>
25 #include <linux/rmap.h>
26 #include <linux/pgalloc.h>
27 
28 #define CREATE_TRACE_POINTS
29 #include <trace/events/fs_dax.h>
30 
31 /* We choose 4096 entries - same as per-zone page wait tables */
32 #define DAX_WAIT_TABLE_BITS 12
33 #define DAX_WAIT_TABLE_ENTRIES (1 << DAX_WAIT_TABLE_BITS)
34 
35 /* The 'colour' (ie low bits) within a PMD of a page offset.  */
36 #define PG_PMD_COLOUR	((PMD_SIZE >> PAGE_SHIFT) - 1)
37 #define PG_PMD_NR	(PMD_SIZE >> PAGE_SHIFT)
38 
39 static wait_queue_head_t wait_table[DAX_WAIT_TABLE_ENTRIES];
40 
41 static int __init init_dax_wait_table(void)
42 {
43 	int i;
44 
45 	for (i = 0; i < DAX_WAIT_TABLE_ENTRIES; i++)
46 		init_waitqueue_head(wait_table + i);
47 	return 0;
48 }
49 fs_initcall(init_dax_wait_table);
50 
51 /*
52  * DAX pagecache entries use XArray value entries so they can't be mistaken
53  * for pages.  We use one bit for locking, one bit for the entry size (PMD)
54  * and two more to tell us if the entry is a zero page or an empty entry that
55  * is just used for locking.  In total four special bits.
56  *
57  * If the PMD bit isn't set the entry has size PAGE_SIZE, and if the ZERO_PAGE
58  * and EMPTY bits aren't set the entry is a normal DAX entry with a filesystem
59  * block allocation.
60  */
61 #define DAX_SHIFT	(4)
62 #define DAX_LOCKED	(1UL << 0)
63 #define DAX_PMD		(1UL << 1)
64 #define DAX_ZERO_PAGE	(1UL << 2)
65 #define DAX_EMPTY	(1UL << 3)
66 
67 static unsigned long dax_to_pfn(void *entry)
68 {
69 	return xa_to_value(entry) >> DAX_SHIFT;
70 }
71 
72 static struct folio *dax_to_folio(void *entry)
73 {
74 	return page_folio(pfn_to_page(dax_to_pfn(entry)));
75 }
76 
77 static void *dax_make_entry(unsigned long pfn, unsigned long flags)
78 {
79 	return xa_mk_value(flags | (pfn << DAX_SHIFT));
80 }
81 
82 static bool dax_is_locked(void *entry)
83 {
84 	return xa_to_value(entry) & DAX_LOCKED;
85 }
86 
87 static unsigned int dax_entry_order(void *entry)
88 {
89 	if (xa_to_value(entry) & DAX_PMD)
90 		return PMD_ORDER;
91 	return 0;
92 }
93 
94 static unsigned long dax_is_pmd_entry(void *entry)
95 {
96 	return xa_to_value(entry) & DAX_PMD;
97 }
98 
99 static bool dax_is_pte_entry(void *entry)
100 {
101 	return !(xa_to_value(entry) & DAX_PMD);
102 }
103 
104 static int dax_is_zero_entry(void *entry)
105 {
106 	return xa_to_value(entry) & DAX_ZERO_PAGE;
107 }
108 
109 static int dax_is_empty_entry(void *entry)
110 {
111 	return xa_to_value(entry) & DAX_EMPTY;
112 }
113 
114 /*
115  * true if the entry that was found is of a smaller order than the entry
116  * we were looking for
117  */
118 static bool dax_is_conflict(void *entry)
119 {
120 	return entry == XA_RETRY_ENTRY;
121 }
122 
123 /*
124  * DAX page cache entry locking
125  */
126 struct exceptional_entry_key {
127 	struct xarray *xa;
128 	pgoff_t entry_start;
129 };
130 
131 struct wait_exceptional_entry_queue {
132 	wait_queue_entry_t wait;
133 	struct exceptional_entry_key key;
134 };
135 
136 /**
137  * enum dax_wake_mode: waitqueue wakeup behaviour
138  * @WAKE_ALL: wake all waiters in the waitqueue
139  * @WAKE_NEXT: wake only the first waiter in the waitqueue
140  */
141 enum dax_wake_mode {
142 	WAKE_ALL,
143 	WAKE_NEXT,
144 };
145 
146 static wait_queue_head_t *dax_entry_waitqueue(struct xa_state *xas,
147 		void *entry, struct exceptional_entry_key *key)
148 {
149 	unsigned long hash;
150 	unsigned long index = xas->xa_index;
151 
152 	/*
153 	 * If 'entry' is a PMD, align the 'index' that we use for the wait
154 	 * queue to the start of that PMD.  This ensures that all offsets in
155 	 * the range covered by the PMD map to the same bit lock.
156 	 */
157 	if (dax_is_pmd_entry(entry))
158 		index &= ~PG_PMD_COLOUR;
159 	key->xa = xas->xa;
160 	key->entry_start = index;
161 
162 	hash = hash_long((unsigned long)xas->xa ^ index, DAX_WAIT_TABLE_BITS);
163 	return wait_table + hash;
164 }
165 
166 static int wake_exceptional_entry_func(wait_queue_entry_t *wait,
167 		unsigned int mode, int sync, void *keyp)
168 {
169 	struct exceptional_entry_key *key = keyp;
170 	struct wait_exceptional_entry_queue *ewait =
171 		container_of(wait, struct wait_exceptional_entry_queue, wait);
172 
173 	if (key->xa != ewait->key.xa ||
174 	    key->entry_start != ewait->key.entry_start)
175 		return 0;
176 	return autoremove_wake_function(wait, mode, sync, NULL);
177 }
178 
179 /*
180  * @entry may no longer be the entry at the index in the mapping.
181  * The important information it's conveying is whether the entry at
182  * this index used to be a PMD entry.
183  */
184 static void dax_wake_entry(struct xa_state *xas, void *entry,
185 			   enum dax_wake_mode mode)
186 {
187 	struct exceptional_entry_key key;
188 	wait_queue_head_t *wq;
189 
190 	wq = dax_entry_waitqueue(xas, entry, &key);
191 
192 	/*
193 	 * Checking for locked entry and prepare_to_wait_exclusive() happens
194 	 * under the i_pages lock, ditto for entry handling in our callers.
195 	 * So at this point all tasks that could have seen our entry locked
196 	 * must be in the waitqueue and the following check will see them.
197 	 */
198 	if (waitqueue_active(wq))
199 		__wake_up(wq, TASK_NORMAL, mode == WAKE_ALL ? 0 : 1, &key);
200 }
201 
202 /*
203  * Look up entry in page cache, wait for it to become unlocked if it
204  * is a DAX entry and return it.  The caller must subsequently call
205  * put_unlocked_entry() if it did not lock the entry or dax_unlock_entry()
206  * if it did.  The entry returned may have a larger order than @order.
207  * If @order is larger than the order of the entry found in i_pages, this
208  * function returns a dax_is_conflict entry.
209  *
210  * Must be called with the i_pages lock held.
211  */
212 static void *get_next_unlocked_entry(struct xa_state *xas, unsigned int order)
213 {
214 	void *entry;
215 	struct wait_exceptional_entry_queue ewait;
216 	wait_queue_head_t *wq;
217 
218 	init_wait(&ewait.wait);
219 	ewait.wait.func = wake_exceptional_entry_func;
220 
221 	for (;;) {
222 		entry = xas_find_conflict(xas);
223 		if (!entry || WARN_ON_ONCE(!xa_is_value(entry)))
224 			return entry;
225 		if (dax_entry_order(entry) < order)
226 			return XA_RETRY_ENTRY;
227 		if (!dax_is_locked(entry))
228 			return entry;
229 
230 		wq = dax_entry_waitqueue(xas, entry, &ewait.key);
231 		prepare_to_wait_exclusive(wq, &ewait.wait,
232 					  TASK_UNINTERRUPTIBLE);
233 		xas_unlock_irq(xas);
234 		xas_reset(xas);
235 		schedule();
236 		finish_wait(wq, &ewait.wait);
237 		xas_lock_irq(xas);
238 	}
239 }
240 
241 /*
242  * Wait for the given entry to become unlocked. Caller must hold the i_pages
243  * lock and call either put_unlocked_entry() if it did not lock the entry or
244  * dax_unlock_entry() if it did. Returns an unlocked entry if still present.
245  */
246 static void *wait_entry_unlocked_exclusive(struct xa_state *xas, void *entry)
247 {
248 	struct wait_exceptional_entry_queue ewait;
249 	wait_queue_head_t *wq;
250 
251 	init_wait(&ewait.wait);
252 	ewait.wait.func = wake_exceptional_entry_func;
253 
254 	while (unlikely(dax_is_locked(entry))) {
255 		wq = dax_entry_waitqueue(xas, entry, &ewait.key);
256 		prepare_to_wait_exclusive(wq, &ewait.wait,
257 					TASK_UNINTERRUPTIBLE);
258 		xas_reset(xas);
259 		xas_unlock_irq(xas);
260 		schedule();
261 		finish_wait(wq, &ewait.wait);
262 		xas_lock_irq(xas);
263 		entry = xas_load(xas);
264 	}
265 
266 	if (xa_is_internal(entry))
267 		return NULL;
268 
269 	return entry;
270 }
271 
272 /*
273  * The only thing keeping the address space around is the i_pages lock
274  * (it's cycled in clear_inode() after removing the entries from i_pages)
275  * After we call xas_unlock_irq(), we cannot touch xas->xa.
276  */
277 static void wait_entry_unlocked(struct xa_state *xas, void *entry)
278 {
279 	struct wait_exceptional_entry_queue ewait;
280 	wait_queue_head_t *wq;
281 
282 	init_wait(&ewait.wait);
283 	ewait.wait.func = wake_exceptional_entry_func;
284 
285 	wq = dax_entry_waitqueue(xas, entry, &ewait.key);
286 	/*
287 	 * Unlike get_next_unlocked_entry() there is no guarantee that this
288 	 * path ever successfully retrieves an unlocked entry before an
289 	 * inode dies. Perform a non-exclusive wait in case this path
290 	 * never successfully performs its own wake up.
291 	 */
292 	prepare_to_wait(wq, &ewait.wait, TASK_UNINTERRUPTIBLE);
293 	xas_unlock_irq(xas);
294 	schedule();
295 	finish_wait(wq, &ewait.wait);
296 }
297 
298 static void put_unlocked_entry(struct xa_state *xas, void *entry,
299 			       enum dax_wake_mode mode)
300 {
301 	if (entry && !dax_is_conflict(entry))
302 		dax_wake_entry(xas, entry, mode);
303 }
304 
305 /*
306  * We used the xa_state to get the entry, but then we locked the entry and
307  * dropped the xa_lock, so we know the xa_state is stale and must be reset
308  * before use.
309  */
310 static void dax_unlock_entry(struct xa_state *xas, void *entry)
311 {
312 	void *old;
313 
314 	BUG_ON(dax_is_locked(entry));
315 	xas_reset(xas);
316 	xas_lock_irq(xas);
317 	old = xas_store(xas, entry);
318 	xas_unlock_irq(xas);
319 	BUG_ON(!dax_is_locked(old));
320 	dax_wake_entry(xas, entry, WAKE_NEXT);
321 }
322 
323 /*
324  * Return: The entry stored at this location before it was locked.
325  */
326 static void *dax_lock_entry(struct xa_state *xas, void *entry)
327 {
328 	unsigned long v = xa_to_value(entry);
329 	return xas_store(xas, xa_mk_value(v | DAX_LOCKED));
330 }
331 
332 static unsigned long dax_entry_size(void *entry)
333 {
334 	if (dax_is_zero_entry(entry))
335 		return 0;
336 	else if (dax_is_empty_entry(entry))
337 		return 0;
338 	else if (dax_is_pmd_entry(entry))
339 		return PMD_SIZE;
340 	else
341 		return PAGE_SIZE;
342 }
343 
344 /*
345  * A DAX folio is considered shared if it has no mapping set and ->share (which
346  * shares the ->index field) is non-zero. Note this may return false even if the
347  * page is shared between multiple files but has not yet actually been mapped
348  * into multiple address spaces.
349  */
350 static inline bool dax_folio_is_shared(struct folio *folio)
351 {
352 	return !folio->mapping && folio->share;
353 }
354 
355 /*
356  * When it is called by dax_insert_entry(), the shared flag will indicate
357  * whether this entry is shared by multiple files. If the page has not
358  * previously been associated with any mappings the ->mapping and ->index
359  * fields will be set. If it has already been associated with a mapping
360  * the mapping will be cleared and the share count set. It's then up to
361  * reverse map users like memory_failure() to call back into the filesystem to
362  * recover ->mapping and ->index information. For example by implementing
363  * dax_holder_operations.
364  */
365 static void dax_folio_make_shared(struct folio *folio)
366 {
367 	/*
368 	 * folio is not currently shared so mark it as shared by clearing
369 	 * folio->mapping.
370 	 */
371 	folio->mapping = NULL;
372 
373 	/*
374 	 * folio has previously been mapped into one address space so set the
375 	 * share count.
376 	 */
377 	folio->share = 1;
378 }
379 
380 static inline unsigned long dax_folio_put(struct folio *folio)
381 {
382 	unsigned long ref;
383 	int order, i;
384 
385 	if (!dax_folio_is_shared(folio))
386 		ref = 0;
387 	else
388 		ref = --folio->share;
389 
390 	if (ref)
391 		return ref;
392 
393 	folio->mapping = NULL;
394 	order = folio_order(folio);
395 	if (!order)
396 		return 0;
397 	folio_reset_order(folio);
398 
399 	for (i = 0; i < (1UL << order); i++) {
400 		struct dev_pagemap *pgmap = page_pgmap(&folio->page);
401 		struct page *page = folio_page(folio, i);
402 		struct folio *new_folio = (struct folio *)page;
403 
404 		ClearPageHead(page);
405 		clear_compound_head(page);
406 
407 		new_folio->mapping = NULL;
408 		/*
409 		 * Reset pgmap which was over-written by
410 		 * prep_compound_page().
411 		 */
412 		new_folio->pgmap = pgmap;
413 		new_folio->share = 0;
414 		WARN_ON_ONCE(folio_ref_count(new_folio));
415 	}
416 
417 	return ref;
418 }
419 
420 static void dax_folio_init(void *entry)
421 {
422 	struct folio *folio = dax_to_folio(entry);
423 	int order = dax_entry_order(entry);
424 
425 	/*
426 	 * Folio should have been split back to order-0 pages in
427 	 * dax_folio_put() when they were removed from their
428 	 * final mapping.
429 	 */
430 	WARN_ON_ONCE(folio_order(folio));
431 
432 	if (order > 0) {
433 		prep_compound_page(&folio->page, order);
434 		if (order > 1)
435 			INIT_LIST_HEAD(&folio->_deferred_list);
436 		WARN_ON_ONCE(folio_ref_count(folio));
437 	}
438 }
439 
440 static void dax_associate_entry(void *entry, struct address_space *mapping,
441 				struct vm_area_struct *vma,
442 				unsigned long address, bool shared)
443 {
444 	unsigned long size = dax_entry_size(entry), index;
445 	struct folio *folio = dax_to_folio(entry);
446 
447 	if (dax_is_zero_entry(entry) || dax_is_empty_entry(entry))
448 		return;
449 
450 	index = linear_page_index(vma, address & ~(size - 1));
451 	if (shared && (folio->mapping || dax_folio_is_shared(folio))) {
452 		if (folio->mapping)
453 			dax_folio_make_shared(folio);
454 
455 		WARN_ON_ONCE(!folio->share);
456 		WARN_ON_ONCE(dax_entry_order(entry) != folio_order(folio));
457 		folio->share++;
458 	} else {
459 		WARN_ON_ONCE(folio->mapping);
460 		dax_folio_init(entry);
461 		folio = dax_to_folio(entry);
462 		folio->mapping = mapping;
463 		folio->index = index;
464 	}
465 }
466 
467 static void dax_disassociate_entry(void *entry, struct address_space *mapping,
468 				bool trunc)
469 {
470 	struct folio *folio = dax_to_folio(entry);
471 
472 	if (dax_is_zero_entry(entry) || dax_is_empty_entry(entry))
473 		return;
474 
475 	dax_folio_put(folio);
476 }
477 
478 static struct page *dax_busy_page(void *entry)
479 {
480 	struct folio *folio = dax_to_folio(entry);
481 
482 	if (dax_is_zero_entry(entry) || dax_is_empty_entry(entry))
483 		return NULL;
484 
485 	if (folio_ref_count(folio) - folio_mapcount(folio))
486 		return &folio->page;
487 	else
488 		return NULL;
489 }
490 
491 /**
492  * dax_lock_folio - Lock the DAX entry corresponding to a folio
493  * @folio: The folio whose entry we want to lock
494  *
495  * Context: Process context.
496  * Return: A cookie to pass to dax_unlock_folio() or 0 if the entry could
497  * not be locked.
498  */
499 dax_entry_t dax_lock_folio(struct folio *folio)
500 {
501 	XA_STATE(xas, NULL, 0);
502 	void *entry;
503 
504 	/* Ensure folio->mapping isn't freed while we look at it */
505 	rcu_read_lock();
506 	for (;;) {
507 		struct address_space *mapping = READ_ONCE(folio->mapping);
508 
509 		entry = NULL;
510 		if (!mapping || !dax_mapping(mapping))
511 			break;
512 
513 		/*
514 		 * In the device-dax case there's no need to lock, a
515 		 * struct dev_pagemap pin is sufficient to keep the
516 		 * inode alive, and we assume we have dev_pagemap pin
517 		 * otherwise we would not have a valid pfn_to_page()
518 		 * translation.
519 		 */
520 		entry = (void *)~0UL;
521 		if (S_ISCHR(mapping->host->i_mode))
522 			break;
523 
524 		xas.xa = &mapping->i_pages;
525 		xas_lock_irq(&xas);
526 		if (mapping != folio->mapping) {
527 			xas_unlock_irq(&xas);
528 			continue;
529 		}
530 		xas_set(&xas, folio->index);
531 		entry = xas_load(&xas);
532 		if (dax_is_locked(entry)) {
533 			rcu_read_unlock();
534 			wait_entry_unlocked(&xas, entry);
535 			rcu_read_lock();
536 			continue;
537 		}
538 		dax_lock_entry(&xas, entry);
539 		xas_unlock_irq(&xas);
540 		break;
541 	}
542 	rcu_read_unlock();
543 	return (dax_entry_t)entry;
544 }
545 
546 void dax_unlock_folio(struct folio *folio, dax_entry_t cookie)
547 {
548 	struct address_space *mapping = folio->mapping;
549 	XA_STATE(xas, &mapping->i_pages, folio->index);
550 
551 	if (S_ISCHR(mapping->host->i_mode))
552 		return;
553 
554 	dax_unlock_entry(&xas, (void *)cookie);
555 }
556 
557 /*
558  * dax_lock_mapping_entry - Lock the DAX entry corresponding to a mapping
559  * @mapping: the file's mapping whose entry we want to lock
560  * @index: the offset within this file
561  * @page: output the dax page corresponding to this dax entry
562  *
563  * Return: A cookie to pass to dax_unlock_mapping_entry() or 0 if the entry
564  * could not be locked.
565  */
566 dax_entry_t dax_lock_mapping_entry(struct address_space *mapping, pgoff_t index,
567 		struct page **page)
568 {
569 	XA_STATE(xas, NULL, 0);
570 	void *entry;
571 
572 	rcu_read_lock();
573 	for (;;) {
574 		entry = NULL;
575 		if (!dax_mapping(mapping))
576 			break;
577 
578 		xas.xa = &mapping->i_pages;
579 		xas_lock_irq(&xas);
580 		xas_set(&xas, index);
581 		entry = xas_load(&xas);
582 		if (dax_is_locked(entry)) {
583 			rcu_read_unlock();
584 			wait_entry_unlocked(&xas, entry);
585 			rcu_read_lock();
586 			continue;
587 		}
588 		if (!entry ||
589 		    dax_is_zero_entry(entry) || dax_is_empty_entry(entry)) {
590 			/*
591 			 * Because we are looking for entry from file's mapping
592 			 * and index, so the entry may not be inserted for now,
593 			 * or even a zero/empty entry.  We don't think this is
594 			 * an error case.  So, return a special value and do
595 			 * not output @page.
596 			 */
597 			entry = (void *)~0UL;
598 		} else {
599 			*page = pfn_to_page(dax_to_pfn(entry));
600 			dax_lock_entry(&xas, entry);
601 		}
602 		xas_unlock_irq(&xas);
603 		break;
604 	}
605 	rcu_read_unlock();
606 	return (dax_entry_t)entry;
607 }
608 
609 void dax_unlock_mapping_entry(struct address_space *mapping, pgoff_t index,
610 		dax_entry_t cookie)
611 {
612 	XA_STATE(xas, &mapping->i_pages, index);
613 
614 	if (cookie == ~0UL)
615 		return;
616 
617 	dax_unlock_entry(&xas, (void *)cookie);
618 }
619 
620 /*
621  * Find page cache entry at given index. If it is a DAX entry, return it
622  * with the entry locked. If the page cache doesn't contain an entry at
623  * that index, add a locked empty entry.
624  *
625  * When requesting an entry with size DAX_PMD, grab_mapping_entry() will
626  * either return that locked entry or will return VM_FAULT_FALLBACK.
627  * This will happen if there are any PTE entries within the PMD range
628  * that we are requesting.
629  *
630  * We always favor PTE entries over PMD entries. There isn't a flow where we
631  * evict PTE entries in order to 'upgrade' them to a PMD entry.  A PMD
632  * insertion will fail if it finds any PTE entries already in the tree, and a
633  * PTE insertion will cause an existing PMD entry to be unmapped and
634  * downgraded to PTE entries.  This happens for both PMD zero pages as
635  * well as PMD empty entries.
636  *
637  * The exception to this downgrade path is for PMD entries that have
638  * real storage backing them.  We will leave these real PMD entries in
639  * the tree, and PTE writes will simply dirty the entire PMD entry.
640  *
641  * Note: Unlike filemap_fault() we don't honor FAULT_FLAG_RETRY flags. For
642  * persistent memory the benefit is doubtful. We can add that later if we can
643  * show it helps.
644  *
645  * On error, this function does not return an ERR_PTR.  Instead it returns
646  * a VM_FAULT code, encoded as an xarray internal entry.  The ERR_PTR values
647  * overlap with xarray value entries.
648  */
649 static void *grab_mapping_entry(struct xa_state *xas,
650 		struct address_space *mapping, unsigned int order)
651 {
652 	unsigned long index = xas->xa_index;
653 	bool pmd_downgrade;	/* splitting PMD entry into PTE entries? */
654 	void *entry;
655 
656 retry:
657 	pmd_downgrade = false;
658 	xas_lock_irq(xas);
659 	entry = get_next_unlocked_entry(xas, order);
660 
661 	if (entry) {
662 		if (dax_is_conflict(entry))
663 			goto fallback;
664 		if (!xa_is_value(entry)) {
665 			xas_set_err(xas, -EIO);
666 			goto out_unlock;
667 		}
668 
669 		if (order == 0) {
670 			if (dax_is_pmd_entry(entry) &&
671 			    (dax_is_zero_entry(entry) ||
672 			     dax_is_empty_entry(entry))) {
673 				pmd_downgrade = true;
674 			}
675 		}
676 	}
677 
678 	if (pmd_downgrade) {
679 		/*
680 		 * Make sure 'entry' remains valid while we drop
681 		 * the i_pages lock.
682 		 */
683 		dax_lock_entry(xas, entry);
684 
685 		/*
686 		 * Besides huge zero pages the only other thing that gets
687 		 * downgraded are empty entries which don't need to be
688 		 * unmapped.
689 		 */
690 		if (dax_is_zero_entry(entry)) {
691 			xas_unlock_irq(xas);
692 			unmap_mapping_pages(mapping,
693 					xas->xa_index & ~PG_PMD_COLOUR,
694 					PG_PMD_NR, false);
695 			xas_reset(xas);
696 			xas_lock_irq(xas);
697 		}
698 
699 		dax_disassociate_entry(entry, mapping, false);
700 		xas_store(xas, NULL);	/* undo the PMD join */
701 		dax_wake_entry(xas, entry, WAKE_ALL);
702 		mapping->nrpages -= PG_PMD_NR;
703 		entry = NULL;
704 		xas_set(xas, index);
705 	}
706 
707 	if (entry) {
708 		dax_lock_entry(xas, entry);
709 	} else {
710 		unsigned long flags = DAX_EMPTY;
711 
712 		if (order > 0)
713 			flags |= DAX_PMD;
714 		entry = dax_make_entry(0, flags);
715 		dax_lock_entry(xas, entry);
716 		if (xas_error(xas))
717 			goto out_unlock;
718 		mapping->nrpages += 1UL << order;
719 	}
720 
721 out_unlock:
722 	xas_unlock_irq(xas);
723 	if (xas_nomem(xas, mapping_gfp_mask(mapping) & ~__GFP_HIGHMEM))
724 		goto retry;
725 	if (xas->xa_node == XA_ERROR(-ENOMEM))
726 		return xa_mk_internal(VM_FAULT_OOM);
727 	if (xas_error(xas))
728 		return xa_mk_internal(VM_FAULT_SIGBUS);
729 	return entry;
730 fallback:
731 	xas_unlock_irq(xas);
732 	return xa_mk_internal(VM_FAULT_FALLBACK);
733 }
734 
735 /**
736  * dax_layout_busy_page_range - find first pinned page in @mapping
737  * @mapping: address space to scan for a page with ref count > 1
738  * @start: Starting offset. Page containing 'start' is included.
739  * @end: End offset. Page containing 'end' is included. If 'end' is LLONG_MAX,
740  *       pages from 'start' till the end of file are included.
741  *
742  * DAX requires ZONE_DEVICE mapped pages. These pages are never
743  * 'onlined' to the page allocator so they are considered idle when
744  * page->count == 1. A filesystem uses this interface to determine if
745  * any page in the mapping is busy, i.e. for DMA, or other
746  * get_user_pages() usages.
747  *
748  * It is expected that the filesystem is holding locks to block the
749  * establishment of new mappings in this address_space. I.e. it expects
750  * to be able to run unmap_mapping_range() and subsequently not race
751  * mapping_mapped() becoming true.
752  */
753 struct page *dax_layout_busy_page_range(struct address_space *mapping,
754 					loff_t start, loff_t end)
755 {
756 	void *entry;
757 	unsigned int scanned = 0;
758 	struct page *page = NULL;
759 	pgoff_t start_idx = start >> PAGE_SHIFT;
760 	pgoff_t end_idx;
761 	XA_STATE(xas, &mapping->i_pages, start_idx);
762 
763 	if (!dax_mapping(mapping))
764 		return NULL;
765 
766 	/* If end == LLONG_MAX, all pages from start to till end of file */
767 	if (end == LLONG_MAX)
768 		end_idx = ULONG_MAX;
769 	else
770 		end_idx = end >> PAGE_SHIFT;
771 	/*
772 	 * If we race get_user_pages_fast() here either we'll see the
773 	 * elevated page count in the iteration and wait, or
774 	 * get_user_pages_fast() will see that the page it took a reference
775 	 * against is no longer mapped in the page tables and bail to the
776 	 * get_user_pages() slow path.  The slow path is protected by
777 	 * pte_lock() and pmd_lock(). New references are not taken without
778 	 * holding those locks, and unmap_mapping_pages() will not zero the
779 	 * pte or pmd without holding the respective lock, so we are
780 	 * guaranteed to either see new references or prevent new
781 	 * references from being established.
782 	 */
783 	unmap_mapping_pages(mapping, start_idx, end_idx - start_idx + 1, 0);
784 
785 	xas_lock_irq(&xas);
786 	xas_for_each(&xas, entry, end_idx) {
787 		if (WARN_ON_ONCE(!xa_is_value(entry)))
788 			continue;
789 		entry = wait_entry_unlocked_exclusive(&xas, entry);
790 		if (entry)
791 			page = dax_busy_page(entry);
792 		put_unlocked_entry(&xas, entry, WAKE_NEXT);
793 		if (page)
794 			break;
795 		if (++scanned % XA_CHECK_SCHED)
796 			continue;
797 
798 		xas_pause(&xas);
799 		xas_unlock_irq(&xas);
800 		cond_resched();
801 		xas_lock_irq(&xas);
802 	}
803 	xas_unlock_irq(&xas);
804 	return page;
805 }
806 EXPORT_SYMBOL_GPL(dax_layout_busy_page_range);
807 
808 struct page *dax_layout_busy_page(struct address_space *mapping)
809 {
810 	return dax_layout_busy_page_range(mapping, 0, LLONG_MAX);
811 }
812 EXPORT_SYMBOL_GPL(dax_layout_busy_page);
813 
814 static int __dax_invalidate_entry(struct address_space *mapping,
815 				  pgoff_t index, bool trunc)
816 {
817 	XA_STATE(xas, &mapping->i_pages, index);
818 	int ret = 0;
819 	void *entry;
820 
821 	xas_lock_irq(&xas);
822 	entry = get_next_unlocked_entry(&xas, 0);
823 	if (!entry || WARN_ON_ONCE(!xa_is_value(entry)))
824 		goto out;
825 	if (!trunc &&
826 	    (xas_get_mark(&xas, PAGECACHE_TAG_DIRTY) ||
827 	     xas_get_mark(&xas, PAGECACHE_TAG_TOWRITE)))
828 		goto out;
829 	dax_disassociate_entry(entry, mapping, trunc);
830 	xas_store(&xas, NULL);
831 	mapping->nrpages -= 1UL << dax_entry_order(entry);
832 	ret = 1;
833 out:
834 	put_unlocked_entry(&xas, entry, WAKE_ALL);
835 	xas_unlock_irq(&xas);
836 	return ret;
837 }
838 
839 static int __dax_clear_dirty_range(struct address_space *mapping,
840 		pgoff_t start, pgoff_t end)
841 {
842 	XA_STATE(xas, &mapping->i_pages, start);
843 	unsigned int scanned = 0;
844 	void *entry;
845 
846 	xas_lock_irq(&xas);
847 	xas_for_each(&xas, entry, end) {
848 		entry = wait_entry_unlocked_exclusive(&xas, entry);
849 		if (!entry)
850 			continue;
851 		xas_clear_mark(&xas, PAGECACHE_TAG_DIRTY);
852 		xas_clear_mark(&xas, PAGECACHE_TAG_TOWRITE);
853 		put_unlocked_entry(&xas, entry, WAKE_NEXT);
854 
855 		if (++scanned % XA_CHECK_SCHED)
856 			continue;
857 
858 		xas_pause(&xas);
859 		xas_unlock_irq(&xas);
860 		cond_resched();
861 		xas_lock_irq(&xas);
862 	}
863 	xas_unlock_irq(&xas);
864 
865 	return 0;
866 }
867 
868 /*
869  * Delete DAX entry at @index from @mapping.  Wait for it
870  * to be unlocked before deleting it.
871  */
872 int dax_delete_mapping_entry(struct address_space *mapping, pgoff_t index)
873 {
874 	int ret = __dax_invalidate_entry(mapping, index, true);
875 
876 	/*
877 	 * This gets called from truncate / punch_hole path. As such, the caller
878 	 * must hold locks protecting against concurrent modifications of the
879 	 * page cache (usually fs-private i_mmap_sem for writing). Since the
880 	 * caller has seen a DAX entry for this index, we better find it
881 	 * at that index as well...
882 	 */
883 	WARN_ON_ONCE(!ret);
884 	return ret;
885 }
886 
887 void dax_delete_mapping_range(struct address_space *mapping,
888 				loff_t start, loff_t end)
889 {
890 	void *entry;
891 	pgoff_t start_idx = start >> PAGE_SHIFT;
892 	pgoff_t end_idx;
893 	XA_STATE(xas, &mapping->i_pages, start_idx);
894 
895 	/* If end == LLONG_MAX, all pages from start to till end of file */
896 	if (end == LLONG_MAX)
897 		end_idx = ULONG_MAX;
898 	else
899 		end_idx = end >> PAGE_SHIFT;
900 
901 	xas_lock_irq(&xas);
902 	xas_for_each(&xas, entry, end_idx) {
903 		if (!xa_is_value(entry))
904 			continue;
905 		entry = wait_entry_unlocked_exclusive(&xas, entry);
906 		if (!entry)
907 			continue;
908 		dax_disassociate_entry(entry, mapping, true);
909 		xas_store(&xas, NULL);
910 		mapping->nrpages -= 1UL << dax_entry_order(entry);
911 		put_unlocked_entry(&xas, entry, WAKE_ALL);
912 	}
913 	xas_unlock_irq(&xas);
914 }
915 EXPORT_SYMBOL_GPL(dax_delete_mapping_range);
916 
917 static int wait_page_idle(struct page *page,
918 			void (cb)(struct inode *),
919 			struct inode *inode)
920 {
921 	return ___wait_var_event(page, dax_page_is_idle(page),
922 				TASK_INTERRUPTIBLE, 0, 0, cb(inode));
923 }
924 
925 static void wait_page_idle_uninterruptible(struct page *page,
926 					struct inode *inode)
927 {
928 	___wait_var_event(page, dax_page_is_idle(page),
929 			TASK_UNINTERRUPTIBLE, 0, 0, schedule());
930 }
931 
932 /*
933  * Unmaps the inode and waits for any DMA to complete prior to deleting the
934  * DAX mapping entries for the range.
935  *
936  * For NOWAIT behavior, pass @cb as NULL to early-exit on first found
937  * busy page
938  */
939 int dax_break_layout(struct inode *inode, loff_t start, loff_t end,
940 		void (cb)(struct inode *))
941 {
942 	struct page *page;
943 	int error = 0;
944 
945 	if (!dax_mapping(inode->i_mapping))
946 		return 0;
947 
948 	do {
949 		page = dax_layout_busy_page_range(inode->i_mapping, start, end);
950 		if (!page)
951 			break;
952 		if (!cb) {
953 			error = -ERESTARTSYS;
954 			break;
955 		}
956 
957 		error = wait_page_idle(page, cb, inode);
958 	} while (error == 0);
959 
960 	if (!page)
961 		dax_delete_mapping_range(inode->i_mapping, start, end);
962 
963 	return error;
964 }
965 EXPORT_SYMBOL_GPL(dax_break_layout);
966 
967 void dax_break_layout_final(struct inode *inode)
968 {
969 	struct page *page;
970 
971 	if (!dax_mapping(inode->i_mapping))
972 		return;
973 
974 	do {
975 		page = dax_layout_busy_page_range(inode->i_mapping, 0,
976 						LLONG_MAX);
977 		if (!page)
978 			break;
979 
980 		wait_page_idle_uninterruptible(page, inode);
981 	} while (true);
982 
983 	if (!page)
984 		dax_delete_mapping_range(inode->i_mapping, 0, LLONG_MAX);
985 }
986 EXPORT_SYMBOL_GPL(dax_break_layout_final);
987 
988 /*
989  * Invalidate DAX entry if it is clean.
990  */
991 int dax_invalidate_mapping_entry_sync(struct address_space *mapping,
992 				      pgoff_t index)
993 {
994 	return __dax_invalidate_entry(mapping, index, false);
995 }
996 
997 static pgoff_t dax_iomap_pgoff(const struct iomap *iomap, loff_t pos)
998 {
999 	return PHYS_PFN(iomap->addr + (pos & PAGE_MASK) - iomap->offset);
1000 }
1001 
1002 static int copy_cow_page_dax(struct vm_fault *vmf, const struct iomap_iter *iter)
1003 {
1004 	pgoff_t pgoff = dax_iomap_pgoff(&iter->iomap, iter->pos);
1005 	void *vto, *kaddr;
1006 	long rc;
1007 	int id;
1008 
1009 	id = dax_read_lock();
1010 	rc = dax_direct_access(iter->iomap.dax_dev, pgoff, 1, DAX_ACCESS,
1011 				&kaddr, NULL);
1012 	if (rc < 0) {
1013 		dax_read_unlock(id);
1014 		return rc;
1015 	}
1016 	vto = kmap_atomic(vmf->cow_page);
1017 	copy_user_page(vto, kaddr, vmf->address, vmf->cow_page);
1018 	kunmap_atomic(vto);
1019 	dax_read_unlock(id);
1020 	return 0;
1021 }
1022 
1023 /*
1024  * MAP_SYNC on a dax mapping guarantees dirty metadata is
1025  * flushed on write-faults (non-cow), but not read-faults.
1026  */
1027 static bool dax_fault_is_synchronous(const struct iomap_iter *iter,
1028 		struct vm_area_struct *vma)
1029 {
1030 	return (iter->flags & IOMAP_WRITE) && (vma->vm_flags & VM_SYNC) &&
1031 		(iter->iomap.flags & IOMAP_F_DIRTY);
1032 }
1033 
1034 /*
1035  * By this point grab_mapping_entry() has ensured that we have a locked entry
1036  * of the appropriate size so we don't have to worry about downgrading PMDs to
1037  * PTEs.  If we happen to be trying to insert a PTE and there is a PMD
1038  * already in the tree, we will skip the insertion and just dirty the PMD as
1039  * appropriate.
1040  */
1041 static void *dax_insert_entry(struct xa_state *xas, struct vm_fault *vmf,
1042 		const struct iomap_iter *iter, void *entry, unsigned long pfn,
1043 		unsigned long flags)
1044 {
1045 	struct address_space *mapping = vmf->vma->vm_file->f_mapping;
1046 	void *new_entry = dax_make_entry(pfn, flags);
1047 	bool write = iter->flags & IOMAP_WRITE;
1048 	bool dirty = write && !dax_fault_is_synchronous(iter, vmf->vma);
1049 	bool shared = iter->iomap.flags & IOMAP_F_SHARED;
1050 
1051 	if (dirty)
1052 		__mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
1053 
1054 	if (shared || (dax_is_zero_entry(entry) && !(flags & DAX_ZERO_PAGE))) {
1055 		unsigned long index = xas->xa_index;
1056 		/* we are replacing a zero page with block mapping */
1057 		if (dax_is_pmd_entry(entry))
1058 			unmap_mapping_pages(mapping, index & ~PG_PMD_COLOUR,
1059 					PG_PMD_NR, false);
1060 		else /* pte entry */
1061 			unmap_mapping_pages(mapping, index, 1, false);
1062 	}
1063 
1064 	xas_reset(xas);
1065 	xas_lock_irq(xas);
1066 	if (shared || dax_is_zero_entry(entry) || dax_is_empty_entry(entry)) {
1067 		void *old;
1068 
1069 		dax_disassociate_entry(entry, mapping, false);
1070 		dax_associate_entry(new_entry, mapping, vmf->vma,
1071 					vmf->address, shared);
1072 
1073 		/*
1074 		 * Only swap our new entry into the page cache if the current
1075 		 * entry is a zero page or an empty entry.  If a normal PTE or
1076 		 * PMD entry is already in the cache, we leave it alone.  This
1077 		 * means that if we are trying to insert a PTE and the
1078 		 * existing entry is a PMD, we will just leave the PMD in the
1079 		 * tree and dirty it if necessary.
1080 		 */
1081 		old = dax_lock_entry(xas, new_entry);
1082 		WARN_ON_ONCE(old != xa_mk_value(xa_to_value(entry) |
1083 					DAX_LOCKED));
1084 		entry = new_entry;
1085 	} else {
1086 		xas_load(xas);	/* Walk the xa_state */
1087 	}
1088 
1089 	if (dirty)
1090 		xas_set_mark(xas, PAGECACHE_TAG_DIRTY);
1091 
1092 	if (write && shared)
1093 		xas_set_mark(xas, PAGECACHE_TAG_TOWRITE);
1094 
1095 	xas_unlock_irq(xas);
1096 	return entry;
1097 }
1098 
1099 static int dax_writeback_one(struct xa_state *xas, struct dax_device *dax_dev,
1100 		struct address_space *mapping, void *entry)
1101 {
1102 	unsigned long pfn, index, count, end;
1103 	long ret = 0;
1104 	struct vm_area_struct *vma;
1105 
1106 	/*
1107 	 * A page got tagged dirty in DAX mapping? Something is seriously
1108 	 * wrong.
1109 	 */
1110 	if (WARN_ON(!xa_is_value(entry)))
1111 		return -EIO;
1112 
1113 	if (unlikely(dax_is_locked(entry))) {
1114 		void *old_entry = entry;
1115 
1116 		entry = get_next_unlocked_entry(xas, 0);
1117 
1118 		/* Entry got punched out / reallocated? */
1119 		if (!entry || WARN_ON_ONCE(!xa_is_value(entry)))
1120 			goto put_unlocked;
1121 		/*
1122 		 * Entry got reallocated elsewhere? No need to writeback.
1123 		 * We have to compare pfns as we must not bail out due to
1124 		 * difference in lockbit or entry type.
1125 		 */
1126 		if (dax_to_pfn(old_entry) != dax_to_pfn(entry))
1127 			goto put_unlocked;
1128 		if (WARN_ON_ONCE(dax_is_empty_entry(entry) ||
1129 					dax_is_zero_entry(entry))) {
1130 			ret = -EIO;
1131 			goto put_unlocked;
1132 		}
1133 
1134 		/* Another fsync thread may have already done this entry */
1135 		if (!xas_get_mark(xas, PAGECACHE_TAG_TOWRITE))
1136 			goto put_unlocked;
1137 	}
1138 
1139 	/* Lock the entry to serialize with page faults */
1140 	dax_lock_entry(xas, entry);
1141 
1142 	/*
1143 	 * We can clear the tag now but we have to be careful so that concurrent
1144 	 * dax_writeback_one() calls for the same index cannot finish before we
1145 	 * actually flush the caches. This is achieved as the calls will look
1146 	 * at the entry only under the i_pages lock and once they do that
1147 	 * they will see the entry locked and wait for it to unlock.
1148 	 */
1149 	xas_clear_mark(xas, PAGECACHE_TAG_TOWRITE);
1150 	xas_unlock_irq(xas);
1151 
1152 	/*
1153 	 * If dax_writeback_mapping_range() was given a wbc->range_start
1154 	 * in the middle of a PMD, the 'index' we use needs to be
1155 	 * aligned to the start of the PMD.
1156 	 * This allows us to flush for PMD_SIZE and not have to worry about
1157 	 * partial PMD writebacks.
1158 	 */
1159 	pfn = dax_to_pfn(entry);
1160 	count = 1UL << dax_entry_order(entry);
1161 	index = xas->xa_index & ~(count - 1);
1162 	end = index + count - 1;
1163 
1164 	/* Walk all mappings of a given index of a file and writeprotect them */
1165 	i_mmap_lock_read(mapping);
1166 	vma_interval_tree_foreach(vma, &mapping->i_mmap, index, end) {
1167 		pfn_mkclean_range(pfn, count, index, vma);
1168 		cond_resched();
1169 	}
1170 	i_mmap_unlock_read(mapping);
1171 
1172 	dax_flush(dax_dev, page_address(pfn_to_page(pfn)), count * PAGE_SIZE);
1173 	/*
1174 	 * After we have flushed the cache, we can clear the dirty tag. There
1175 	 * cannot be new dirty data in the pfn after the flush has completed as
1176 	 * the pfn mappings are writeprotected and fault waits for mapping
1177 	 * entry lock.
1178 	 */
1179 	xas_reset(xas);
1180 	xas_lock_irq(xas);
1181 	xas_store(xas, entry);
1182 	xas_clear_mark(xas, PAGECACHE_TAG_DIRTY);
1183 	dax_wake_entry(xas, entry, WAKE_NEXT);
1184 
1185 	trace_dax_writeback_one(mapping->host, index, count);
1186 	return ret;
1187 
1188  put_unlocked:
1189 	put_unlocked_entry(xas, entry, WAKE_NEXT);
1190 	return ret;
1191 }
1192 
1193 /*
1194  * Flush the mapping to the persistent domain within the byte range of [start,
1195  * end]. This is required by data integrity operations to ensure file data is
1196  * on persistent storage prior to completion of the operation.
1197  */
1198 int dax_writeback_mapping_range(struct address_space *mapping,
1199 		struct dax_device *dax_dev, struct writeback_control *wbc)
1200 {
1201 	XA_STATE(xas, &mapping->i_pages, wbc->range_start >> PAGE_SHIFT);
1202 	struct inode *inode = mapping->host;
1203 	pgoff_t end_index = wbc->range_end >> PAGE_SHIFT;
1204 	void *entry;
1205 	int ret = 0;
1206 	unsigned int scanned = 0;
1207 
1208 	if (WARN_ON_ONCE(inode->i_blkbits != PAGE_SHIFT))
1209 		return -EIO;
1210 
1211 	if (mapping_empty(mapping) || wbc->sync_mode != WB_SYNC_ALL)
1212 		return 0;
1213 
1214 	trace_dax_writeback_range(inode, xas.xa_index, end_index);
1215 
1216 	tag_pages_for_writeback(mapping, xas.xa_index, end_index);
1217 
1218 	xas_lock_irq(&xas);
1219 	xas_for_each_marked(&xas, entry, end_index, PAGECACHE_TAG_TOWRITE) {
1220 		ret = dax_writeback_one(&xas, dax_dev, mapping, entry);
1221 		if (ret < 0) {
1222 			mapping_set_error(mapping, ret);
1223 			break;
1224 		}
1225 		if (++scanned % XA_CHECK_SCHED)
1226 			continue;
1227 
1228 		xas_pause(&xas);
1229 		xas_unlock_irq(&xas);
1230 		cond_resched();
1231 		xas_lock_irq(&xas);
1232 	}
1233 	xas_unlock_irq(&xas);
1234 	trace_dax_writeback_range_done(inode, xas.xa_index, end_index);
1235 	return ret;
1236 }
1237 EXPORT_SYMBOL_GPL(dax_writeback_mapping_range);
1238 
1239 static int dax_iomap_direct_access(const struct iomap *iomap, loff_t pos,
1240 		size_t size, void **kaddr, unsigned long *pfnp)
1241 {
1242 	pgoff_t pgoff = dax_iomap_pgoff(iomap, pos);
1243 	int id, rc = 0;
1244 	long length;
1245 
1246 	id = dax_read_lock();
1247 	length = dax_direct_access(iomap->dax_dev, pgoff, PHYS_PFN(size),
1248 				   DAX_ACCESS, kaddr, pfnp);
1249 	if (length < 0) {
1250 		rc = length;
1251 		goto out;
1252 	}
1253 	if (!pfnp)
1254 		goto out_check_addr;
1255 	rc = -EINVAL;
1256 	if (PFN_PHYS(length) < size)
1257 		goto out;
1258 	if (*pfnp & (PHYS_PFN(size)-1))
1259 		goto out;
1260 
1261 	rc = 0;
1262 
1263 out_check_addr:
1264 	if (!kaddr)
1265 		goto out;
1266 	if (!*kaddr)
1267 		rc = -EFAULT;
1268 out:
1269 	dax_read_unlock(id);
1270 	return rc;
1271 }
1272 
1273 /**
1274  * dax_iomap_copy_around - Prepare for an unaligned write to a shared/cow page
1275  * by copying the data before and after the range to be written.
1276  * @pos:	address to do copy from.
1277  * @length:	size of copy operation.
1278  * @align_size:	aligned w.r.t align_size (either PMD_SIZE or PAGE_SIZE)
1279  * @srcmap:	iomap srcmap
1280  * @daddr:	destination address to copy to.
1281  *
1282  * This can be called from two places. Either during DAX write fault (page
1283  * aligned), to copy the length size data to daddr. Or, while doing normal DAX
1284  * write operation, dax_iomap_iter() might call this to do the copy of either
1285  * start or end unaligned address. In the latter case the rest of the copy of
1286  * aligned ranges is taken care by dax_iomap_iter() itself.
1287  * If the srcmap contains invalid data, such as HOLE and UNWRITTEN, zero the
1288  * area to make sure no old data remains.
1289  */
1290 static int dax_iomap_copy_around(loff_t pos, uint64_t length, size_t align_size,
1291 		const struct iomap *srcmap, void *daddr)
1292 {
1293 	loff_t head_off = pos & (align_size - 1);
1294 	size_t size = ALIGN(head_off + length, align_size);
1295 	loff_t end = pos + length;
1296 	loff_t pg_end = round_up(end, align_size);
1297 	/* copy_all is usually in page fault case */
1298 	bool copy_all = head_off == 0 && end == pg_end;
1299 	/* zero the edges if srcmap is a HOLE or IOMAP_UNWRITTEN */
1300 	bool zero_edge = srcmap->flags & IOMAP_F_SHARED ||
1301 			 srcmap->type == IOMAP_UNWRITTEN;
1302 	void *saddr = NULL;
1303 	int ret = 0;
1304 
1305 	if (!zero_edge) {
1306 		ret = dax_iomap_direct_access(srcmap, pos, size, &saddr, NULL);
1307 		if (ret)
1308 			return dax_mem2blk_err(ret);
1309 	}
1310 
1311 	if (copy_all) {
1312 		if (zero_edge)
1313 			memset(daddr, 0, size);
1314 		else
1315 			ret = copy_mc_to_kernel(daddr, saddr, length);
1316 		goto out;
1317 	}
1318 
1319 	/* Copy the head part of the range */
1320 	if (head_off) {
1321 		if (zero_edge)
1322 			memset(daddr, 0, head_off);
1323 		else {
1324 			ret = copy_mc_to_kernel(daddr, saddr, head_off);
1325 			if (ret)
1326 				return -EIO;
1327 		}
1328 	}
1329 
1330 	/* Copy the tail part of the range */
1331 	if (end < pg_end) {
1332 		loff_t tail_off = head_off + length;
1333 		loff_t tail_len = pg_end - end;
1334 
1335 		if (zero_edge)
1336 			memset(daddr + tail_off, 0, tail_len);
1337 		else {
1338 			ret = copy_mc_to_kernel(daddr + tail_off,
1339 						saddr + tail_off, tail_len);
1340 			if (ret)
1341 				return -EIO;
1342 		}
1343 	}
1344 out:
1345 	if (zero_edge)
1346 		dax_flush(srcmap->dax_dev, daddr, size);
1347 	return ret ? -EIO : 0;
1348 }
1349 
1350 /*
1351  * The user has performed a load from a hole in the file.  Allocating a new
1352  * page in the file would cause excessive storage usage for workloads with
1353  * sparse files.  Instead we insert a read-only mapping of the 4k zero page.
1354  * If this page is ever written to we will re-fault and change the mapping to
1355  * point to real DAX storage instead.
1356  */
1357 static vm_fault_t dax_load_hole(struct xa_state *xas, struct vm_fault *vmf,
1358 		const struct iomap_iter *iter, void **entry)
1359 {
1360 	struct inode *inode = iter->inode;
1361 	unsigned long vaddr = vmf->address;
1362 	unsigned long pfn = zero_pfn(vaddr);
1363 	vm_fault_t ret;
1364 
1365 	*entry = dax_insert_entry(xas, vmf, iter, *entry, pfn, DAX_ZERO_PAGE);
1366 
1367 	ret = vmf_insert_page_mkwrite(vmf, pfn_to_page(pfn), false);
1368 	trace_dax_load_hole(inode, vmf, ret);
1369 	return ret;
1370 }
1371 
1372 #ifdef CONFIG_FS_DAX_PMD
1373 static vm_fault_t dax_pmd_load_hole(struct xa_state *xas, struct vm_fault *vmf,
1374 		const struct iomap_iter *iter, void **entry)
1375 {
1376 	struct address_space *mapping = vmf->vma->vm_file->f_mapping;
1377 	struct inode *inode = mapping->host;
1378 	struct folio *zero_folio;
1379 	vm_fault_t ret;
1380 
1381 	zero_folio = mm_get_huge_zero_folio(vmf->vma->vm_mm);
1382 
1383 	if (unlikely(!zero_folio)) {
1384 		trace_dax_pmd_load_hole_fallback(inode, vmf, zero_folio, *entry);
1385 		return VM_FAULT_FALLBACK;
1386 	}
1387 
1388 	*entry = dax_insert_entry(xas, vmf, iter, *entry, folio_pfn(zero_folio),
1389 				  DAX_PMD | DAX_ZERO_PAGE);
1390 
1391 	ret = vmf_insert_folio_pmd(vmf, zero_folio, false);
1392 	if (ret == VM_FAULT_NOPAGE)
1393 		trace_dax_pmd_load_hole(inode, vmf, zero_folio, *entry);
1394 	return ret;
1395 }
1396 #else
1397 static vm_fault_t dax_pmd_load_hole(struct xa_state *xas, struct vm_fault *vmf,
1398 		const struct iomap_iter *iter, void **entry)
1399 {
1400 	return VM_FAULT_FALLBACK;
1401 }
1402 #endif /* CONFIG_FS_DAX_PMD */
1403 
1404 static int dax_unshare_iter(struct iomap_iter *iter)
1405 {
1406 	struct iomap *iomap = &iter->iomap;
1407 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
1408 	loff_t copy_pos = iter->pos;
1409 	u64 copy_len = iomap_length(iter);
1410 	u32 mod;
1411 	int id = 0;
1412 	s64 ret;
1413 	void *daddr = NULL, *saddr = NULL;
1414 
1415 	if (!iomap_want_unshare_iter(iter))
1416 		return iomap_iter_advance_full(iter);
1417 
1418 	/*
1419 	 * Extend the file range to be aligned to fsblock/pagesize, because
1420 	 * we need to copy entire blocks, not just the byte range specified.
1421 	 * Invalidate the mapping because we're about to CoW.
1422 	 */
1423 	mod = offset_in_page(copy_pos);
1424 	if (mod) {
1425 		copy_len += mod;
1426 		copy_pos -= mod;
1427 	}
1428 
1429 	mod = offset_in_page(copy_pos + copy_len);
1430 	if (mod)
1431 		copy_len += PAGE_SIZE - mod;
1432 
1433 	invalidate_inode_pages2_range(iter->inode->i_mapping,
1434 				      copy_pos >> PAGE_SHIFT,
1435 				      (copy_pos + copy_len - 1) >> PAGE_SHIFT);
1436 
1437 	id = dax_read_lock();
1438 	ret = dax_iomap_direct_access(iomap, copy_pos, copy_len, &daddr, NULL);
1439 	if (ret < 0)
1440 		goto out_unlock;
1441 
1442 	ret = dax_iomap_direct_access(srcmap, copy_pos, copy_len, &saddr, NULL);
1443 	if (ret < 0)
1444 		goto out_unlock;
1445 
1446 	if (copy_mc_to_kernel(daddr, saddr, copy_len) != 0)
1447 		ret = -EIO;
1448 
1449 out_unlock:
1450 	dax_read_unlock(id);
1451 	if (ret < 0)
1452 		return dax_mem2blk_err(ret);
1453 	return iomap_iter_advance_full(iter);
1454 }
1455 
1456 int dax_file_unshare(struct inode *inode, loff_t pos, loff_t len,
1457 		const struct iomap_ops *ops)
1458 {
1459 	struct iomap_iter iter = {
1460 		.inode		= inode,
1461 		.pos		= pos,
1462 		.flags		= IOMAP_WRITE | IOMAP_UNSHARE | IOMAP_DAX,
1463 	};
1464 	loff_t size = i_size_read(inode);
1465 	int ret;
1466 
1467 	if (pos < 0 || pos >= size)
1468 		return 0;
1469 
1470 	iter.len = min(len, size - pos);
1471 	while ((ret = iomap_iter(&iter, ops)) > 0)
1472 		iter.status = dax_unshare_iter(&iter);
1473 	return ret;
1474 }
1475 EXPORT_SYMBOL_GPL(dax_file_unshare);
1476 
1477 static int dax_memzero(struct iomap_iter *iter, loff_t pos, size_t size)
1478 {
1479 	const struct iomap *iomap = &iter->iomap;
1480 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
1481 	unsigned offset = offset_in_page(pos);
1482 	pgoff_t pgoff = dax_iomap_pgoff(iomap, pos);
1483 	void *kaddr;
1484 	long ret;
1485 
1486 	ret = dax_direct_access(iomap->dax_dev, pgoff, 1, DAX_ACCESS, &kaddr,
1487 				NULL);
1488 	if (ret < 0)
1489 		return dax_mem2blk_err(ret);
1490 
1491 	memset(kaddr + offset, 0, size);
1492 	if (iomap->flags & IOMAP_F_SHARED)
1493 		ret = dax_iomap_copy_around(pos, size, PAGE_SIZE, srcmap,
1494 					    kaddr);
1495 	else
1496 		dax_flush(iomap->dax_dev, kaddr + offset, size);
1497 	return ret;
1498 }
1499 
1500 static int dax_zero_iter(struct iomap_iter *iter, bool *did_zero)
1501 {
1502 	const struct iomap *iomap = &iter->iomap;
1503 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
1504 	u64 length = iomap_length(iter);
1505 	int ret;
1506 
1507 	/* already zeroed?  we're done. */
1508 	if (srcmap->type == IOMAP_HOLE || srcmap->type == IOMAP_UNWRITTEN)
1509 		return iomap_iter_advance(iter, length);
1510 
1511 	/*
1512 	 * invalidate the pages whose sharing state is to be changed
1513 	 * because of CoW.
1514 	 */
1515 	if (iomap->flags & IOMAP_F_SHARED)
1516 		invalidate_inode_pages2_range(iter->inode->i_mapping,
1517 				iter->pos >> PAGE_SHIFT,
1518 				(iter->pos + length - 1) >> PAGE_SHIFT);
1519 
1520 	do {
1521 		loff_t pos = iter->pos;
1522 		unsigned offset = offset_in_page(pos);
1523 		pgoff_t pgoff = dax_iomap_pgoff(iomap, pos);
1524 		int id;
1525 
1526 		length = min_t(u64, PAGE_SIZE - offset, length);
1527 
1528 		id = dax_read_lock();
1529 		if (IS_ALIGNED(pos, PAGE_SIZE) && length == PAGE_SIZE)
1530 			ret = dax_zero_page_range(iomap->dax_dev, pgoff, 1);
1531 		else
1532 			ret = dax_memzero(iter, pos, length);
1533 		dax_read_unlock(id);
1534 
1535 		if (ret < 0)
1536 			return ret;
1537 
1538 		ret = iomap_iter_advance(iter, length);
1539 		if (ret)
1540 			return ret;
1541 	} while ((length = iomap_length(iter)) > 0);
1542 
1543 	if (did_zero)
1544 		*did_zero = true;
1545 	return ret;
1546 }
1547 
1548 int dax_zero_range(struct inode *inode, loff_t pos, loff_t len, bool *did_zero,
1549 		const struct iomap_ops *ops)
1550 {
1551 	struct iomap_iter iter = {
1552 		.inode		= inode,
1553 		.pos		= pos,
1554 		.len		= len,
1555 		.flags		= IOMAP_DAX | IOMAP_ZERO,
1556 	};
1557 	int ret;
1558 
1559 	while ((ret = iomap_iter(&iter, ops)) > 0)
1560 		iter.status = dax_zero_iter(&iter, did_zero);
1561 	return ret;
1562 }
1563 EXPORT_SYMBOL_GPL(dax_zero_range);
1564 
1565 int dax_truncate_page(struct inode *inode, loff_t pos, bool *did_zero,
1566 		const struct iomap_ops *ops)
1567 {
1568 	unsigned int blocksize = i_blocksize(inode);
1569 	unsigned int off = pos & (blocksize - 1);
1570 
1571 	/* Block boundary? Nothing to do */
1572 	if (!off)
1573 		return 0;
1574 	return dax_zero_range(inode, pos, blocksize - off, did_zero, ops);
1575 }
1576 EXPORT_SYMBOL_GPL(dax_truncate_page);
1577 
1578 static int dax_iomap_iter(struct iomap_iter *iomi, struct iov_iter *iter)
1579 {
1580 	const struct iomap *iomap = &iomi->iomap;
1581 	const struct iomap *srcmap = iomap_iter_srcmap(iomi);
1582 	loff_t length = iomap_length(iomi);
1583 	loff_t pos = iomi->pos;
1584 	struct dax_device *dax_dev = iomap->dax_dev;
1585 	loff_t end = pos + length, done = 0;
1586 	bool write = iov_iter_rw(iter) == WRITE;
1587 	bool cow = write && iomap->flags & IOMAP_F_SHARED;
1588 	ssize_t ret = 0;
1589 	size_t xfer;
1590 	int id;
1591 
1592 	if (!write) {
1593 		end = min(end, i_size_read(iomi->inode));
1594 		if (pos >= end)
1595 			return 0;
1596 
1597 		if (iomap->type == IOMAP_HOLE || iomap->type == IOMAP_UNWRITTEN) {
1598 			done = iov_iter_zero(min(length, end - pos), iter);
1599 			return iomap_iter_advance(iomi, done);
1600 		}
1601 	}
1602 
1603 	/*
1604 	 * In DAX mode, enforce either pure overwrites of written extents, or
1605 	 * writes to unwritten extents as part of a copy-on-write operation.
1606 	 */
1607 	if (WARN_ON_ONCE(iomap->type != IOMAP_MAPPED &&
1608 			!(iomap->flags & IOMAP_F_SHARED)))
1609 		return -EIO;
1610 
1611 	/*
1612 	 * Write can allocate block for an area which has a hole page mapped
1613 	 * into page tables. We have to tear down these mappings so that data
1614 	 * written by write(2) is visible in mmap.
1615 	 */
1616 	if (iomap->flags & IOMAP_F_NEW || cow) {
1617 		/*
1618 		 * Filesystem allows CoW on non-shared extents. The src extents
1619 		 * may have been mmapped with dirty mark before. To be able to
1620 		 * invalidate its dax entries, we need to clear the dirty mark
1621 		 * in advance.
1622 		 */
1623 		if (cow)
1624 			__dax_clear_dirty_range(iomi->inode->i_mapping,
1625 						pos >> PAGE_SHIFT,
1626 						(end - 1) >> PAGE_SHIFT);
1627 		invalidate_inode_pages2_range(iomi->inode->i_mapping,
1628 					      pos >> PAGE_SHIFT,
1629 					      (end - 1) >> PAGE_SHIFT);
1630 	}
1631 
1632 	id = dax_read_lock();
1633 	while ((pos = iomi->pos) < end) {
1634 		unsigned offset = pos & (PAGE_SIZE - 1);
1635 		const size_t size = ALIGN(length + offset, PAGE_SIZE);
1636 		pgoff_t pgoff = dax_iomap_pgoff(iomap, pos);
1637 		ssize_t map_len;
1638 		bool recovery = false;
1639 		void *kaddr;
1640 
1641 		if (fatal_signal_pending(current)) {
1642 			ret = -EINTR;
1643 			break;
1644 		}
1645 
1646 		map_len = dax_direct_access(dax_dev, pgoff, PHYS_PFN(size),
1647 				DAX_ACCESS, &kaddr, NULL);
1648 		if (map_len == -EHWPOISON && iov_iter_rw(iter) == WRITE) {
1649 			map_len = dax_direct_access(dax_dev, pgoff,
1650 					PHYS_PFN(size), DAX_RECOVERY_WRITE,
1651 					&kaddr, NULL);
1652 			if (map_len > 0)
1653 				recovery = true;
1654 		}
1655 		if (map_len < 0) {
1656 			ret = dax_mem2blk_err(map_len);
1657 			break;
1658 		}
1659 
1660 		if (cow) {
1661 			ret = dax_iomap_copy_around(pos, length, PAGE_SIZE,
1662 						    srcmap, kaddr);
1663 			if (ret)
1664 				break;
1665 		}
1666 
1667 		map_len = PFN_PHYS(map_len);
1668 		kaddr += offset;
1669 		map_len -= offset;
1670 		if (map_len > end - pos)
1671 			map_len = end - pos;
1672 
1673 		if (recovery)
1674 			xfer = dax_recovery_write(dax_dev, pgoff, kaddr,
1675 					map_len, iter);
1676 		else if (write)
1677 			xfer = dax_copy_from_iter(dax_dev, pgoff, kaddr,
1678 					map_len, iter);
1679 		else
1680 			xfer = dax_copy_to_iter(dax_dev, pgoff, kaddr,
1681 					map_len, iter);
1682 
1683 		ret = iomap_iter_advance(iomi, xfer);
1684 		if (!ret && xfer == 0)
1685 			ret = -EFAULT;
1686 		if (xfer < map_len)
1687 			break;
1688 		length = iomap_length(iomi);
1689 	}
1690 	dax_read_unlock(id);
1691 
1692 	return ret;
1693 }
1694 
1695 /**
1696  * dax_iomap_rw - Perform I/O to a DAX file
1697  * @iocb:	The control block for this I/O
1698  * @iter:	The addresses to do I/O from or to
1699  * @ops:	iomap ops passed from the file system
1700  *
1701  * This function performs read and write operations to directly mapped
1702  * persistent memory.  The callers needs to take care of read/write exclusion
1703  * and evicting any page cache pages in the region under I/O.
1704  */
1705 ssize_t
1706 dax_iomap_rw(struct kiocb *iocb, struct iov_iter *iter,
1707 		const struct iomap_ops *ops)
1708 {
1709 	struct iomap_iter iomi = {
1710 		.inode		= iocb->ki_filp->f_mapping->host,
1711 		.pos		= iocb->ki_pos,
1712 		.len		= iov_iter_count(iter),
1713 		.flags		= IOMAP_DAX,
1714 	};
1715 	loff_t done = 0;
1716 	int ret;
1717 
1718 	if (WARN_ON_ONCE(iocb->ki_flags & IOCB_ATOMIC))
1719 		return -EIO;
1720 
1721 	if (!iomi.len)
1722 		return 0;
1723 
1724 	if (iov_iter_rw(iter) == WRITE) {
1725 		lockdep_assert_held_write(&iomi.inode->i_rwsem);
1726 		iomi.flags |= IOMAP_WRITE;
1727 	} else if (!sb_rdonly(iomi.inode->i_sb)) {
1728 		lockdep_assert_held(&iomi.inode->i_rwsem);
1729 	}
1730 
1731 	if (iocb->ki_flags & IOCB_NOWAIT)
1732 		iomi.flags |= IOMAP_NOWAIT;
1733 
1734 	while ((ret = iomap_iter(&iomi, ops)) > 0)
1735 		iomi.status = dax_iomap_iter(&iomi, iter);
1736 
1737 	done = iomi.pos - iocb->ki_pos;
1738 	iocb->ki_pos = iomi.pos;
1739 	return done ? done : ret;
1740 }
1741 EXPORT_SYMBOL_GPL(dax_iomap_rw);
1742 
1743 static vm_fault_t dax_fault_return(int error)
1744 {
1745 	if (error == 0)
1746 		return VM_FAULT_NOPAGE;
1747 	return vmf_error(error);
1748 }
1749 
1750 /*
1751  * When handling a synchronous page fault and the inode need a fsync, we can
1752  * insert the PTE/PMD into page tables only after that fsync happened. Skip
1753  * insertion for now and return the pfn so that caller can insert it after the
1754  * fsync is done.
1755  */
1756 static vm_fault_t dax_fault_synchronous_pfnp(unsigned long *pfnp,
1757 					unsigned long pfn)
1758 {
1759 	if (WARN_ON_ONCE(!pfnp))
1760 		return VM_FAULT_SIGBUS;
1761 	*pfnp = pfn;
1762 	return VM_FAULT_NEEDDSYNC;
1763 }
1764 
1765 static vm_fault_t dax_fault_cow_page(struct vm_fault *vmf,
1766 		const struct iomap_iter *iter)
1767 {
1768 	vm_fault_t ret;
1769 	int error = 0;
1770 
1771 	switch (iter->iomap.type) {
1772 	case IOMAP_HOLE:
1773 	case IOMAP_UNWRITTEN:
1774 		clear_user_highpage(vmf->cow_page, vmf->address);
1775 		break;
1776 	case IOMAP_MAPPED:
1777 		error = copy_cow_page_dax(vmf, iter);
1778 		break;
1779 	default:
1780 		WARN_ON_ONCE(1);
1781 		error = -EIO;
1782 		break;
1783 	}
1784 
1785 	if (error)
1786 		return dax_fault_return(error);
1787 
1788 	__SetPageUptodate(vmf->cow_page);
1789 	ret = finish_fault(vmf);
1790 	if (!ret)
1791 		return VM_FAULT_DONE_COW;
1792 	return ret;
1793 }
1794 
1795 /**
1796  * dax_fault_iter - Common actor to handle pfn insertion in PTE/PMD fault.
1797  * @vmf:	vm fault instance
1798  * @iter:	iomap iter
1799  * @pfnp:	pfn to be returned
1800  * @xas:	the dax mapping tree of a file
1801  * @entry:	an unlocked dax entry to be inserted
1802  * @pmd:	distinguish whether it is a pmd fault
1803  */
1804 static vm_fault_t dax_fault_iter(struct vm_fault *vmf,
1805 		const struct iomap_iter *iter, unsigned long *pfnp,
1806 		struct xa_state *xas, void **entry, bool pmd)
1807 {
1808 	const struct iomap *iomap = &iter->iomap;
1809 	const struct iomap *srcmap = iomap_iter_srcmap(iter);
1810 	size_t size = pmd ? PMD_SIZE : PAGE_SIZE;
1811 	loff_t pos = (loff_t)xas->xa_index << PAGE_SHIFT;
1812 	bool write = iter->flags & IOMAP_WRITE;
1813 	unsigned long entry_flags = pmd ? DAX_PMD : 0;
1814 	struct folio *folio;
1815 	int ret, err = 0;
1816 	unsigned long pfn;
1817 	void *kaddr;
1818 
1819 	if (!pmd && vmf->cow_page)
1820 		return dax_fault_cow_page(vmf, iter);
1821 
1822 	/* if we are reading UNWRITTEN and HOLE, return a hole. */
1823 	if (!write &&
1824 	    (iomap->type == IOMAP_UNWRITTEN || iomap->type == IOMAP_HOLE)) {
1825 		if (!pmd)
1826 			return dax_load_hole(xas, vmf, iter, entry);
1827 		return dax_pmd_load_hole(xas, vmf, iter, entry);
1828 	}
1829 
1830 	if (iomap->type != IOMAP_MAPPED && !(iomap->flags & IOMAP_F_SHARED)) {
1831 		WARN_ON_ONCE(1);
1832 		return pmd ? VM_FAULT_FALLBACK : VM_FAULT_SIGBUS;
1833 	}
1834 
1835 	err = dax_iomap_direct_access(iomap, pos, size, &kaddr, &pfn);
1836 	if (err)
1837 		return pmd ? VM_FAULT_FALLBACK : dax_fault_return(err);
1838 
1839 	*entry = dax_insert_entry(xas, vmf, iter, *entry, pfn, entry_flags);
1840 
1841 	if (write && iomap->flags & IOMAP_F_SHARED) {
1842 		err = dax_iomap_copy_around(pos, size, size, srcmap, kaddr);
1843 		if (err)
1844 			return dax_fault_return(err);
1845 	}
1846 
1847 	folio = dax_to_folio(*entry);
1848 	if (dax_fault_is_synchronous(iter, vmf->vma))
1849 		return dax_fault_synchronous_pfnp(pfnp, pfn);
1850 
1851 	folio_ref_inc(folio);
1852 	if (pmd)
1853 		ret = vmf_insert_folio_pmd(vmf, pfn_folio(pfn), write);
1854 	else
1855 		ret = vmf_insert_page_mkwrite(vmf, pfn_to_page(pfn), write);
1856 	folio_put(folio);
1857 
1858 	return ret;
1859 }
1860 
1861 static vm_fault_t dax_iomap_pte_fault(struct vm_fault *vmf, unsigned long *pfnp,
1862 			       int *iomap_errp, const struct iomap_ops *ops)
1863 {
1864 	struct address_space *mapping = vmf->vma->vm_file->f_mapping;
1865 	XA_STATE(xas, &mapping->i_pages, vmf->pgoff);
1866 	struct iomap_iter iter = {
1867 		.inode		= mapping->host,
1868 		.pos		= (loff_t)vmf->pgoff << PAGE_SHIFT,
1869 		.len		= PAGE_SIZE,
1870 		.flags		= IOMAP_DAX | IOMAP_FAULT,
1871 	};
1872 	vm_fault_t ret = 0;
1873 	void *entry;
1874 	int error;
1875 
1876 	trace_dax_pte_fault(iter.inode, vmf, ret);
1877 	/*
1878 	 * Check whether offset isn't beyond end of file now. Caller is supposed
1879 	 * to hold locks serializing us with truncate / punch hole so this is
1880 	 * a reliable test.
1881 	 */
1882 	if (iter.pos >= i_size_read(iter.inode)) {
1883 		ret = VM_FAULT_SIGBUS;
1884 		goto out;
1885 	}
1886 
1887 	if ((vmf->flags & FAULT_FLAG_WRITE) && !vmf->cow_page)
1888 		iter.flags |= IOMAP_WRITE;
1889 
1890 	entry = grab_mapping_entry(&xas, mapping, 0);
1891 	if (xa_is_internal(entry)) {
1892 		ret = xa_to_internal(entry);
1893 		goto out;
1894 	}
1895 
1896 	/*
1897 	 * It is possible, particularly with mixed reads & writes to private
1898 	 * mappings, that we have raced with a PMD fault that overlaps with
1899 	 * the PTE we need to set up.  If so just return and the fault will be
1900 	 * retried.
1901 	 */
1902 	if (pmd_trans_huge(*vmf->pmd)) {
1903 		ret = VM_FAULT_NOPAGE;
1904 		goto unlock_entry;
1905 	}
1906 
1907 	while ((error = iomap_iter(&iter, ops)) > 0) {
1908 		if (WARN_ON_ONCE(iomap_length(&iter) < PAGE_SIZE)) {
1909 			iter.status = -EIO;	/* fs corruption? */
1910 			continue;
1911 		}
1912 
1913 		ret = dax_fault_iter(vmf, &iter, pfnp, &xas, &entry, false);
1914 		if (ret != VM_FAULT_SIGBUS &&
1915 		    (iter.iomap.flags & IOMAP_F_NEW)) {
1916 			count_vm_event(PGMAJFAULT);
1917 			count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
1918 			ret |= VM_FAULT_MAJOR;
1919 		}
1920 
1921 		if (!(ret & VM_FAULT_ERROR))
1922 			iter.status = iomap_iter_advance(&iter, PAGE_SIZE);
1923 	}
1924 
1925 	if (iomap_errp)
1926 		*iomap_errp = error;
1927 	if (!ret && error)
1928 		ret = dax_fault_return(error);
1929 
1930 unlock_entry:
1931 	dax_unlock_entry(&xas, entry);
1932 out:
1933 	trace_dax_pte_fault_done(iter.inode, vmf, ret);
1934 	return ret;
1935 }
1936 
1937 #ifdef CONFIG_FS_DAX_PMD
1938 static bool dax_fault_check_fallback(struct vm_fault *vmf, struct xa_state *xas,
1939 		pgoff_t max_pgoff)
1940 {
1941 	unsigned long pmd_addr = vmf->address & PMD_MASK;
1942 	bool write = vmf->flags & FAULT_FLAG_WRITE;
1943 
1944 	/*
1945 	 * Make sure that the faulting address's PMD offset (color) matches
1946 	 * the PMD offset from the start of the file.  This is necessary so
1947 	 * that a PMD range in the page table overlaps exactly with a PMD
1948 	 * range in the page cache.
1949 	 */
1950 	if ((vmf->pgoff & PG_PMD_COLOUR) !=
1951 	    ((vmf->address >> PAGE_SHIFT) & PG_PMD_COLOUR))
1952 		return true;
1953 
1954 	/* Fall back to PTEs if we're going to COW */
1955 	if (write && !(vmf->vma->vm_flags & VM_SHARED))
1956 		return true;
1957 
1958 	/* If the PMD would extend outside the VMA */
1959 	if (pmd_addr < vmf->vma->vm_start)
1960 		return true;
1961 	if ((pmd_addr + PMD_SIZE) > vmf->vma->vm_end)
1962 		return true;
1963 
1964 	/* If the PMD would extend beyond the file size */
1965 	if ((xas->xa_index | PG_PMD_COLOUR) >= max_pgoff)
1966 		return true;
1967 
1968 	return false;
1969 }
1970 
1971 static vm_fault_t dax_iomap_pmd_fault(struct vm_fault *vmf, unsigned long *pfnp,
1972 			       const struct iomap_ops *ops)
1973 {
1974 	struct address_space *mapping = vmf->vma->vm_file->f_mapping;
1975 	XA_STATE_ORDER(xas, &mapping->i_pages, vmf->pgoff, PMD_ORDER);
1976 	struct iomap_iter iter = {
1977 		.inode		= mapping->host,
1978 		.len		= PMD_SIZE,
1979 		.flags		= IOMAP_DAX | IOMAP_FAULT,
1980 	};
1981 	vm_fault_t ret = VM_FAULT_FALLBACK;
1982 	pgoff_t max_pgoff;
1983 	void *entry;
1984 
1985 	if (vmf->flags & FAULT_FLAG_WRITE)
1986 		iter.flags |= IOMAP_WRITE;
1987 
1988 	/*
1989 	 * Check whether offset isn't beyond end of file now. Caller is
1990 	 * supposed to hold locks serializing us with truncate / punch hole so
1991 	 * this is a reliable test.
1992 	 */
1993 	max_pgoff = DIV_ROUND_UP(i_size_read(iter.inode), PAGE_SIZE);
1994 
1995 	trace_dax_pmd_fault(iter.inode, vmf, max_pgoff, 0);
1996 
1997 	if (xas.xa_index >= max_pgoff) {
1998 		ret = VM_FAULT_SIGBUS;
1999 		goto out;
2000 	}
2001 
2002 	if (dax_fault_check_fallback(vmf, &xas, max_pgoff))
2003 		goto fallback;
2004 
2005 	/*
2006 	 * grab_mapping_entry() will make sure we get an empty PMD entry,
2007 	 * a zero PMD entry or a DAX PMD.  If it can't (because a PTE
2008 	 * entry is already in the array, for instance), it will return
2009 	 * VM_FAULT_FALLBACK.
2010 	 */
2011 	entry = grab_mapping_entry(&xas, mapping, PMD_ORDER);
2012 	if (xa_is_internal(entry)) {
2013 		ret = xa_to_internal(entry);
2014 		goto fallback;
2015 	}
2016 
2017 	/*
2018 	 * It is possible, particularly with mixed reads & writes to private
2019 	 * mappings, that we have raced with a PTE fault that overlaps with
2020 	 * the PMD we need to set up.  If so just return and the fault will be
2021 	 * retried.
2022 	 */
2023 	if (!pmd_none(*vmf->pmd) && !pmd_trans_huge(*vmf->pmd)) {
2024 		ret = 0;
2025 		goto unlock_entry;
2026 	}
2027 
2028 	iter.pos = (loff_t)xas.xa_index << PAGE_SHIFT;
2029 	while (iomap_iter(&iter, ops) > 0) {
2030 		if (iomap_length(&iter) < PMD_SIZE)
2031 			continue; /* actually breaks out of the loop */
2032 
2033 		ret = dax_fault_iter(vmf, &iter, pfnp, &xas, &entry, true);
2034 		if (ret != VM_FAULT_FALLBACK)
2035 			iter.status = iomap_iter_advance(&iter, PMD_SIZE);
2036 	}
2037 
2038 unlock_entry:
2039 	dax_unlock_entry(&xas, entry);
2040 fallback:
2041 	if (ret == VM_FAULT_FALLBACK) {
2042 		split_huge_pmd(vmf->vma, vmf->pmd, vmf->address);
2043 		count_vm_event(THP_FAULT_FALLBACK);
2044 	}
2045 out:
2046 	trace_dax_pmd_fault_done(iter.inode, vmf, max_pgoff, ret);
2047 	return ret;
2048 }
2049 #else
2050 static vm_fault_t dax_iomap_pmd_fault(struct vm_fault *vmf, unsigned long *pfnp,
2051 			       const struct iomap_ops *ops)
2052 {
2053 	return VM_FAULT_FALLBACK;
2054 }
2055 #endif /* CONFIG_FS_DAX_PMD */
2056 
2057 /**
2058  * dax_iomap_fault - handle a page fault on a DAX file
2059  * @vmf: The description of the fault
2060  * @order: Order of the page to fault in
2061  * @pfnp: PFN to insert for synchronous faults if fsync is required
2062  * @iomap_errp: Storage for detailed error code in case of error
2063  * @ops: Iomap ops passed from the file system
2064  *
2065  * When a page fault occurs, filesystems may call this helper in
2066  * their fault handler for DAX files. dax_iomap_fault() assumes the caller
2067  * has done all the necessary locking for page fault to proceed
2068  * successfully.
2069  */
2070 vm_fault_t dax_iomap_fault(struct vm_fault *vmf, unsigned int order,
2071 			unsigned long *pfnp, int *iomap_errp,
2072 			const struct iomap_ops *ops)
2073 {
2074 	if (order == 0)
2075 		return dax_iomap_pte_fault(vmf, pfnp, iomap_errp, ops);
2076 	else if (order == PMD_ORDER)
2077 		return dax_iomap_pmd_fault(vmf, pfnp, ops);
2078 	else
2079 		return VM_FAULT_FALLBACK;
2080 }
2081 EXPORT_SYMBOL_GPL(dax_iomap_fault);
2082 
2083 /*
2084  * dax_insert_pfn_mkwrite - insert PTE or PMD entry into page tables
2085  * @vmf: The description of the fault
2086  * @pfn: PFN to insert
2087  * @order: Order of entry to insert.
2088  *
2089  * This function inserts a writeable PTE or PMD entry into the page tables
2090  * for an mmaped DAX file.  It also marks the page cache entry as dirty.
2091  */
2092 static vm_fault_t dax_insert_pfn_mkwrite(struct vm_fault *vmf,
2093 					unsigned long pfn, unsigned int order)
2094 {
2095 	struct address_space *mapping = vmf->vma->vm_file->f_mapping;
2096 	XA_STATE_ORDER(xas, &mapping->i_pages, vmf->pgoff, order);
2097 	struct folio *folio;
2098 	void *entry;
2099 	vm_fault_t ret;
2100 
2101 	xas_lock_irq(&xas);
2102 	entry = get_next_unlocked_entry(&xas, order);
2103 	/* Did we race with someone splitting entry or so? */
2104 	if (!entry || dax_is_conflict(entry) ||
2105 	    (order == 0 && !dax_is_pte_entry(entry))) {
2106 		put_unlocked_entry(&xas, entry, WAKE_NEXT);
2107 		xas_unlock_irq(&xas);
2108 		trace_dax_insert_pfn_mkwrite_no_entry(mapping->host, vmf,
2109 						      VM_FAULT_NOPAGE);
2110 		return VM_FAULT_NOPAGE;
2111 	}
2112 	xas_set_mark(&xas, PAGECACHE_TAG_DIRTY);
2113 	dax_lock_entry(&xas, entry);
2114 	xas_unlock_irq(&xas);
2115 	folio = pfn_folio(pfn);
2116 	folio_ref_inc(folio);
2117 	if (order == 0)
2118 		ret = vmf_insert_page_mkwrite(vmf, &folio->page, true);
2119 #ifdef CONFIG_FS_DAX_PMD
2120 	else if (order == PMD_ORDER)
2121 		ret = vmf_insert_folio_pmd(vmf, folio, FAULT_FLAG_WRITE);
2122 #endif
2123 	else
2124 		ret = VM_FAULT_FALLBACK;
2125 	folio_put(folio);
2126 	dax_unlock_entry(&xas, entry);
2127 	trace_dax_insert_pfn_mkwrite(mapping->host, vmf, ret);
2128 	return ret;
2129 }
2130 
2131 /**
2132  * dax_finish_sync_fault - finish synchronous page fault
2133  * @vmf: The description of the fault
2134  * @order: Order of entry to be inserted
2135  * @pfn: PFN to insert
2136  *
2137  * This function ensures that the file range touched by the page fault is
2138  * stored persistently on the media and handles inserting of appropriate page
2139  * table entry.
2140  */
2141 vm_fault_t dax_finish_sync_fault(struct vm_fault *vmf, unsigned int order,
2142 		unsigned long pfn)
2143 {
2144 	int err;
2145 	loff_t start = ((loff_t)vmf->pgoff) << PAGE_SHIFT;
2146 	size_t len = PAGE_SIZE << order;
2147 
2148 	err = vfs_fsync_range(vmf->vma->vm_file, start, start + len - 1, 1);
2149 	if (err)
2150 		return VM_FAULT_SIGBUS;
2151 	return dax_insert_pfn_mkwrite(vmf, pfn, order);
2152 }
2153 EXPORT_SYMBOL_GPL(dax_finish_sync_fault);
2154 
2155 static int dax_range_compare_iter(struct iomap_iter *it_src,
2156 		struct iomap_iter *it_dest, u64 len, bool *same)
2157 {
2158 	const struct iomap *smap = &it_src->iomap;
2159 	const struct iomap *dmap = &it_dest->iomap;
2160 	loff_t pos1 = it_src->pos, pos2 = it_dest->pos;
2161 	void *saddr, *daddr;
2162 	int id, ret;
2163 
2164 	len = min(len, min(smap->length, dmap->length));
2165 
2166 	if (smap->type == IOMAP_HOLE && dmap->type == IOMAP_HOLE) {
2167 		*same = true;
2168 		goto advance;
2169 	}
2170 
2171 	if (smap->type == IOMAP_HOLE || dmap->type == IOMAP_HOLE) {
2172 		*same = false;
2173 		return 0;
2174 	}
2175 
2176 	id = dax_read_lock();
2177 	ret = dax_iomap_direct_access(smap, pos1, ALIGN(pos1 + len, PAGE_SIZE),
2178 				      &saddr, NULL);
2179 	if (ret < 0)
2180 		goto out_unlock;
2181 
2182 	ret = dax_iomap_direct_access(dmap, pos2, ALIGN(pos2 + len, PAGE_SIZE),
2183 				      &daddr, NULL);
2184 	if (ret < 0)
2185 		goto out_unlock;
2186 
2187 	*same = !memcmp(saddr, daddr, len);
2188 	if (!*same)
2189 		len = 0;
2190 	dax_read_unlock(id);
2191 
2192 advance:
2193 	ret = iomap_iter_advance(it_src, len);
2194 	if (!ret)
2195 		ret = iomap_iter_advance(it_dest, len);
2196 	return ret;
2197 
2198 out_unlock:
2199 	dax_read_unlock(id);
2200 	return -EIO;
2201 }
2202 
2203 int dax_dedupe_file_range_compare(struct inode *src, loff_t srcoff,
2204 		struct inode *dst, loff_t dstoff, loff_t len, bool *same,
2205 		const struct iomap_ops *ops)
2206 {
2207 	struct iomap_iter src_iter = {
2208 		.inode		= src,
2209 		.pos		= srcoff,
2210 		.len		= len,
2211 		.flags		= IOMAP_DAX,
2212 	};
2213 	struct iomap_iter dst_iter = {
2214 		.inode		= dst,
2215 		.pos		= dstoff,
2216 		.len		= len,
2217 		.flags		= IOMAP_DAX,
2218 	};
2219 	int ret, status;
2220 
2221 	while ((ret = iomap_iter(&src_iter, ops)) > 0 &&
2222 	       (ret = iomap_iter(&dst_iter, ops)) > 0) {
2223 		status = dax_range_compare_iter(&src_iter, &dst_iter,
2224 				min(src_iter.len, dst_iter.len), same);
2225 		if (status < 0)
2226 			return ret;
2227 		src_iter.status = dst_iter.status = status;
2228 	}
2229 	return ret;
2230 }
2231 
2232 int dax_remap_file_range_prep(struct file *file_in, loff_t pos_in,
2233 			      struct file *file_out, loff_t pos_out,
2234 			      loff_t *len, unsigned int remap_flags,
2235 			      const struct iomap_ops *ops)
2236 {
2237 	return __generic_remap_file_range_prep(file_in, pos_in, file_out,
2238 					       pos_out, len, remap_flags, ops);
2239 }
2240 EXPORT_SYMBOL_GPL(dax_remap_file_range_prep);
2241