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