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