GNU Linux-libre 6.8.9-gnu
[releases.git] / fs / ubifs / file.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * This file is part of UBIFS.
4  *
5  * Copyright (C) 2006-2008 Nokia Corporation.
6  *
7  * Authors: Artem Bityutskiy (Битюцкий Артём)
8  *          Adrian Hunter
9  */
10
11 /*
12  * This file implements VFS file and inode operations for regular files, device
13  * nodes and symlinks as well as address space operations.
14  *
15  * UBIFS uses 2 page flags: @PG_private and @PG_checked. @PG_private is set if
16  * the page is dirty and is used for optimization purposes - dirty pages are
17  * not budgeted so the flag shows that 'ubifs_write_end()' should not release
18  * the budget for this page. The @PG_checked flag is set if full budgeting is
19  * required for the page e.g., when it corresponds to a file hole or it is
20  * beyond the file size. The budgeting is done in 'ubifs_write_begin()', because
21  * it is OK to fail in this function, and the budget is released in
22  * 'ubifs_write_end()'. So the @PG_private and @PG_checked flags carry
23  * information about how the page was budgeted, to make it possible to release
24  * the budget properly.
25  *
26  * A thing to keep in mind: inode @i_mutex is locked in most VFS operations we
27  * implement. However, this is not true for 'ubifs_writepage()', which may be
28  * called with @i_mutex unlocked. For example, when flusher thread is doing
29  * background write-back, it calls 'ubifs_writepage()' with unlocked @i_mutex.
30  * At "normal" work-paths the @i_mutex is locked in 'ubifs_writepage()', e.g.
31  * in the "sys_write -> alloc_pages -> direct reclaim path". So, in
32  * 'ubifs_writepage()' we are only guaranteed that the page is locked.
33  *
34  * Similarly, @i_mutex is not always locked in 'ubifs_read_folio()', e.g., the
35  * read-ahead path does not lock it ("sys_read -> generic_file_aio_read ->
36  * ondemand_readahead -> read_folio"). In case of readahead, @I_SYNC flag is not
37  * set as well. However, UBIFS disables readahead.
38  */
39
40 #include "ubifs.h"
41 #include <linux/mount.h>
42 #include <linux/slab.h>
43 #include <linux/migrate.h>
44
45 static int read_block(struct inode *inode, void *addr, unsigned int block,
46                       struct ubifs_data_node *dn)
47 {
48         struct ubifs_info *c = inode->i_sb->s_fs_info;
49         int err, len, out_len;
50         union ubifs_key key;
51         unsigned int dlen;
52
53         data_key_init(c, &key, inode->i_ino, block);
54         err = ubifs_tnc_lookup(c, &key, dn);
55         if (err) {
56                 if (err == -ENOENT)
57                         /* Not found, so it must be a hole */
58                         memset(addr, 0, UBIFS_BLOCK_SIZE);
59                 return err;
60         }
61
62         ubifs_assert(c, le64_to_cpu(dn->ch.sqnum) >
63                      ubifs_inode(inode)->creat_sqnum);
64         len = le32_to_cpu(dn->size);
65         if (len <= 0 || len > UBIFS_BLOCK_SIZE)
66                 goto dump;
67
68         dlen = le32_to_cpu(dn->ch.len) - UBIFS_DATA_NODE_SZ;
69
70         if (IS_ENCRYPTED(inode)) {
71                 err = ubifs_decrypt(inode, dn, &dlen, block);
72                 if (err)
73                         goto dump;
74         }
75
76         out_len = UBIFS_BLOCK_SIZE;
77         err = ubifs_decompress(c, &dn->data, dlen, addr, &out_len,
78                                le16_to_cpu(dn->compr_type));
79         if (err || len != out_len)
80                 goto dump;
81
82         /*
83          * Data length can be less than a full block, even for blocks that are
84          * not the last in the file (e.g., as a result of making a hole and
85          * appending data). Ensure that the remainder is zeroed out.
86          */
87         if (len < UBIFS_BLOCK_SIZE)
88                 memset(addr + len, 0, UBIFS_BLOCK_SIZE - len);
89
90         return 0;
91
92 dump:
93         ubifs_err(c, "bad data node (block %u, inode %lu)",
94                   block, inode->i_ino);
95         ubifs_dump_node(c, dn, UBIFS_MAX_DATA_NODE_SZ);
96         return -EINVAL;
97 }
98
99 static int do_readpage(struct page *page)
100 {
101         void *addr;
102         int err = 0, i;
103         unsigned int block, beyond;
104         struct ubifs_data_node *dn;
105         struct inode *inode = page->mapping->host;
106         struct ubifs_info *c = inode->i_sb->s_fs_info;
107         loff_t i_size = i_size_read(inode);
108
109         dbg_gen("ino %lu, pg %lu, i_size %lld, flags %#lx",
110                 inode->i_ino, page->index, i_size, page->flags);
111         ubifs_assert(c, !PageChecked(page));
112         ubifs_assert(c, !PagePrivate(page));
113
114         addr = kmap(page);
115
116         block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
117         beyond = (i_size + UBIFS_BLOCK_SIZE - 1) >> UBIFS_BLOCK_SHIFT;
118         if (block >= beyond) {
119                 /* Reading beyond inode */
120                 SetPageChecked(page);
121                 memset(addr, 0, PAGE_SIZE);
122                 goto out;
123         }
124
125         dn = kmalloc(UBIFS_MAX_DATA_NODE_SZ, GFP_NOFS);
126         if (!dn) {
127                 err = -ENOMEM;
128                 goto error;
129         }
130
131         i = 0;
132         while (1) {
133                 int ret;
134
135                 if (block >= beyond) {
136                         /* Reading beyond inode */
137                         err = -ENOENT;
138                         memset(addr, 0, UBIFS_BLOCK_SIZE);
139                 } else {
140                         ret = read_block(inode, addr, block, dn);
141                         if (ret) {
142                                 err = ret;
143                                 if (err != -ENOENT)
144                                         break;
145                         } else if (block + 1 == beyond) {
146                                 int dlen = le32_to_cpu(dn->size);
147                                 int ilen = i_size & (UBIFS_BLOCK_SIZE - 1);
148
149                                 if (ilen && ilen < dlen)
150                                         memset(addr + ilen, 0, dlen - ilen);
151                         }
152                 }
153                 if (++i >= UBIFS_BLOCKS_PER_PAGE)
154                         break;
155                 block += 1;
156                 addr += UBIFS_BLOCK_SIZE;
157         }
158         if (err) {
159                 struct ubifs_info *c = inode->i_sb->s_fs_info;
160                 if (err == -ENOENT) {
161                         /* Not found, so it must be a hole */
162                         SetPageChecked(page);
163                         dbg_gen("hole");
164                         goto out_free;
165                 }
166                 ubifs_err(c, "cannot read page %lu of inode %lu, error %d",
167                           page->index, inode->i_ino, err);
168                 goto error;
169         }
170
171 out_free:
172         kfree(dn);
173 out:
174         SetPageUptodate(page);
175         ClearPageError(page);
176         flush_dcache_page(page);
177         kunmap(page);
178         return 0;
179
180 error:
181         kfree(dn);
182         ClearPageUptodate(page);
183         SetPageError(page);
184         flush_dcache_page(page);
185         kunmap(page);
186         return err;
187 }
188
189 /**
190  * release_new_page_budget - release budget of a new page.
191  * @c: UBIFS file-system description object
192  *
193  * This is a helper function which releases budget corresponding to the budget
194  * of one new page of data.
195  */
196 static void release_new_page_budget(struct ubifs_info *c)
197 {
198         struct ubifs_budget_req req = { .recalculate = 1, .new_page = 1 };
199
200         ubifs_release_budget(c, &req);
201 }
202
203 /**
204  * release_existing_page_budget - release budget of an existing page.
205  * @c: UBIFS file-system description object
206  *
207  * This is a helper function which releases budget corresponding to the budget
208  * of changing one page of data which already exists on the flash media.
209  */
210 static void release_existing_page_budget(struct ubifs_info *c)
211 {
212         struct ubifs_budget_req req = { .dd_growth = c->bi.page_budget};
213
214         ubifs_release_budget(c, &req);
215 }
216
217 static int write_begin_slow(struct address_space *mapping,
218                             loff_t pos, unsigned len, struct page **pagep)
219 {
220         struct inode *inode = mapping->host;
221         struct ubifs_info *c = inode->i_sb->s_fs_info;
222         pgoff_t index = pos >> PAGE_SHIFT;
223         struct ubifs_budget_req req = { .new_page = 1 };
224         int err, appending = !!(pos + len > inode->i_size);
225         struct page *page;
226
227         dbg_gen("ino %lu, pos %llu, len %u, i_size %lld",
228                 inode->i_ino, pos, len, inode->i_size);
229
230         /*
231          * At the slow path we have to budget before locking the page, because
232          * budgeting may force write-back, which would wait on locked pages and
233          * deadlock if we had the page locked. At this point we do not know
234          * anything about the page, so assume that this is a new page which is
235          * written to a hole. This corresponds to largest budget. Later the
236          * budget will be amended if this is not true.
237          */
238         if (appending)
239                 /* We are appending data, budget for inode change */
240                 req.dirtied_ino = 1;
241
242         err = ubifs_budget_space(c, &req);
243         if (unlikely(err))
244                 return err;
245
246         page = grab_cache_page_write_begin(mapping, index);
247         if (unlikely(!page)) {
248                 ubifs_release_budget(c, &req);
249                 return -ENOMEM;
250         }
251
252         if (!PageUptodate(page)) {
253                 if (!(pos & ~PAGE_MASK) && len == PAGE_SIZE)
254                         SetPageChecked(page);
255                 else {
256                         err = do_readpage(page);
257                         if (err) {
258                                 unlock_page(page);
259                                 put_page(page);
260                                 ubifs_release_budget(c, &req);
261                                 return err;
262                         }
263                 }
264         }
265
266         if (PagePrivate(page))
267                 /*
268                  * The page is dirty, which means it was budgeted twice:
269                  *   o first time the budget was allocated by the task which
270                  *     made the page dirty and set the PG_private flag;
271                  *   o and then we budgeted for it for the second time at the
272                  *     very beginning of this function.
273                  *
274                  * So what we have to do is to release the page budget we
275                  * allocated.
276                  */
277                 release_new_page_budget(c);
278         else if (!PageChecked(page))
279                 /*
280                  * We are changing a page which already exists on the media.
281                  * This means that changing the page does not make the amount
282                  * of indexing information larger, and this part of the budget
283                  * which we have already acquired may be released.
284                  */
285                 ubifs_convert_page_budget(c);
286
287         if (appending) {
288                 struct ubifs_inode *ui = ubifs_inode(inode);
289
290                 /*
291                  * 'ubifs_write_end()' is optimized from the fast-path part of
292                  * 'ubifs_write_begin()' and expects the @ui_mutex to be locked
293                  * if data is appended.
294                  */
295                 mutex_lock(&ui->ui_mutex);
296                 if (ui->dirty)
297                         /*
298                          * The inode is dirty already, so we may free the
299                          * budget we allocated.
300                          */
301                         ubifs_release_dirty_inode_budget(c, ui);
302         }
303
304         *pagep = page;
305         return 0;
306 }
307
308 /**
309  * allocate_budget - allocate budget for 'ubifs_write_begin()'.
310  * @c: UBIFS file-system description object
311  * @page: page to allocate budget for
312  * @ui: UBIFS inode object the page belongs to
313  * @appending: non-zero if the page is appended
314  *
315  * This is a helper function for 'ubifs_write_begin()' which allocates budget
316  * for the operation. The budget is allocated differently depending on whether
317  * this is appending, whether the page is dirty or not, and so on. This
318  * function leaves the @ui->ui_mutex locked in case of appending.
319  *
320  * Returns: %0 in case of success and %-ENOSPC in case of failure.
321  */
322 static int allocate_budget(struct ubifs_info *c, struct page *page,
323                            struct ubifs_inode *ui, int appending)
324 {
325         struct ubifs_budget_req req = { .fast = 1 };
326
327         if (PagePrivate(page)) {
328                 if (!appending)
329                         /*
330                          * The page is dirty and we are not appending, which
331                          * means no budget is needed at all.
332                          */
333                         return 0;
334
335                 mutex_lock(&ui->ui_mutex);
336                 if (ui->dirty)
337                         /*
338                          * The page is dirty and we are appending, so the inode
339                          * has to be marked as dirty. However, it is already
340                          * dirty, so we do not need any budget. We may return,
341                          * but @ui->ui_mutex hast to be left locked because we
342                          * should prevent write-back from flushing the inode
343                          * and freeing the budget. The lock will be released in
344                          * 'ubifs_write_end()'.
345                          */
346                         return 0;
347
348                 /*
349                  * The page is dirty, we are appending, the inode is clean, so
350                  * we need to budget the inode change.
351                  */
352                 req.dirtied_ino = 1;
353         } else {
354                 if (PageChecked(page))
355                         /*
356                          * The page corresponds to a hole and does not
357                          * exist on the media. So changing it makes
358                          * make the amount of indexing information
359                          * larger, and we have to budget for a new
360                          * page.
361                          */
362                         req.new_page = 1;
363                 else
364                         /*
365                          * Not a hole, the change will not add any new
366                          * indexing information, budget for page
367                          * change.
368                          */
369                         req.dirtied_page = 1;
370
371                 if (appending) {
372                         mutex_lock(&ui->ui_mutex);
373                         if (!ui->dirty)
374                                 /*
375                                  * The inode is clean but we will have to mark
376                                  * it as dirty because we are appending. This
377                                  * needs a budget.
378                                  */
379                                 req.dirtied_ino = 1;
380                 }
381         }
382
383         return ubifs_budget_space(c, &req);
384 }
385
386 /*
387  * This function is called when a page of data is going to be written. Since
388  * the page of data will not necessarily go to the flash straight away, UBIFS
389  * has to reserve space on the media for it, which is done by means of
390  * budgeting.
391  *
392  * This is the hot-path of the file-system and we are trying to optimize it as
393  * much as possible. For this reasons it is split on 2 parts - slow and fast.
394  *
395  * There many budgeting cases:
396  *     o a new page is appended - we have to budget for a new page and for
397  *       changing the inode; however, if the inode is already dirty, there is
398  *       no need to budget for it;
399  *     o an existing clean page is changed - we have budget for it; if the page
400  *       does not exist on the media (a hole), we have to budget for a new
401  *       page; otherwise, we may budget for changing an existing page; the
402  *       difference between these cases is that changing an existing page does
403  *       not introduce anything new to the FS indexing information, so it does
404  *       not grow, and smaller budget is acquired in this case;
405  *     o an existing dirty page is changed - no need to budget at all, because
406  *       the page budget has been acquired by earlier, when the page has been
407  *       marked dirty.
408  *
409  * UBIFS budgeting sub-system may force write-back if it thinks there is no
410  * space to reserve. This imposes some locking restrictions and makes it
411  * impossible to take into account the above cases, and makes it impossible to
412  * optimize budgeting.
413  *
414  * The solution for this is that the fast path of 'ubifs_write_begin()' assumes
415  * there is a plenty of flash space and the budget will be acquired quickly,
416  * without forcing write-back. The slow path does not make this assumption.
417  */
418 static int ubifs_write_begin(struct file *file, struct address_space *mapping,
419                              loff_t pos, unsigned len,
420                              struct page **pagep, void **fsdata)
421 {
422         struct inode *inode = mapping->host;
423         struct ubifs_info *c = inode->i_sb->s_fs_info;
424         struct ubifs_inode *ui = ubifs_inode(inode);
425         pgoff_t index = pos >> PAGE_SHIFT;
426         int err, appending = !!(pos + len > inode->i_size);
427         int skipped_read = 0;
428         struct page *page;
429
430         ubifs_assert(c, ubifs_inode(inode)->ui_size == inode->i_size);
431         ubifs_assert(c, !c->ro_media && !c->ro_mount);
432
433         if (unlikely(c->ro_error))
434                 return -EROFS;
435
436         /* Try out the fast-path part first */
437         page = grab_cache_page_write_begin(mapping, index);
438         if (unlikely(!page))
439                 return -ENOMEM;
440
441         if (!PageUptodate(page)) {
442                 /* The page is not loaded from the flash */
443                 if (!(pos & ~PAGE_MASK) && len == PAGE_SIZE) {
444                         /*
445                          * We change whole page so no need to load it. But we
446                          * do not know whether this page exists on the media or
447                          * not, so we assume the latter because it requires
448                          * larger budget. The assumption is that it is better
449                          * to budget a bit more than to read the page from the
450                          * media. Thus, we are setting the @PG_checked flag
451                          * here.
452                          */
453                         SetPageChecked(page);
454                         skipped_read = 1;
455                 } else {
456                         err = do_readpage(page);
457                         if (err) {
458                                 unlock_page(page);
459                                 put_page(page);
460                                 return err;
461                         }
462                 }
463         }
464
465         err = allocate_budget(c, page, ui, appending);
466         if (unlikely(err)) {
467                 ubifs_assert(c, err == -ENOSPC);
468                 /*
469                  * If we skipped reading the page because we were going to
470                  * write all of it, then it is not up to date.
471                  */
472                 if (skipped_read)
473                         ClearPageChecked(page);
474                 /*
475                  * Budgeting failed which means it would have to force
476                  * write-back but didn't, because we set the @fast flag in the
477                  * request. Write-back cannot be done now, while we have the
478                  * page locked, because it would deadlock. Unlock and free
479                  * everything and fall-back to slow-path.
480                  */
481                 if (appending) {
482                         ubifs_assert(c, mutex_is_locked(&ui->ui_mutex));
483                         mutex_unlock(&ui->ui_mutex);
484                 }
485                 unlock_page(page);
486                 put_page(page);
487
488                 return write_begin_slow(mapping, pos, len, pagep);
489         }
490
491         /*
492          * Whee, we acquired budgeting quickly - without involving
493          * garbage-collection, committing or forcing write-back. We return
494          * with @ui->ui_mutex locked if we are appending pages, and unlocked
495          * otherwise. This is an optimization (slightly hacky though).
496          */
497         *pagep = page;
498         return 0;
499
500 }
501
502 /**
503  * cancel_budget - cancel budget.
504  * @c: UBIFS file-system description object
505  * @page: page to cancel budget for
506  * @ui: UBIFS inode object the page belongs to
507  * @appending: non-zero if the page is appended
508  *
509  * This is a helper function for a page write operation. It unlocks the
510  * @ui->ui_mutex in case of appending.
511  */
512 static void cancel_budget(struct ubifs_info *c, struct page *page,
513                           struct ubifs_inode *ui, int appending)
514 {
515         if (appending) {
516                 if (!ui->dirty)
517                         ubifs_release_dirty_inode_budget(c, ui);
518                 mutex_unlock(&ui->ui_mutex);
519         }
520         if (!PagePrivate(page)) {
521                 if (PageChecked(page))
522                         release_new_page_budget(c);
523                 else
524                         release_existing_page_budget(c);
525         }
526 }
527
528 static int ubifs_write_end(struct file *file, struct address_space *mapping,
529                            loff_t pos, unsigned len, unsigned copied,
530                            struct page *page, void *fsdata)
531 {
532         struct inode *inode = mapping->host;
533         struct ubifs_inode *ui = ubifs_inode(inode);
534         struct ubifs_info *c = inode->i_sb->s_fs_info;
535         loff_t end_pos = pos + len;
536         int appending = !!(end_pos > inode->i_size);
537
538         dbg_gen("ino %lu, pos %llu, pg %lu, len %u, copied %d, i_size %lld",
539                 inode->i_ino, pos, page->index, len, copied, inode->i_size);
540
541         if (unlikely(copied < len && len == PAGE_SIZE)) {
542                 /*
543                  * VFS copied less data to the page that it intended and
544                  * declared in its '->write_begin()' call via the @len
545                  * argument. If the page was not up-to-date, and @len was
546                  * @PAGE_SIZE, the 'ubifs_write_begin()' function did
547                  * not load it from the media (for optimization reasons). This
548                  * means that part of the page contains garbage. So read the
549                  * page now.
550                  */
551                 dbg_gen("copied %d instead of %d, read page and repeat",
552                         copied, len);
553                 cancel_budget(c, page, ui, appending);
554                 ClearPageChecked(page);
555
556                 /*
557                  * Return 0 to force VFS to repeat the whole operation, or the
558                  * error code if 'do_readpage()' fails.
559                  */
560                 copied = do_readpage(page);
561                 goto out;
562         }
563
564         if (len == PAGE_SIZE)
565                 SetPageUptodate(page);
566
567         if (!PagePrivate(page)) {
568                 attach_page_private(page, (void *)1);
569                 atomic_long_inc(&c->dirty_pg_cnt);
570                 __set_page_dirty_nobuffers(page);
571         }
572
573         if (appending) {
574                 i_size_write(inode, end_pos);
575                 ui->ui_size = end_pos;
576                 /*
577                  * Note, we do not set @I_DIRTY_PAGES (which means that the
578                  * inode has dirty pages), this has been done in
579                  * '__set_page_dirty_nobuffers()'.
580                  */
581                 __mark_inode_dirty(inode, I_DIRTY_DATASYNC);
582                 ubifs_assert(c, mutex_is_locked(&ui->ui_mutex));
583                 mutex_unlock(&ui->ui_mutex);
584         }
585
586 out:
587         unlock_page(page);
588         put_page(page);
589         return copied;
590 }
591
592 /**
593  * populate_page - copy data nodes into a page for bulk-read.
594  * @c: UBIFS file-system description object
595  * @page: page
596  * @bu: bulk-read information
597  * @n: next zbranch slot
598  *
599  * Returns: %0 on success and a negative error code on failure.
600  */
601 static int populate_page(struct ubifs_info *c, struct page *page,
602                          struct bu_info *bu, int *n)
603 {
604         int i = 0, nn = *n, offs = bu->zbranch[0].offs, hole = 0, read = 0;
605         struct inode *inode = page->mapping->host;
606         loff_t i_size = i_size_read(inode);
607         unsigned int page_block;
608         void *addr, *zaddr;
609         pgoff_t end_index;
610
611         dbg_gen("ino %lu, pg %lu, i_size %lld, flags %#lx",
612                 inode->i_ino, page->index, i_size, page->flags);
613
614         addr = zaddr = kmap(page);
615
616         end_index = (i_size - 1) >> PAGE_SHIFT;
617         if (!i_size || page->index > end_index) {
618                 hole = 1;
619                 memset(addr, 0, PAGE_SIZE);
620                 goto out_hole;
621         }
622
623         page_block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
624         while (1) {
625                 int err, len, out_len, dlen;
626
627                 if (nn >= bu->cnt) {
628                         hole = 1;
629                         memset(addr, 0, UBIFS_BLOCK_SIZE);
630                 } else if (key_block(c, &bu->zbranch[nn].key) == page_block) {
631                         struct ubifs_data_node *dn;
632
633                         dn = bu->buf + (bu->zbranch[nn].offs - offs);
634
635                         ubifs_assert(c, le64_to_cpu(dn->ch.sqnum) >
636                                      ubifs_inode(inode)->creat_sqnum);
637
638                         len = le32_to_cpu(dn->size);
639                         if (len <= 0 || len > UBIFS_BLOCK_SIZE)
640                                 goto out_err;
641
642                         dlen = le32_to_cpu(dn->ch.len) - UBIFS_DATA_NODE_SZ;
643                         out_len = UBIFS_BLOCK_SIZE;
644
645                         if (IS_ENCRYPTED(inode)) {
646                                 err = ubifs_decrypt(inode, dn, &dlen, page_block);
647                                 if (err)
648                                         goto out_err;
649                         }
650
651                         err = ubifs_decompress(c, &dn->data, dlen, addr, &out_len,
652                                                le16_to_cpu(dn->compr_type));
653                         if (err || len != out_len)
654                                 goto out_err;
655
656                         if (len < UBIFS_BLOCK_SIZE)
657                                 memset(addr + len, 0, UBIFS_BLOCK_SIZE - len);
658
659                         nn += 1;
660                         read = (i << UBIFS_BLOCK_SHIFT) + len;
661                 } else if (key_block(c, &bu->zbranch[nn].key) < page_block) {
662                         nn += 1;
663                         continue;
664                 } else {
665                         hole = 1;
666                         memset(addr, 0, UBIFS_BLOCK_SIZE);
667                 }
668                 if (++i >= UBIFS_BLOCKS_PER_PAGE)
669                         break;
670                 addr += UBIFS_BLOCK_SIZE;
671                 page_block += 1;
672         }
673
674         if (end_index == page->index) {
675                 int len = i_size & (PAGE_SIZE - 1);
676
677                 if (len && len < read)
678                         memset(zaddr + len, 0, read - len);
679         }
680
681 out_hole:
682         if (hole) {
683                 SetPageChecked(page);
684                 dbg_gen("hole");
685         }
686
687         SetPageUptodate(page);
688         ClearPageError(page);
689         flush_dcache_page(page);
690         kunmap(page);
691         *n = nn;
692         return 0;
693
694 out_err:
695         ClearPageUptodate(page);
696         SetPageError(page);
697         flush_dcache_page(page);
698         kunmap(page);
699         ubifs_err(c, "bad data node (block %u, inode %lu)",
700                   page_block, inode->i_ino);
701         return -EINVAL;
702 }
703
704 /**
705  * ubifs_do_bulk_read - do bulk-read.
706  * @c: UBIFS file-system description object
707  * @bu: bulk-read information
708  * @page1: first page to read
709  *
710  * Returns: %1 if the bulk-read is done, otherwise %0 is returned.
711  */
712 static int ubifs_do_bulk_read(struct ubifs_info *c, struct bu_info *bu,
713                               struct page *page1)
714 {
715         pgoff_t offset = page1->index, end_index;
716         struct address_space *mapping = page1->mapping;
717         struct inode *inode = mapping->host;
718         struct ubifs_inode *ui = ubifs_inode(inode);
719         int err, page_idx, page_cnt, ret = 0, n = 0;
720         int allocate = bu->buf ? 0 : 1;
721         loff_t isize;
722         gfp_t ra_gfp_mask = readahead_gfp_mask(mapping) & ~__GFP_FS;
723
724         err = ubifs_tnc_get_bu_keys(c, bu);
725         if (err)
726                 goto out_warn;
727
728         if (bu->eof) {
729                 /* Turn off bulk-read at the end of the file */
730                 ui->read_in_a_row = 1;
731                 ui->bulk_read = 0;
732         }
733
734         page_cnt = bu->blk_cnt >> UBIFS_BLOCKS_PER_PAGE_SHIFT;
735         if (!page_cnt) {
736                 /*
737                  * This happens when there are multiple blocks per page and the
738                  * blocks for the first page we are looking for, are not
739                  * together. If all the pages were like this, bulk-read would
740                  * reduce performance, so we turn it off for a while.
741                  */
742                 goto out_bu_off;
743         }
744
745         if (bu->cnt) {
746                 if (allocate) {
747                         /*
748                          * Allocate bulk-read buffer depending on how many data
749                          * nodes we are going to read.
750                          */
751                         bu->buf_len = bu->zbranch[bu->cnt - 1].offs +
752                                       bu->zbranch[bu->cnt - 1].len -
753                                       bu->zbranch[0].offs;
754                         ubifs_assert(c, bu->buf_len > 0);
755                         ubifs_assert(c, bu->buf_len <= c->leb_size);
756                         bu->buf = kmalloc(bu->buf_len, GFP_NOFS | __GFP_NOWARN);
757                         if (!bu->buf)
758                                 goto out_bu_off;
759                 }
760
761                 err = ubifs_tnc_bulk_read(c, bu);
762                 if (err)
763                         goto out_warn;
764         }
765
766         err = populate_page(c, page1, bu, &n);
767         if (err)
768                 goto out_warn;
769
770         unlock_page(page1);
771         ret = 1;
772
773         isize = i_size_read(inode);
774         if (isize == 0)
775                 goto out_free;
776         end_index = ((isize - 1) >> PAGE_SHIFT);
777
778         for (page_idx = 1; page_idx < page_cnt; page_idx++) {
779                 pgoff_t page_offset = offset + page_idx;
780                 struct page *page;
781
782                 if (page_offset > end_index)
783                         break;
784                 page = pagecache_get_page(mapping, page_offset,
785                                  FGP_LOCK|FGP_ACCESSED|FGP_CREAT|FGP_NOWAIT,
786                                  ra_gfp_mask);
787                 if (!page)
788                         break;
789                 if (!PageUptodate(page))
790                         err = populate_page(c, page, bu, &n);
791                 unlock_page(page);
792                 put_page(page);
793                 if (err)
794                         break;
795         }
796
797         ui->last_page_read = offset + page_idx - 1;
798
799 out_free:
800         if (allocate)
801                 kfree(bu->buf);
802         return ret;
803
804 out_warn:
805         ubifs_warn(c, "ignoring error %d and skipping bulk-read", err);
806         goto out_free;
807
808 out_bu_off:
809         ui->read_in_a_row = ui->bulk_read = 0;
810         goto out_free;
811 }
812
813 /**
814  * ubifs_bulk_read - determine whether to bulk-read and, if so, do it.
815  * @page: page from which to start bulk-read.
816  *
817  * Some flash media are capable of reading sequentially at faster rates. UBIFS
818  * bulk-read facility is designed to take advantage of that, by reading in one
819  * go consecutive data nodes that are also located consecutively in the same
820  * LEB.
821  *
822  * Returns: %1 if a bulk-read is done and %0 otherwise.
823  */
824 static int ubifs_bulk_read(struct page *page)
825 {
826         struct inode *inode = page->mapping->host;
827         struct ubifs_info *c = inode->i_sb->s_fs_info;
828         struct ubifs_inode *ui = ubifs_inode(inode);
829         pgoff_t index = page->index, last_page_read = ui->last_page_read;
830         struct bu_info *bu;
831         int err = 0, allocated = 0;
832
833         ui->last_page_read = index;
834         if (!c->bulk_read)
835                 return 0;
836
837         /*
838          * Bulk-read is protected by @ui->ui_mutex, but it is an optimization,
839          * so don't bother if we cannot lock the mutex.
840          */
841         if (!mutex_trylock(&ui->ui_mutex))
842                 return 0;
843
844         if (index != last_page_read + 1) {
845                 /* Turn off bulk-read if we stop reading sequentially */
846                 ui->read_in_a_row = 1;
847                 if (ui->bulk_read)
848                         ui->bulk_read = 0;
849                 goto out_unlock;
850         }
851
852         if (!ui->bulk_read) {
853                 ui->read_in_a_row += 1;
854                 if (ui->read_in_a_row < 3)
855                         goto out_unlock;
856                 /* Three reads in a row, so switch on bulk-read */
857                 ui->bulk_read = 1;
858         }
859
860         /*
861          * If possible, try to use pre-allocated bulk-read information, which
862          * is protected by @c->bu_mutex.
863          */
864         if (mutex_trylock(&c->bu_mutex))
865                 bu = &c->bu;
866         else {
867                 bu = kmalloc(sizeof(struct bu_info), GFP_NOFS | __GFP_NOWARN);
868                 if (!bu)
869                         goto out_unlock;
870
871                 bu->buf = NULL;
872                 allocated = 1;
873         }
874
875         bu->buf_len = c->max_bu_buf_len;
876         data_key_init(c, &bu->key, inode->i_ino,
877                       page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT);
878         err = ubifs_do_bulk_read(c, bu, page);
879
880         if (!allocated)
881                 mutex_unlock(&c->bu_mutex);
882         else
883                 kfree(bu);
884
885 out_unlock:
886         mutex_unlock(&ui->ui_mutex);
887         return err;
888 }
889
890 static int ubifs_read_folio(struct file *file, struct folio *folio)
891 {
892         struct page *page = &folio->page;
893
894         if (ubifs_bulk_read(page))
895                 return 0;
896         do_readpage(page);
897         folio_unlock(folio);
898         return 0;
899 }
900
901 static int do_writepage(struct page *page, int len)
902 {
903         int err = 0, i, blen;
904         unsigned int block;
905         void *addr;
906         union ubifs_key key;
907         struct inode *inode = page->mapping->host;
908         struct ubifs_info *c = inode->i_sb->s_fs_info;
909
910 #ifdef UBIFS_DEBUG
911         struct ubifs_inode *ui = ubifs_inode(inode);
912         spin_lock(&ui->ui_lock);
913         ubifs_assert(c, page->index <= ui->synced_i_size >> PAGE_SHIFT);
914         spin_unlock(&ui->ui_lock);
915 #endif
916
917         /* Update radix tree tags */
918         set_page_writeback(page);
919
920         addr = kmap(page);
921         block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
922         i = 0;
923         while (len) {
924                 blen = min_t(int, len, UBIFS_BLOCK_SIZE);
925                 data_key_init(c, &key, inode->i_ino, block);
926                 err = ubifs_jnl_write_data(c, inode, &key, addr, blen);
927                 if (err)
928                         break;
929                 if (++i >= UBIFS_BLOCKS_PER_PAGE)
930                         break;
931                 block += 1;
932                 addr += blen;
933                 len -= blen;
934         }
935         if (err) {
936                 SetPageError(page);
937                 ubifs_err(c, "cannot write page %lu of inode %lu, error %d",
938                           page->index, inode->i_ino, err);
939                 ubifs_ro_mode(c, err);
940         }
941
942         ubifs_assert(c, PagePrivate(page));
943         if (PageChecked(page))
944                 release_new_page_budget(c);
945         else
946                 release_existing_page_budget(c);
947
948         atomic_long_dec(&c->dirty_pg_cnt);
949         detach_page_private(page);
950         ClearPageChecked(page);
951
952         kunmap(page);
953         unlock_page(page);
954         end_page_writeback(page);
955         return err;
956 }
957
958 /*
959  * When writing-back dirty inodes, VFS first writes-back pages belonging to the
960  * inode, then the inode itself. For UBIFS this may cause a problem. Consider a
961  * situation when a we have an inode with size 0, then a megabyte of data is
962  * appended to the inode, then write-back starts and flushes some amount of the
963  * dirty pages, the journal becomes full, commit happens and finishes, and then
964  * an unclean reboot happens. When the file system is mounted next time, the
965  * inode size would still be 0, but there would be many pages which are beyond
966  * the inode size, they would be indexed and consume flash space. Because the
967  * journal has been committed, the replay would not be able to detect this
968  * situation and correct the inode size. This means UBIFS would have to scan
969  * whole index and correct all inode sizes, which is long an unacceptable.
970  *
971  * To prevent situations like this, UBIFS writes pages back only if they are
972  * within the last synchronized inode size, i.e. the size which has been
973  * written to the flash media last time. Otherwise, UBIFS forces inode
974  * write-back, thus making sure the on-flash inode contains current inode size,
975  * and then keeps writing pages back.
976  *
977  * Some locking issues explanation. 'ubifs_writepage()' first is called with
978  * the page locked, and it locks @ui_mutex. However, write-back does take inode
979  * @i_mutex, which means other VFS operations may be run on this inode at the
980  * same time. And the problematic one is truncation to smaller size, from where
981  * we have to call 'truncate_setsize()', which first changes @inode->i_size,
982  * then drops the truncated pages. And while dropping the pages, it takes the
983  * page lock. This means that 'do_truncation()' cannot call 'truncate_setsize()'
984  * with @ui_mutex locked, because it would deadlock with 'ubifs_writepage()'.
985  * This means that @inode->i_size is changed while @ui_mutex is unlocked.
986  *
987  * XXX(truncate): with the new truncate sequence this is not true anymore,
988  * and the calls to truncate_setsize can be move around freely.  They should
989  * be moved to the very end of the truncate sequence.
990  *
991  * But in 'ubifs_writepage()' we have to guarantee that we do not write beyond
992  * inode size. How do we do this if @inode->i_size may became smaller while we
993  * are in the middle of 'ubifs_writepage()'? The UBIFS solution is the
994  * @ui->ui_isize "shadow" field which UBIFS uses instead of @inode->i_size
995  * internally and updates it under @ui_mutex.
996  *
997  * Q: why we do not worry that if we race with truncation, we may end up with a
998  * situation when the inode is truncated while we are in the middle of
999  * 'do_writepage()', so we do write beyond inode size?
1000  * A: If we are in the middle of 'do_writepage()', truncation would be locked
1001  * on the page lock and it would not write the truncated inode node to the
1002  * journal before we have finished.
1003  */
1004 static int ubifs_writepage(struct page *page, struct writeback_control *wbc)
1005 {
1006         struct inode *inode = page->mapping->host;
1007         struct ubifs_info *c = inode->i_sb->s_fs_info;
1008         struct ubifs_inode *ui = ubifs_inode(inode);
1009         loff_t i_size =  i_size_read(inode), synced_i_size;
1010         pgoff_t end_index = i_size >> PAGE_SHIFT;
1011         int err, len = i_size & (PAGE_SIZE - 1);
1012         void *kaddr;
1013
1014         dbg_gen("ino %lu, pg %lu, pg flags %#lx",
1015                 inode->i_ino, page->index, page->flags);
1016         ubifs_assert(c, PagePrivate(page));
1017
1018         /* Is the page fully outside @i_size? (truncate in progress) */
1019         if (page->index > end_index || (page->index == end_index && !len)) {
1020                 err = 0;
1021                 goto out_unlock;
1022         }
1023
1024         spin_lock(&ui->ui_lock);
1025         synced_i_size = ui->synced_i_size;
1026         spin_unlock(&ui->ui_lock);
1027
1028         /* Is the page fully inside @i_size? */
1029         if (page->index < end_index) {
1030                 if (page->index >= synced_i_size >> PAGE_SHIFT) {
1031                         err = inode->i_sb->s_op->write_inode(inode, NULL);
1032                         if (err)
1033                                 goto out_redirty;
1034                         /*
1035                          * The inode has been written, but the write-buffer has
1036                          * not been synchronized, so in case of an unclean
1037                          * reboot we may end up with some pages beyond inode
1038                          * size, but they would be in the journal (because
1039                          * commit flushes write buffers) and recovery would deal
1040                          * with this.
1041                          */
1042                 }
1043                 return do_writepage(page, PAGE_SIZE);
1044         }
1045
1046         /*
1047          * The page straddles @i_size. It must be zeroed out on each and every
1048          * writepage invocation because it may be mmapped. "A file is mapped
1049          * in multiples of the page size. For a file that is not a multiple of
1050          * the page size, the remaining memory is zeroed when mapped, and
1051          * writes to that region are not written out to the file."
1052          */
1053         kaddr = kmap_atomic(page);
1054         memset(kaddr + len, 0, PAGE_SIZE - len);
1055         flush_dcache_page(page);
1056         kunmap_atomic(kaddr);
1057
1058         if (i_size > synced_i_size) {
1059                 err = inode->i_sb->s_op->write_inode(inode, NULL);
1060                 if (err)
1061                         goto out_redirty;
1062         }
1063
1064         return do_writepage(page, len);
1065 out_redirty:
1066         /*
1067          * redirty_page_for_writepage() won't call ubifs_dirty_inode() because
1068          * it passes I_DIRTY_PAGES flag while calling __mark_inode_dirty(), so
1069          * there is no need to do space budget for dirty inode.
1070          */
1071         redirty_page_for_writepage(wbc, page);
1072 out_unlock:
1073         unlock_page(page);
1074         return err;
1075 }
1076
1077 /**
1078  * do_attr_changes - change inode attributes.
1079  * @inode: inode to change attributes for
1080  * @attr: describes attributes to change
1081  */
1082 static void do_attr_changes(struct inode *inode, const struct iattr *attr)
1083 {
1084         if (attr->ia_valid & ATTR_UID)
1085                 inode->i_uid = attr->ia_uid;
1086         if (attr->ia_valid & ATTR_GID)
1087                 inode->i_gid = attr->ia_gid;
1088         if (attr->ia_valid & ATTR_ATIME)
1089                 inode_set_atime_to_ts(inode, attr->ia_atime);
1090         if (attr->ia_valid & ATTR_MTIME)
1091                 inode_set_mtime_to_ts(inode, attr->ia_mtime);
1092         if (attr->ia_valid & ATTR_CTIME)
1093                 inode_set_ctime_to_ts(inode, attr->ia_ctime);
1094         if (attr->ia_valid & ATTR_MODE) {
1095                 umode_t mode = attr->ia_mode;
1096
1097                 if (!in_group_p(inode->i_gid) && !capable(CAP_FSETID))
1098                         mode &= ~S_ISGID;
1099                 inode->i_mode = mode;
1100         }
1101 }
1102
1103 /**
1104  * do_truncation - truncate an inode.
1105  * @c: UBIFS file-system description object
1106  * @inode: inode to truncate
1107  * @attr: inode attribute changes description
1108  *
1109  * This function implements VFS '->setattr()' call when the inode is truncated
1110  * to a smaller size.
1111  *
1112  * Returns: %0 in case of success and a negative error code
1113  * in case of failure.
1114  */
1115 static int do_truncation(struct ubifs_info *c, struct inode *inode,
1116                          const struct iattr *attr)
1117 {
1118         int err;
1119         struct ubifs_budget_req req;
1120         loff_t old_size = inode->i_size, new_size = attr->ia_size;
1121         int offset = new_size & (UBIFS_BLOCK_SIZE - 1), budgeted = 1;
1122         struct ubifs_inode *ui = ubifs_inode(inode);
1123
1124         dbg_gen("ino %lu, size %lld -> %lld", inode->i_ino, old_size, new_size);
1125         memset(&req, 0, sizeof(struct ubifs_budget_req));
1126
1127         /*
1128          * If this is truncation to a smaller size, and we do not truncate on a
1129          * block boundary, budget for changing one data block, because the last
1130          * block will be re-written.
1131          */
1132         if (new_size & (UBIFS_BLOCK_SIZE - 1))
1133                 req.dirtied_page = 1;
1134
1135         req.dirtied_ino = 1;
1136         /* A funny way to budget for truncation node */
1137         req.dirtied_ino_d = UBIFS_TRUN_NODE_SZ;
1138         err = ubifs_budget_space(c, &req);
1139         if (err) {
1140                 /*
1141                  * Treat truncations to zero as deletion and always allow them,
1142                  * just like we do for '->unlink()'.
1143                  */
1144                 if (new_size || err != -ENOSPC)
1145                         return err;
1146                 budgeted = 0;
1147         }
1148
1149         truncate_setsize(inode, new_size);
1150
1151         if (offset) {
1152                 pgoff_t index = new_size >> PAGE_SHIFT;
1153                 struct page *page;
1154
1155                 page = find_lock_page(inode->i_mapping, index);
1156                 if (page) {
1157                         if (PageDirty(page)) {
1158                                 /*
1159                                  * 'ubifs_jnl_truncate()' will try to truncate
1160                                  * the last data node, but it contains
1161                                  * out-of-date data because the page is dirty.
1162                                  * Write the page now, so that
1163                                  * 'ubifs_jnl_truncate()' will see an already
1164                                  * truncated (and up to date) data node.
1165                                  */
1166                                 ubifs_assert(c, PagePrivate(page));
1167
1168                                 clear_page_dirty_for_io(page);
1169                                 if (UBIFS_BLOCKS_PER_PAGE_SHIFT)
1170                                         offset = new_size &
1171                                                  (PAGE_SIZE - 1);
1172                                 err = do_writepage(page, offset);
1173                                 put_page(page);
1174                                 if (err)
1175                                         goto out_budg;
1176                                 /*
1177                                  * We could now tell 'ubifs_jnl_truncate()' not
1178                                  * to read the last block.
1179                                  */
1180                         } else {
1181                                 /*
1182                                  * We could 'kmap()' the page and pass the data
1183                                  * to 'ubifs_jnl_truncate()' to save it from
1184                                  * having to read it.
1185                                  */
1186                                 unlock_page(page);
1187                                 put_page(page);
1188                         }
1189                 }
1190         }
1191
1192         mutex_lock(&ui->ui_mutex);
1193         ui->ui_size = inode->i_size;
1194         /* Truncation changes inode [mc]time */
1195         inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
1196         /* Other attributes may be changed at the same time as well */
1197         do_attr_changes(inode, attr);
1198         err = ubifs_jnl_truncate(c, inode, old_size, new_size);
1199         mutex_unlock(&ui->ui_mutex);
1200
1201 out_budg:
1202         if (budgeted)
1203                 ubifs_release_budget(c, &req);
1204         else {
1205                 c->bi.nospace = c->bi.nospace_rp = 0;
1206                 smp_wmb();
1207         }
1208         return err;
1209 }
1210
1211 /**
1212  * do_setattr - change inode attributes.
1213  * @c: UBIFS file-system description object
1214  * @inode: inode to change attributes for
1215  * @attr: inode attribute changes description
1216  *
1217  * This function implements VFS '->setattr()' call for all cases except
1218  * truncations to smaller size.
1219  *
1220  * Returns: %0 in case of success and a negative
1221  * error code in case of failure.
1222  */
1223 static int do_setattr(struct ubifs_info *c, struct inode *inode,
1224                       const struct iattr *attr)
1225 {
1226         int err, release;
1227         loff_t new_size = attr->ia_size;
1228         struct ubifs_inode *ui = ubifs_inode(inode);
1229         struct ubifs_budget_req req = { .dirtied_ino = 1,
1230                                 .dirtied_ino_d = ALIGN(ui->data_len, 8) };
1231
1232         err = ubifs_budget_space(c, &req);
1233         if (err)
1234                 return err;
1235
1236         if (attr->ia_valid & ATTR_SIZE) {
1237                 dbg_gen("size %lld -> %lld", inode->i_size, new_size);
1238                 truncate_setsize(inode, new_size);
1239         }
1240
1241         mutex_lock(&ui->ui_mutex);
1242         if (attr->ia_valid & ATTR_SIZE) {
1243                 /* Truncation changes inode [mc]time */
1244                 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
1245                 /* 'truncate_setsize()' changed @i_size, update @ui_size */
1246                 ui->ui_size = inode->i_size;
1247         }
1248
1249         do_attr_changes(inode, attr);
1250
1251         release = ui->dirty;
1252         if (attr->ia_valid & ATTR_SIZE)
1253                 /*
1254                  * Inode length changed, so we have to make sure
1255                  * @I_DIRTY_DATASYNC is set.
1256                  */
1257                  __mark_inode_dirty(inode, I_DIRTY_DATASYNC);
1258         else
1259                 mark_inode_dirty_sync(inode);
1260         mutex_unlock(&ui->ui_mutex);
1261
1262         if (release)
1263                 ubifs_release_budget(c, &req);
1264         if (IS_SYNC(inode))
1265                 err = inode->i_sb->s_op->write_inode(inode, NULL);
1266         return err;
1267 }
1268
1269 int ubifs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
1270                   struct iattr *attr)
1271 {
1272         int err;
1273         struct inode *inode = d_inode(dentry);
1274         struct ubifs_info *c = inode->i_sb->s_fs_info;
1275
1276         dbg_gen("ino %lu, mode %#x, ia_valid %#x",
1277                 inode->i_ino, inode->i_mode, attr->ia_valid);
1278         err = setattr_prepare(&nop_mnt_idmap, dentry, attr);
1279         if (err)
1280                 return err;
1281
1282         err = dbg_check_synced_i_size(c, inode);
1283         if (err)
1284                 return err;
1285
1286         err = fscrypt_prepare_setattr(dentry, attr);
1287         if (err)
1288                 return err;
1289
1290         if ((attr->ia_valid & ATTR_SIZE) && attr->ia_size < inode->i_size)
1291                 /* Truncation to a smaller size */
1292                 err = do_truncation(c, inode, attr);
1293         else
1294                 err = do_setattr(c, inode, attr);
1295
1296         return err;
1297 }
1298
1299 static void ubifs_invalidate_folio(struct folio *folio, size_t offset,
1300                                  size_t length)
1301 {
1302         struct inode *inode = folio->mapping->host;
1303         struct ubifs_info *c = inode->i_sb->s_fs_info;
1304
1305         ubifs_assert(c, folio_test_private(folio));
1306         if (offset || length < folio_size(folio))
1307                 /* Partial folio remains dirty */
1308                 return;
1309
1310         if (folio_test_checked(folio))
1311                 release_new_page_budget(c);
1312         else
1313                 release_existing_page_budget(c);
1314
1315         atomic_long_dec(&c->dirty_pg_cnt);
1316         folio_detach_private(folio);
1317         folio_clear_checked(folio);
1318 }
1319
1320 int ubifs_fsync(struct file *file, loff_t start, loff_t end, int datasync)
1321 {
1322         struct inode *inode = file->f_mapping->host;
1323         struct ubifs_info *c = inode->i_sb->s_fs_info;
1324         int err;
1325
1326         dbg_gen("syncing inode %lu", inode->i_ino);
1327
1328         if (c->ro_mount)
1329                 /*
1330                  * For some really strange reasons VFS does not filter out
1331                  * 'fsync()' for R/O mounted file-systems as per 2.6.39.
1332                  */
1333                 return 0;
1334
1335         err = file_write_and_wait_range(file, start, end);
1336         if (err)
1337                 return err;
1338         inode_lock(inode);
1339
1340         /* Synchronize the inode unless this is a 'datasync()' call. */
1341         if (!datasync || (inode->i_state & I_DIRTY_DATASYNC)) {
1342                 err = inode->i_sb->s_op->write_inode(inode, NULL);
1343                 if (err)
1344                         goto out;
1345         }
1346
1347         /*
1348          * Nodes related to this inode may still sit in a write-buffer. Flush
1349          * them.
1350          */
1351         err = ubifs_sync_wbufs_by_inode(c, inode);
1352 out:
1353         inode_unlock(inode);
1354         return err;
1355 }
1356
1357 /**
1358  * mctime_update_needed - check if mtime or ctime update is needed.
1359  * @inode: the inode to do the check for
1360  * @now: current time
1361  *
1362  * This helper function checks if the inode mtime/ctime should be updated or
1363  * not. If current values of the time-stamps are within the UBIFS inode time
1364  * granularity, they are not updated. This is an optimization.
1365  *
1366  * Returns: %1 if time update is needed, %0 if not
1367  */
1368 static inline int mctime_update_needed(const struct inode *inode,
1369                                        const struct timespec64 *now)
1370 {
1371         struct timespec64 ctime = inode_get_ctime(inode);
1372         struct timespec64 mtime = inode_get_mtime(inode);
1373
1374         if (!timespec64_equal(&mtime, now) || !timespec64_equal(&ctime, now))
1375                 return 1;
1376         return 0;
1377 }
1378
1379 /**
1380  * ubifs_update_time - update time of inode.
1381  * @inode: inode to update
1382  * @flags: time updating control flag determines updating
1383  *          which time fields of @inode
1384  *
1385  * This function updates time of the inode.
1386  *
1387  * Returns: %0 for success or a negative error code otherwise.
1388  */
1389 int ubifs_update_time(struct inode *inode, int flags)
1390 {
1391         struct ubifs_inode *ui = ubifs_inode(inode);
1392         struct ubifs_info *c = inode->i_sb->s_fs_info;
1393         struct ubifs_budget_req req = { .dirtied_ino = 1,
1394                         .dirtied_ino_d = ALIGN(ui->data_len, 8) };
1395         int err, release;
1396
1397         if (!IS_ENABLED(CONFIG_UBIFS_ATIME_SUPPORT)) {
1398                 generic_update_time(inode, flags);
1399                 return 0;
1400         }
1401
1402         err = ubifs_budget_space(c, &req);
1403         if (err)
1404                 return err;
1405
1406         mutex_lock(&ui->ui_mutex);
1407         inode_update_timestamps(inode, flags);
1408         release = ui->dirty;
1409         __mark_inode_dirty(inode, I_DIRTY_SYNC);
1410         mutex_unlock(&ui->ui_mutex);
1411         if (release)
1412                 ubifs_release_budget(c, &req);
1413         return 0;
1414 }
1415
1416 /**
1417  * update_mctime - update mtime and ctime of an inode.
1418  * @inode: inode to update
1419  *
1420  * This function updates mtime and ctime of the inode if it is not equivalent to
1421  * current time.
1422  *
1423  * Returns: %0 in case of success and a negative error code in
1424  * case of failure.
1425  */
1426 static int update_mctime(struct inode *inode)
1427 {
1428         struct timespec64 now = current_time(inode);
1429         struct ubifs_inode *ui = ubifs_inode(inode);
1430         struct ubifs_info *c = inode->i_sb->s_fs_info;
1431
1432         if (mctime_update_needed(inode, &now)) {
1433                 int err, release;
1434                 struct ubifs_budget_req req = { .dirtied_ino = 1,
1435                                 .dirtied_ino_d = ALIGN(ui->data_len, 8) };
1436
1437                 err = ubifs_budget_space(c, &req);
1438                 if (err)
1439                         return err;
1440
1441                 mutex_lock(&ui->ui_mutex);
1442                 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
1443                 release = ui->dirty;
1444                 mark_inode_dirty_sync(inode);
1445                 mutex_unlock(&ui->ui_mutex);
1446                 if (release)
1447                         ubifs_release_budget(c, &req);
1448         }
1449
1450         return 0;
1451 }
1452
1453 static ssize_t ubifs_write_iter(struct kiocb *iocb, struct iov_iter *from)
1454 {
1455         int err = update_mctime(file_inode(iocb->ki_filp));
1456         if (err)
1457                 return err;
1458
1459         return generic_file_write_iter(iocb, from);
1460 }
1461
1462 static bool ubifs_dirty_folio(struct address_space *mapping,
1463                 struct folio *folio)
1464 {
1465         bool ret;
1466         struct ubifs_info *c = mapping->host->i_sb->s_fs_info;
1467
1468         ret = filemap_dirty_folio(mapping, folio);
1469         /*
1470          * An attempt to dirty a page without budgeting for it - should not
1471          * happen.
1472          */
1473         ubifs_assert(c, ret == false);
1474         return ret;
1475 }
1476
1477 static bool ubifs_release_folio(struct folio *folio, gfp_t unused_gfp_flags)
1478 {
1479         struct inode *inode = folio->mapping->host;
1480         struct ubifs_info *c = inode->i_sb->s_fs_info;
1481
1482         if (folio_test_writeback(folio))
1483                 return false;
1484
1485         /*
1486          * Page is private but not dirty, weird? There is one condition
1487          * making it happened. ubifs_writepage skipped the page because
1488          * page index beyonds isize (for example. truncated by other
1489          * process named A), then the page is invalidated by fadvise64
1490          * syscall before being truncated by process A.
1491          */
1492         ubifs_assert(c, folio_test_private(folio));
1493         if (folio_test_checked(folio))
1494                 release_new_page_budget(c);
1495         else
1496                 release_existing_page_budget(c);
1497
1498         atomic_long_dec(&c->dirty_pg_cnt);
1499         folio_detach_private(folio);
1500         folio_clear_checked(folio);
1501         return true;
1502 }
1503
1504 /*
1505  * mmap()d file has taken write protection fault and is being made writable.
1506  * UBIFS must ensure page is budgeted for.
1507  */
1508 static vm_fault_t ubifs_vm_page_mkwrite(struct vm_fault *vmf)
1509 {
1510         struct page *page = vmf->page;
1511         struct inode *inode = file_inode(vmf->vma->vm_file);
1512         struct ubifs_info *c = inode->i_sb->s_fs_info;
1513         struct timespec64 now = current_time(inode);
1514         struct ubifs_budget_req req = { .new_page = 1 };
1515         int err, update_time;
1516
1517         dbg_gen("ino %lu, pg %lu, i_size %lld", inode->i_ino, page->index,
1518                 i_size_read(inode));
1519         ubifs_assert(c, !c->ro_media && !c->ro_mount);
1520
1521         if (unlikely(c->ro_error))
1522                 return VM_FAULT_SIGBUS; /* -EROFS */
1523
1524         /*
1525          * We have not locked @page so far so we may budget for changing the
1526          * page. Note, we cannot do this after we locked the page, because
1527          * budgeting may cause write-back which would cause deadlock.
1528          *
1529          * At the moment we do not know whether the page is dirty or not, so we
1530          * assume that it is not and budget for a new page. We could look at
1531          * the @PG_private flag and figure this out, but we may race with write
1532          * back and the page state may change by the time we lock it, so this
1533          * would need additional care. We do not bother with this at the
1534          * moment, although it might be good idea to do. Instead, we allocate
1535          * budget for a new page and amend it later on if the page was in fact
1536          * dirty.
1537          *
1538          * The budgeting-related logic of this function is similar to what we
1539          * do in 'ubifs_write_begin()' and 'ubifs_write_end()'. Glance there
1540          * for more comments.
1541          */
1542         update_time = mctime_update_needed(inode, &now);
1543         if (update_time)
1544                 /*
1545                  * We have to change inode time stamp which requires extra
1546                  * budgeting.
1547                  */
1548                 req.dirtied_ino = 1;
1549
1550         err = ubifs_budget_space(c, &req);
1551         if (unlikely(err)) {
1552                 if (err == -ENOSPC)
1553                         ubifs_warn(c, "out of space for mmapped file (inode number %lu)",
1554                                    inode->i_ino);
1555                 return VM_FAULT_SIGBUS;
1556         }
1557
1558         lock_page(page);
1559         if (unlikely(page->mapping != inode->i_mapping ||
1560                      page_offset(page) > i_size_read(inode))) {
1561                 /* Page got truncated out from underneath us */
1562                 goto sigbus;
1563         }
1564
1565         if (PagePrivate(page))
1566                 release_new_page_budget(c);
1567         else {
1568                 if (!PageChecked(page))
1569                         ubifs_convert_page_budget(c);
1570                 attach_page_private(page, (void *)1);
1571                 atomic_long_inc(&c->dirty_pg_cnt);
1572                 __set_page_dirty_nobuffers(page);
1573         }
1574
1575         if (update_time) {
1576                 int release;
1577                 struct ubifs_inode *ui = ubifs_inode(inode);
1578
1579                 mutex_lock(&ui->ui_mutex);
1580                 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
1581                 release = ui->dirty;
1582                 mark_inode_dirty_sync(inode);
1583                 mutex_unlock(&ui->ui_mutex);
1584                 if (release)
1585                         ubifs_release_dirty_inode_budget(c, ui);
1586         }
1587
1588         wait_for_stable_page(page);
1589         return VM_FAULT_LOCKED;
1590
1591 sigbus:
1592         unlock_page(page);
1593         ubifs_release_budget(c, &req);
1594         return VM_FAULT_SIGBUS;
1595 }
1596
1597 static const struct vm_operations_struct ubifs_file_vm_ops = {
1598         .fault        = filemap_fault,
1599         .map_pages = filemap_map_pages,
1600         .page_mkwrite = ubifs_vm_page_mkwrite,
1601 };
1602
1603 static int ubifs_file_mmap(struct file *file, struct vm_area_struct *vma)
1604 {
1605         int err;
1606
1607         err = generic_file_mmap(file, vma);
1608         if (err)
1609                 return err;
1610         vma->vm_ops = &ubifs_file_vm_ops;
1611
1612         if (IS_ENABLED(CONFIG_UBIFS_ATIME_SUPPORT))
1613                 file_accessed(file);
1614
1615         return 0;
1616 }
1617
1618 static const char *ubifs_get_link(struct dentry *dentry,
1619                                             struct inode *inode,
1620                                             struct delayed_call *done)
1621 {
1622         struct ubifs_inode *ui = ubifs_inode(inode);
1623
1624         if (!IS_ENCRYPTED(inode))
1625                 return ui->data;
1626
1627         if (!dentry)
1628                 return ERR_PTR(-ECHILD);
1629
1630         return fscrypt_get_symlink(inode, ui->data, ui->data_len, done);
1631 }
1632
1633 static int ubifs_symlink_getattr(struct mnt_idmap *idmap,
1634                                  const struct path *path, struct kstat *stat,
1635                                  u32 request_mask, unsigned int query_flags)
1636 {
1637         ubifs_getattr(idmap, path, stat, request_mask, query_flags);
1638
1639         if (IS_ENCRYPTED(d_inode(path->dentry)))
1640                 return fscrypt_symlink_getattr(path, stat);
1641         return 0;
1642 }
1643
1644 const struct address_space_operations ubifs_file_address_operations = {
1645         .read_folio     = ubifs_read_folio,
1646         .writepage      = ubifs_writepage,
1647         .write_begin    = ubifs_write_begin,
1648         .write_end      = ubifs_write_end,
1649         .invalidate_folio = ubifs_invalidate_folio,
1650         .dirty_folio    = ubifs_dirty_folio,
1651         .migrate_folio  = filemap_migrate_folio,
1652         .release_folio  = ubifs_release_folio,
1653 };
1654
1655 const struct inode_operations ubifs_file_inode_operations = {
1656         .setattr     = ubifs_setattr,
1657         .getattr     = ubifs_getattr,
1658         .listxattr   = ubifs_listxattr,
1659         .update_time = ubifs_update_time,
1660         .fileattr_get = ubifs_fileattr_get,
1661         .fileattr_set = ubifs_fileattr_set,
1662 };
1663
1664 const struct inode_operations ubifs_symlink_inode_operations = {
1665         .get_link    = ubifs_get_link,
1666         .setattr     = ubifs_setattr,
1667         .getattr     = ubifs_symlink_getattr,
1668         .listxattr   = ubifs_listxattr,
1669         .update_time = ubifs_update_time,
1670 };
1671
1672 const struct file_operations ubifs_file_operations = {
1673         .llseek         = generic_file_llseek,
1674         .read_iter      = generic_file_read_iter,
1675         .write_iter     = ubifs_write_iter,
1676         .mmap           = ubifs_file_mmap,
1677         .fsync          = ubifs_fsync,
1678         .unlocked_ioctl = ubifs_ioctl,
1679         .splice_read    = filemap_splice_read,
1680         .splice_write   = iter_file_splice_write,
1681         .open           = fscrypt_file_open,
1682 #ifdef CONFIG_COMPAT
1683         .compat_ioctl   = ubifs_compat_ioctl,
1684 #endif
1685 };