Auto-update from upstream
[linux-2.6] / fs / ntfs / aops.c
1 /**
2  * aops.c - NTFS kernel address space operations and page cache handling.
3  *          Part of the Linux-NTFS project.
4  *
5  * Copyright (c) 2001-2005 Anton Altaparmakov
6  * Copyright (c) 2002 Richard Russon
7  *
8  * This program/include file is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License as published
10  * by the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program/include file is distributed in the hope that it will be
14  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
15  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program (in the main directory of the Linux-NTFS
20  * distribution in the file COPYING); if not, write to the Free Software
21  * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 #include <linux/errno.h>
25 #include <linux/mm.h>
26 #include <linux/pagemap.h>
27 #include <linux/swap.h>
28 #include <linux/buffer_head.h>
29 #include <linux/writeback.h>
30
31 #include "aops.h"
32 #include "attrib.h"
33 #include "debug.h"
34 #include "inode.h"
35 #include "mft.h"
36 #include "runlist.h"
37 #include "types.h"
38 #include "ntfs.h"
39
40 /**
41  * ntfs_end_buffer_async_read - async io completion for reading attributes
42  * @bh:         buffer head on which io is completed
43  * @uptodate:   whether @bh is now uptodate or not
44  *
45  * Asynchronous I/O completion handler for reading pages belonging to the
46  * attribute address space of an inode.  The inodes can either be files or
47  * directories or they can be fake inodes describing some attribute.
48  *
49  * If NInoMstProtected(), perform the post read mst fixups when all IO on the
50  * page has been completed and mark the page uptodate or set the error bit on
51  * the page.  To determine the size of the records that need fixing up, we
52  * cheat a little bit by setting the index_block_size in ntfs_inode to the ntfs
53  * record size, and index_block_size_bits, to the log(base 2) of the ntfs
54  * record size.
55  */
56 static void ntfs_end_buffer_async_read(struct buffer_head *bh, int uptodate)
57 {
58         static DEFINE_SPINLOCK(page_uptodate_lock);
59         unsigned long flags;
60         struct buffer_head *tmp;
61         struct page *page;
62         ntfs_inode *ni;
63         int page_uptodate = 1;
64
65         page = bh->b_page;
66         ni = NTFS_I(page->mapping->host);
67
68         if (likely(uptodate)) {
69                 s64 file_ofs, initialized_size;
70
71                 set_buffer_uptodate(bh);
72
73                 file_ofs = ((s64)page->index << PAGE_CACHE_SHIFT) +
74                                 bh_offset(bh);
75                 read_lock_irqsave(&ni->size_lock, flags);
76                 initialized_size = ni->initialized_size;
77                 read_unlock_irqrestore(&ni->size_lock, flags);
78                 /* Check for the current buffer head overflowing. */
79                 if (file_ofs + bh->b_size > initialized_size) {
80                         char *addr;
81                         int ofs = 0;
82
83                         if (file_ofs < initialized_size)
84                                 ofs = initialized_size - file_ofs;
85                         addr = kmap_atomic(page, KM_BIO_SRC_IRQ);
86                         memset(addr + bh_offset(bh) + ofs, 0, bh->b_size - ofs);
87                         flush_dcache_page(page);
88                         kunmap_atomic(addr, KM_BIO_SRC_IRQ);
89                 }
90         } else {
91                 clear_buffer_uptodate(bh);
92                 ntfs_error(ni->vol->sb, "Buffer I/O error, logical block %llu.",
93                                 (unsigned long long)bh->b_blocknr);
94                 SetPageError(page);
95         }
96         spin_lock_irqsave(&page_uptodate_lock, flags);
97         clear_buffer_async_read(bh);
98         unlock_buffer(bh);
99         tmp = bh;
100         do {
101                 if (!buffer_uptodate(tmp))
102                         page_uptodate = 0;
103                 if (buffer_async_read(tmp)) {
104                         if (likely(buffer_locked(tmp)))
105                                 goto still_busy;
106                         /* Async buffers must be locked. */
107                         BUG();
108                 }
109                 tmp = tmp->b_this_page;
110         } while (tmp != bh);
111         spin_unlock_irqrestore(&page_uptodate_lock, flags);
112         /*
113          * If none of the buffers had errors then we can set the page uptodate,
114          * but we first have to perform the post read mst fixups, if the
115          * attribute is mst protected, i.e. if NInoMstProteced(ni) is true.
116          * Note we ignore fixup errors as those are detected when
117          * map_mft_record() is called which gives us per record granularity
118          * rather than per page granularity.
119          */
120         if (!NInoMstProtected(ni)) {
121                 if (likely(page_uptodate && !PageError(page)))
122                         SetPageUptodate(page);
123         } else {
124                 char *addr;
125                 unsigned int i, recs;
126                 u32 rec_size;
127
128                 rec_size = ni->itype.index.block_size;
129                 recs = PAGE_CACHE_SIZE / rec_size;
130                 /* Should have been verified before we got here... */
131                 BUG_ON(!recs);
132                 addr = kmap_atomic(page, KM_BIO_SRC_IRQ);
133                 for (i = 0; i < recs; i++)
134                         post_read_mst_fixup((NTFS_RECORD*)(addr +
135                                         i * rec_size), rec_size);
136                 flush_dcache_page(page);
137                 kunmap_atomic(addr, KM_BIO_SRC_IRQ);
138                 if (likely(page_uptodate && !PageError(page)))
139                         SetPageUptodate(page);
140         }
141         unlock_page(page);
142         return;
143 still_busy:
144         spin_unlock_irqrestore(&page_uptodate_lock, flags);
145         return;
146 }
147
148 /**
149  * ntfs_read_block - fill a @page of an address space with data
150  * @page:       page cache page to fill with data
151  *
152  * Fill the page @page of the address space belonging to the @page->host inode.
153  * We read each buffer asynchronously and when all buffers are read in, our io
154  * completion handler ntfs_end_buffer_read_async(), if required, automatically
155  * applies the mst fixups to the page before finally marking it uptodate and
156  * unlocking it.
157  *
158  * We only enforce allocated_size limit because i_size is checked for in
159  * generic_file_read().
160  *
161  * Return 0 on success and -errno on error.
162  *
163  * Contains an adapted version of fs/buffer.c::block_read_full_page().
164  */
165 static int ntfs_read_block(struct page *page)
166 {
167         VCN vcn;
168         LCN lcn;
169         ntfs_inode *ni;
170         ntfs_volume *vol;
171         runlist_element *rl;
172         struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
173         sector_t iblock, lblock, zblock;
174         unsigned long flags;
175         unsigned int blocksize, vcn_ofs;
176         int i, nr;
177         unsigned char blocksize_bits;
178
179         ni = NTFS_I(page->mapping->host);
180         vol = ni->vol;
181
182         /* $MFT/$DATA must have its complete runlist in memory at all times. */
183         BUG_ON(!ni->runlist.rl && !ni->mft_no && !NInoAttr(ni));
184
185         blocksize_bits = VFS_I(ni)->i_blkbits;
186         blocksize = 1 << blocksize_bits;
187
188         if (!page_has_buffers(page))
189                 create_empty_buffers(page, blocksize, 0);
190         bh = head = page_buffers(page);
191         if (unlikely(!bh)) {
192                 unlock_page(page);
193                 return -ENOMEM;
194         }
195
196         iblock = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
197         read_lock_irqsave(&ni->size_lock, flags);
198         lblock = (ni->allocated_size + blocksize - 1) >> blocksize_bits;
199         zblock = (ni->initialized_size + blocksize - 1) >> blocksize_bits;
200         read_unlock_irqrestore(&ni->size_lock, flags);
201
202         /* Loop through all the buffers in the page. */
203         rl = NULL;
204         nr = i = 0;
205         do {
206                 u8 *kaddr;
207
208                 if (unlikely(buffer_uptodate(bh)))
209                         continue;
210                 if (unlikely(buffer_mapped(bh))) {
211                         arr[nr++] = bh;
212                         continue;
213                 }
214                 bh->b_bdev = vol->sb->s_bdev;
215                 /* Is the block within the allowed limits? */
216                 if (iblock < lblock) {
217                         BOOL is_retry = FALSE;
218
219                         /* Convert iblock into corresponding vcn and offset. */
220                         vcn = (VCN)iblock << blocksize_bits >>
221                                         vol->cluster_size_bits;
222                         vcn_ofs = ((VCN)iblock << blocksize_bits) &
223                                         vol->cluster_size_mask;
224                         if (!rl) {
225 lock_retry_remap:
226                                 down_read(&ni->runlist.lock);
227                                 rl = ni->runlist.rl;
228                         }
229                         if (likely(rl != NULL)) {
230                                 /* Seek to element containing target vcn. */
231                                 while (rl->length && rl[1].vcn <= vcn)
232                                         rl++;
233                                 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
234                         } else
235                                 lcn = LCN_RL_NOT_MAPPED;
236                         /* Successful remap. */
237                         if (lcn >= 0) {
238                                 /* Setup buffer head to correct block. */
239                                 bh->b_blocknr = ((lcn << vol->cluster_size_bits)
240                                                 + vcn_ofs) >> blocksize_bits;
241                                 set_buffer_mapped(bh);
242                                 /* Only read initialized data blocks. */
243                                 if (iblock < zblock) {
244                                         arr[nr++] = bh;
245                                         continue;
246                                 }
247                                 /* Fully non-initialized data block, zero it. */
248                                 goto handle_zblock;
249                         }
250                         /* It is a hole, need to zero it. */
251                         if (lcn == LCN_HOLE)
252                                 goto handle_hole;
253                         /* If first try and runlist unmapped, map and retry. */
254                         if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
255                                 int err;
256                                 is_retry = TRUE;
257                                 /*
258                                  * Attempt to map runlist, dropping lock for
259                                  * the duration.
260                                  */
261                                 up_read(&ni->runlist.lock);
262                                 err = ntfs_map_runlist(ni, vcn);
263                                 if (likely(!err))
264                                         goto lock_retry_remap;
265                                 rl = NULL;
266                                 lcn = err;
267                         } else if (!rl)
268                                 up_read(&ni->runlist.lock);
269                         /* Hard error, zero out region. */
270                         bh->b_blocknr = -1;
271                         SetPageError(page);
272                         ntfs_error(vol->sb, "Failed to read from inode 0x%lx, "
273                                         "attribute type 0x%x, vcn 0x%llx, "
274                                         "offset 0x%x because its location on "
275                                         "disk could not be determined%s "
276                                         "(error code %lli).", ni->mft_no,
277                                         ni->type, (unsigned long long)vcn,
278                                         vcn_ofs, is_retry ? " even after "
279                                         "retrying" : "", (long long)lcn);
280                 }
281                 /*
282                  * Either iblock was outside lblock limits or
283                  * ntfs_rl_vcn_to_lcn() returned error.  Just zero that portion
284                  * of the page and set the buffer uptodate.
285                  */
286 handle_hole:
287                 bh->b_blocknr = -1UL;
288                 clear_buffer_mapped(bh);
289 handle_zblock:
290                 kaddr = kmap_atomic(page, KM_USER0);
291                 memset(kaddr + i * blocksize, 0, blocksize);
292                 flush_dcache_page(page);
293                 kunmap_atomic(kaddr, KM_USER0);
294                 set_buffer_uptodate(bh);
295         } while (i++, iblock++, (bh = bh->b_this_page) != head);
296
297         /* Release the lock if we took it. */
298         if (rl)
299                 up_read(&ni->runlist.lock);
300
301         /* Check we have at least one buffer ready for i/o. */
302         if (nr) {
303                 struct buffer_head *tbh;
304
305                 /* Lock the buffers. */
306                 for (i = 0; i < nr; i++) {
307                         tbh = arr[i];
308                         lock_buffer(tbh);
309                         tbh->b_end_io = ntfs_end_buffer_async_read;
310                         set_buffer_async_read(tbh);
311                 }
312                 /* Finally, start i/o on the buffers. */
313                 for (i = 0; i < nr; i++) {
314                         tbh = arr[i];
315                         if (likely(!buffer_uptodate(tbh)))
316                                 submit_bh(READ, tbh);
317                         else
318                                 ntfs_end_buffer_async_read(tbh, 1);
319                 }
320                 return 0;
321         }
322         /* No i/o was scheduled on any of the buffers. */
323         if (likely(!PageError(page)))
324                 SetPageUptodate(page);
325         else /* Signal synchronous i/o error. */
326                 nr = -EIO;
327         unlock_page(page);
328         return nr;
329 }
330
331 /**
332  * ntfs_readpage - fill a @page of a @file with data from the device
333  * @file:       open file to which the page @page belongs or NULL
334  * @page:       page cache page to fill with data
335  *
336  * For non-resident attributes, ntfs_readpage() fills the @page of the open
337  * file @file by calling the ntfs version of the generic block_read_full_page()
338  * function, ntfs_read_block(), which in turn creates and reads in the buffers
339  * associated with the page asynchronously.
340  *
341  * For resident attributes, OTOH, ntfs_readpage() fills @page by copying the
342  * data from the mft record (which at this stage is most likely in memory) and
343  * fills the remainder with zeroes. Thus, in this case, I/O is synchronous, as
344  * even if the mft record is not cached at this point in time, we need to wait
345  * for it to be read in before we can do the copy.
346  *
347  * Return 0 on success and -errno on error.
348  */
349 static int ntfs_readpage(struct file *file, struct page *page)
350 {
351         ntfs_inode *ni, *base_ni;
352         u8 *kaddr;
353         ntfs_attr_search_ctx *ctx;
354         MFT_RECORD *mrec;
355         unsigned long flags;
356         u32 attr_len;
357         int err = 0;
358
359 retry_readpage:
360         BUG_ON(!PageLocked(page));
361         /*
362          * This can potentially happen because we clear PageUptodate() during
363          * ntfs_writepage() of MstProtected() attributes.
364          */
365         if (PageUptodate(page)) {
366                 unlock_page(page);
367                 return 0;
368         }
369         ni = NTFS_I(page->mapping->host);
370
371         /* NInoNonResident() == NInoIndexAllocPresent() */
372         if (NInoNonResident(ni)) {
373                 /*
374                  * Only unnamed $DATA attributes can be compressed or
375                  * encrypted.
376                  */
377                 if (ni->type == AT_DATA && !ni->name_len) {
378                         /* If file is encrypted, deny access, just like NT4. */
379                         if (NInoEncrypted(ni)) {
380                                 err = -EACCES;
381                                 goto err_out;
382                         }
383                         /* Compressed data streams are handled in compress.c. */
384                         if (NInoCompressed(ni))
385                                 return ntfs_read_compressed_block(page);
386                 }
387                 /* Normal data stream. */
388                 return ntfs_read_block(page);
389         }
390         /*
391          * Attribute is resident, implying it is not compressed or encrypted.
392          * This also means the attribute is smaller than an mft record and
393          * hence smaller than a page, so can simply zero out any pages with
394          * index above 0.
395          */
396         if (unlikely(page->index > 0)) {
397                 kaddr = kmap_atomic(page, KM_USER0);
398                 memset(kaddr, 0, PAGE_CACHE_SIZE);
399                 flush_dcache_page(page);
400                 kunmap_atomic(kaddr, KM_USER0);
401                 goto done;
402         }
403         if (!NInoAttr(ni))
404                 base_ni = ni;
405         else
406                 base_ni = ni->ext.base_ntfs_ino;
407         /* Map, pin, and lock the mft record. */
408         mrec = map_mft_record(base_ni);
409         if (IS_ERR(mrec)) {
410                 err = PTR_ERR(mrec);
411                 goto err_out;
412         }
413         /*
414          * If a parallel write made the attribute non-resident, drop the mft
415          * record and retry the readpage.
416          */
417         if (unlikely(NInoNonResident(ni))) {
418                 unmap_mft_record(base_ni);
419                 goto retry_readpage;
420         }
421         ctx = ntfs_attr_get_search_ctx(base_ni, mrec);
422         if (unlikely(!ctx)) {
423                 err = -ENOMEM;
424                 goto unm_err_out;
425         }
426         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
427                         CASE_SENSITIVE, 0, NULL, 0, ctx);
428         if (unlikely(err))
429                 goto put_unm_err_out;
430         attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
431         read_lock_irqsave(&ni->size_lock, flags);
432         if (unlikely(attr_len > ni->initialized_size))
433                 attr_len = ni->initialized_size;
434         read_unlock_irqrestore(&ni->size_lock, flags);
435         kaddr = kmap_atomic(page, KM_USER0);
436         /* Copy the data to the page. */
437         memcpy(kaddr, (u8*)ctx->attr +
438                         le16_to_cpu(ctx->attr->data.resident.value_offset),
439                         attr_len);
440         /* Zero the remainder of the page. */
441         memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
442         flush_dcache_page(page);
443         kunmap_atomic(kaddr, KM_USER0);
444 put_unm_err_out:
445         ntfs_attr_put_search_ctx(ctx);
446 unm_err_out:
447         unmap_mft_record(base_ni);
448 done:
449         SetPageUptodate(page);
450 err_out:
451         unlock_page(page);
452         return err;
453 }
454
455 #ifdef NTFS_RW
456
457 /**
458  * ntfs_write_block - write a @page to the backing store
459  * @page:       page cache page to write out
460  * @wbc:        writeback control structure
461  *
462  * This function is for writing pages belonging to non-resident, non-mst
463  * protected attributes to their backing store.
464  *
465  * For a page with buffers, map and write the dirty buffers asynchronously
466  * under page writeback. For a page without buffers, create buffers for the
467  * page, then proceed as above.
468  *
469  * If a page doesn't have buffers the page dirty state is definitive. If a page
470  * does have buffers, the page dirty state is just a hint, and the buffer dirty
471  * state is definitive. (A hint which has rules: dirty buffers against a clean
472  * page is illegal. Other combinations are legal and need to be handled. In
473  * particular a dirty page containing clean buffers for example.)
474  *
475  * Return 0 on success and -errno on error.
476  *
477  * Based on ntfs_read_block() and __block_write_full_page().
478  */
479 static int ntfs_write_block(struct page *page, struct writeback_control *wbc)
480 {
481         VCN vcn;
482         LCN lcn;
483         s64 initialized_size;
484         loff_t i_size;
485         sector_t block, dblock, iblock;
486         struct inode *vi;
487         ntfs_inode *ni;
488         ntfs_volume *vol;
489         runlist_element *rl;
490         struct buffer_head *bh, *head;
491         unsigned long flags;
492         unsigned int blocksize, vcn_ofs;
493         int err;
494         BOOL need_end_writeback;
495         unsigned char blocksize_bits;
496
497         vi = page->mapping->host;
498         ni = NTFS_I(vi);
499         vol = ni->vol;
500
501         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
502                         "0x%lx.", ni->mft_no, ni->type, page->index);
503
504         BUG_ON(!NInoNonResident(ni));
505         BUG_ON(NInoMstProtected(ni));
506
507         blocksize_bits = vi->i_blkbits;
508         blocksize = 1 << blocksize_bits;
509
510         if (!page_has_buffers(page)) {
511                 BUG_ON(!PageUptodate(page));
512                 create_empty_buffers(page, blocksize,
513                                 (1 << BH_Uptodate) | (1 << BH_Dirty));
514         }
515         bh = head = page_buffers(page);
516         if (unlikely(!bh)) {
517                 ntfs_warning(vol->sb, "Error allocating page buffers. "
518                                 "Redirtying page so we try again later.");
519                 /*
520                  * Put the page back on mapping->dirty_pages, but leave its
521                  * buffer's dirty state as-is.
522                  */
523                 redirty_page_for_writepage(wbc, page);
524                 unlock_page(page);
525                 return 0;
526         }
527
528         /* NOTE: Different naming scheme to ntfs_read_block()! */
529
530         /* The first block in the page. */
531         block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
532
533         read_lock_irqsave(&ni->size_lock, flags);
534         i_size = i_size_read(vi);
535         initialized_size = ni->initialized_size;
536         read_unlock_irqrestore(&ni->size_lock, flags);
537
538         /* The first out of bounds block for the data size. */
539         dblock = (i_size + blocksize - 1) >> blocksize_bits;
540
541         /* The last (fully or partially) initialized block. */
542         iblock = initialized_size >> blocksize_bits;
543
544         /*
545          * Be very careful.  We have no exclusion from __set_page_dirty_buffers
546          * here, and the (potentially unmapped) buffers may become dirty at
547          * any time.  If a buffer becomes dirty here after we've inspected it
548          * then we just miss that fact, and the page stays dirty.
549          *
550          * Buffers outside i_size may be dirtied by __set_page_dirty_buffers;
551          * handle that here by just cleaning them.
552          */
553
554         /*
555          * Loop through all the buffers in the page, mapping all the dirty
556          * buffers to disk addresses and handling any aliases from the
557          * underlying block device's mapping.
558          */
559         rl = NULL;
560         err = 0;
561         do {
562                 BOOL is_retry = FALSE;
563
564                 if (unlikely(block >= dblock)) {
565                         /*
566                          * Mapped buffers outside i_size will occur, because
567                          * this page can be outside i_size when there is a
568                          * truncate in progress. The contents of such buffers
569                          * were zeroed by ntfs_writepage().
570                          *
571                          * FIXME: What about the small race window where
572                          * ntfs_writepage() has not done any clearing because
573                          * the page was within i_size but before we get here,
574                          * vmtruncate() modifies i_size?
575                          */
576                         clear_buffer_dirty(bh);
577                         set_buffer_uptodate(bh);
578                         continue;
579                 }
580
581                 /* Clean buffers are not written out, so no need to map them. */
582                 if (!buffer_dirty(bh))
583                         continue;
584
585                 /* Make sure we have enough initialized size. */
586                 if (unlikely((block >= iblock) &&
587                                 (initialized_size < i_size))) {
588                         /*
589                          * If this page is fully outside initialized size, zero
590                          * out all pages between the current initialized size
591                          * and the current page. Just use ntfs_readpage() to do
592                          * the zeroing transparently.
593                          */
594                         if (block > iblock) {
595                                 // TODO:
596                                 // For each page do:
597                                 // - read_cache_page()
598                                 // Again for each page do:
599                                 // - wait_on_page_locked()
600                                 // - Check (PageUptodate(page) &&
601                                 //                      !PageError(page))
602                                 // Update initialized size in the attribute and
603                                 // in the inode.
604                                 // Again, for each page do:
605                                 //      __set_page_dirty_buffers();
606                                 // page_cache_release()
607                                 // We don't need to wait on the writes.
608                                 // Update iblock.
609                         }
610                         /*
611                          * The current page straddles initialized size. Zero
612                          * all non-uptodate buffers and set them uptodate (and
613                          * dirty?). Note, there aren't any non-uptodate buffers
614                          * if the page is uptodate.
615                          * FIXME: For an uptodate page, the buffers may need to
616                          * be written out because they were not initialized on
617                          * disk before.
618                          */
619                         if (!PageUptodate(page)) {
620                                 // TODO:
621                                 // Zero any non-uptodate buffers up to i_size.
622                                 // Set them uptodate and dirty.
623                         }
624                         // TODO:
625                         // Update initialized size in the attribute and in the
626                         // inode (up to i_size).
627                         // Update iblock.
628                         // FIXME: This is inefficient. Try to batch the two
629                         // size changes to happen in one go.
630                         ntfs_error(vol->sb, "Writing beyond initialized size "
631                                         "is not supported yet. Sorry.");
632                         err = -EOPNOTSUPP;
633                         break;
634                         // Do NOT set_buffer_new() BUT DO clear buffer range
635                         // outside write request range.
636                         // set_buffer_uptodate() on complete buffers as well as
637                         // set_buffer_dirty().
638                 }
639
640                 /* No need to map buffers that are already mapped. */
641                 if (buffer_mapped(bh))
642                         continue;
643
644                 /* Unmapped, dirty buffer. Need to map it. */
645                 bh->b_bdev = vol->sb->s_bdev;
646
647                 /* Convert block into corresponding vcn and offset. */
648                 vcn = (VCN)block << blocksize_bits;
649                 vcn_ofs = vcn & vol->cluster_size_mask;
650                 vcn >>= vol->cluster_size_bits;
651                 if (!rl) {
652 lock_retry_remap:
653                         down_read(&ni->runlist.lock);
654                         rl = ni->runlist.rl;
655                 }
656                 if (likely(rl != NULL)) {
657                         /* Seek to element containing target vcn. */
658                         while (rl->length && rl[1].vcn <= vcn)
659                                 rl++;
660                         lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
661                 } else
662                         lcn = LCN_RL_NOT_MAPPED;
663                 /* Successful remap. */
664                 if (lcn >= 0) {
665                         /* Setup buffer head to point to correct block. */
666                         bh->b_blocknr = ((lcn << vol->cluster_size_bits) +
667                                         vcn_ofs) >> blocksize_bits;
668                         set_buffer_mapped(bh);
669                         continue;
670                 }
671                 /* It is a hole, need to instantiate it. */
672                 if (lcn == LCN_HOLE) {
673                         // TODO: Instantiate the hole.
674                         // clear_buffer_new(bh);
675                         // unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
676                         ntfs_error(vol->sb, "Writing into sparse regions is "
677                                         "not supported yet. Sorry.");
678                         err = -EOPNOTSUPP;
679                         break;
680                 }
681                 /* If first try and runlist unmapped, map and retry. */
682                 if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
683                         is_retry = TRUE;
684                         /*
685                          * Attempt to map runlist, dropping lock for
686                          * the duration.
687                          */
688                         up_read(&ni->runlist.lock);
689                         err = ntfs_map_runlist(ni, vcn);
690                         if (likely(!err))
691                                 goto lock_retry_remap;
692                         rl = NULL;
693                         lcn = err;
694                 } else if (!rl)
695                         up_read(&ni->runlist.lock);
696                 /* Failed to map the buffer, even after retrying. */
697                 bh->b_blocknr = -1;
698                 ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
699                                 "attribute type 0x%x, vcn 0x%llx, offset 0x%x "
700                                 "because its location on disk could not be "
701                                 "determined%s (error code %lli).", ni->mft_no,
702                                 ni->type, (unsigned long long)vcn,
703                                 vcn_ofs, is_retry ? " even after "
704                                 "retrying" : "", (long long)lcn);
705                 if (!err)
706                         err = -EIO;
707                 break;
708         } while (block++, (bh = bh->b_this_page) != head);
709
710         /* Release the lock if we took it. */
711         if (rl)
712                 up_read(&ni->runlist.lock);
713
714         /* For the error case, need to reset bh to the beginning. */
715         bh = head;
716
717         /* Just an optimization, so ->readpage() isn't called later. */
718         if (unlikely(!PageUptodate(page))) {
719                 int uptodate = 1;
720                 do {
721                         if (!buffer_uptodate(bh)) {
722                                 uptodate = 0;
723                                 bh = head;
724                                 break;
725                         }
726                 } while ((bh = bh->b_this_page) != head);
727                 if (uptodate)
728                         SetPageUptodate(page);
729         }
730
731         /* Setup all mapped, dirty buffers for async write i/o. */
732         do {
733                 get_bh(bh);
734                 if (buffer_mapped(bh) && buffer_dirty(bh)) {
735                         lock_buffer(bh);
736                         if (test_clear_buffer_dirty(bh)) {
737                                 BUG_ON(!buffer_uptodate(bh));
738                                 mark_buffer_async_write(bh);
739                         } else
740                                 unlock_buffer(bh);
741                 } else if (unlikely(err)) {
742                         /*
743                          * For the error case. The buffer may have been set
744                          * dirty during attachment to a dirty page.
745                          */
746                         if (err != -ENOMEM)
747                                 clear_buffer_dirty(bh);
748                 }
749         } while ((bh = bh->b_this_page) != head);
750
751         if (unlikely(err)) {
752                 // TODO: Remove the -EOPNOTSUPP check later on...
753                 if (unlikely(err == -EOPNOTSUPP))
754                         err = 0;
755                 else if (err == -ENOMEM) {
756                         ntfs_warning(vol->sb, "Error allocating memory. "
757                                         "Redirtying page so we try again "
758                                         "later.");
759                         /*
760                          * Put the page back on mapping->dirty_pages, but
761                          * leave its buffer's dirty state as-is.
762                          */
763                         redirty_page_for_writepage(wbc, page);
764                         err = 0;
765                 } else
766                         SetPageError(page);
767         }
768
769         BUG_ON(PageWriteback(page));
770         set_page_writeback(page);       /* Keeps try_to_free_buffers() away. */
771         unlock_page(page);
772
773         /*
774          * Submit the prepared buffers for i/o. Note the page is unlocked,
775          * and the async write i/o completion handler can end_page_writeback()
776          * at any time after the *first* submit_bh(). So the buffers can then
777          * disappear...
778          */
779         need_end_writeback = TRUE;
780         do {
781                 struct buffer_head *next = bh->b_this_page;
782                 if (buffer_async_write(bh)) {
783                         submit_bh(WRITE, bh);
784                         need_end_writeback = FALSE;
785                 }
786                 put_bh(bh);
787                 bh = next;
788         } while (bh != head);
789
790         /* If no i/o was started, need to end_page_writeback(). */
791         if (unlikely(need_end_writeback))
792                 end_page_writeback(page);
793
794         ntfs_debug("Done.");
795         return err;
796 }
797
798 /**
799  * ntfs_write_mst_block - write a @page to the backing store
800  * @page:       page cache page to write out
801  * @wbc:        writeback control structure
802  *
803  * This function is for writing pages belonging to non-resident, mst protected
804  * attributes to their backing store.  The only supported attributes are index
805  * allocation and $MFT/$DATA.  Both directory inodes and index inodes are
806  * supported for the index allocation case.
807  *
808  * The page must remain locked for the duration of the write because we apply
809  * the mst fixups, write, and then undo the fixups, so if we were to unlock the
810  * page before undoing the fixups, any other user of the page will see the
811  * page contents as corrupt.
812  *
813  * We clear the page uptodate flag for the duration of the function to ensure
814  * exclusion for the $MFT/$DATA case against someone mapping an mft record we
815  * are about to apply the mst fixups to.
816  *
817  * Return 0 on success and -errno on error.
818  *
819  * Based on ntfs_write_block(), ntfs_mft_writepage(), and
820  * write_mft_record_nolock().
821  */
822 static int ntfs_write_mst_block(struct page *page,
823                 struct writeback_control *wbc)
824 {
825         sector_t block, dblock, rec_block;
826         struct inode *vi = page->mapping->host;
827         ntfs_inode *ni = NTFS_I(vi);
828         ntfs_volume *vol = ni->vol;
829         u8 *kaddr;
830         unsigned int rec_size = ni->itype.index.block_size;
831         ntfs_inode *locked_nis[PAGE_CACHE_SIZE / rec_size];
832         struct buffer_head *bh, *head, *tbh, *rec_start_bh;
833         struct buffer_head *bhs[MAX_BUF_PER_PAGE];
834         runlist_element *rl;
835         int i, nr_locked_nis, nr_recs, nr_bhs, max_bhs, bhs_per_rec, err, err2;
836         unsigned bh_size, rec_size_bits;
837         BOOL sync, is_mft, page_is_dirty, rec_is_dirty;
838         unsigned char bh_size_bits;
839
840         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
841                         "0x%lx.", vi->i_ino, ni->type, page->index);
842         BUG_ON(!NInoNonResident(ni));
843         BUG_ON(!NInoMstProtected(ni));
844         is_mft = (S_ISREG(vi->i_mode) && !vi->i_ino);
845         /*
846          * NOTE: ntfs_write_mst_block() would be called for $MFTMirr if a page
847          * in its page cache were to be marked dirty.  However this should
848          * never happen with the current driver and considering we do not
849          * handle this case here we do want to BUG(), at least for now.
850          */
851         BUG_ON(!(is_mft || S_ISDIR(vi->i_mode) ||
852                         (NInoAttr(ni) && ni->type == AT_INDEX_ALLOCATION)));
853         bh_size_bits = vi->i_blkbits;
854         bh_size = 1 << bh_size_bits;
855         max_bhs = PAGE_CACHE_SIZE / bh_size;
856         BUG_ON(!max_bhs);
857         BUG_ON(max_bhs > MAX_BUF_PER_PAGE);
858
859         /* Were we called for sync purposes? */
860         sync = (wbc->sync_mode == WB_SYNC_ALL);
861
862         /* Make sure we have mapped buffers. */
863         BUG_ON(!page_has_buffers(page));
864         bh = head = page_buffers(page);
865         BUG_ON(!bh);
866
867         rec_size_bits = ni->itype.index.block_size_bits;
868         BUG_ON(!(PAGE_CACHE_SIZE >> rec_size_bits));
869         bhs_per_rec = rec_size >> bh_size_bits;
870         BUG_ON(!bhs_per_rec);
871
872         /* The first block in the page. */
873         rec_block = block = (sector_t)page->index <<
874                         (PAGE_CACHE_SHIFT - bh_size_bits);
875
876         /* The first out of bounds block for the data size. */
877         dblock = (i_size_read(vi) + bh_size - 1) >> bh_size_bits;
878
879         rl = NULL;
880         err = err2 = nr_bhs = nr_recs = nr_locked_nis = 0;
881         page_is_dirty = rec_is_dirty = FALSE;
882         rec_start_bh = NULL;
883         do {
884                 BOOL is_retry = FALSE;
885
886                 if (likely(block < rec_block)) {
887                         if (unlikely(block >= dblock)) {
888                                 clear_buffer_dirty(bh);
889                                 set_buffer_uptodate(bh);
890                                 continue;
891                         }
892                         /*
893                          * This block is not the first one in the record.  We
894                          * ignore the buffer's dirty state because we could
895                          * have raced with a parallel mark_ntfs_record_dirty().
896                          */
897                         if (!rec_is_dirty)
898                                 continue;
899                         if (unlikely(err2)) {
900                                 if (err2 != -ENOMEM)
901                                         clear_buffer_dirty(bh);
902                                 continue;
903                         }
904                 } else /* if (block == rec_block) */ {
905                         BUG_ON(block > rec_block);
906                         /* This block is the first one in the record. */
907                         rec_block += bhs_per_rec;
908                         err2 = 0;
909                         if (unlikely(block >= dblock)) {
910                                 clear_buffer_dirty(bh);
911                                 continue;
912                         }
913                         if (!buffer_dirty(bh)) {
914                                 /* Clean records are not written out. */
915                                 rec_is_dirty = FALSE;
916                                 continue;
917                         }
918                         rec_is_dirty = TRUE;
919                         rec_start_bh = bh;
920                 }
921                 /* Need to map the buffer if it is not mapped already. */
922                 if (unlikely(!buffer_mapped(bh))) {
923                         VCN vcn;
924                         LCN lcn;
925                         unsigned int vcn_ofs;
926
927                         bh->b_bdev = vol->sb->s_bdev;
928                         /* Obtain the vcn and offset of the current block. */
929                         vcn = (VCN)block << bh_size_bits;
930                         vcn_ofs = vcn & vol->cluster_size_mask;
931                         vcn >>= vol->cluster_size_bits;
932                         if (!rl) {
933 lock_retry_remap:
934                                 down_read(&ni->runlist.lock);
935                                 rl = ni->runlist.rl;
936                         }
937                         if (likely(rl != NULL)) {
938                                 /* Seek to element containing target vcn. */
939                                 while (rl->length && rl[1].vcn <= vcn)
940                                         rl++;
941                                 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
942                         } else
943                                 lcn = LCN_RL_NOT_MAPPED;
944                         /* Successful remap. */
945                         if (likely(lcn >= 0)) {
946                                 /* Setup buffer head to correct block. */
947                                 bh->b_blocknr = ((lcn <<
948                                                 vol->cluster_size_bits) +
949                                                 vcn_ofs) >> bh_size_bits;
950                                 set_buffer_mapped(bh);
951                         } else {
952                                 /*
953                                  * Remap failed.  Retry to map the runlist once
954                                  * unless we are working on $MFT which always
955                                  * has the whole of its runlist in memory.
956                                  */
957                                 if (!is_mft && !is_retry &&
958                                                 lcn == LCN_RL_NOT_MAPPED) {
959                                         is_retry = TRUE;
960                                         /*
961                                          * Attempt to map runlist, dropping
962                                          * lock for the duration.
963                                          */
964                                         up_read(&ni->runlist.lock);
965                                         err2 = ntfs_map_runlist(ni, vcn);
966                                         if (likely(!err2))
967                                                 goto lock_retry_remap;
968                                         if (err2 == -ENOMEM)
969                                                 page_is_dirty = TRUE;
970                                         lcn = err2;
971                                 } else {
972                                         err2 = -EIO;
973                                         if (!rl)
974                                                 up_read(&ni->runlist.lock);
975                                 }
976                                 /* Hard error.  Abort writing this record. */
977                                 if (!err || err == -ENOMEM)
978                                         err = err2;
979                                 bh->b_blocknr = -1;
980                                 ntfs_error(vol->sb, "Cannot write ntfs record "
981                                                 "0x%llx (inode 0x%lx, "
982                                                 "attribute type 0x%x) because "
983                                                 "its location on disk could "
984                                                 "not be determined (error "
985                                                 "code %lli).",
986                                                 (long long)block <<
987                                                 bh_size_bits >>
988                                                 vol->mft_record_size_bits,
989                                                 ni->mft_no, ni->type,
990                                                 (long long)lcn);
991                                 /*
992                                  * If this is not the first buffer, remove the
993                                  * buffers in this record from the list of
994                                  * buffers to write and clear their dirty bit
995                                  * if not error -ENOMEM.
996                                  */
997                                 if (rec_start_bh != bh) {
998                                         while (bhs[--nr_bhs] != rec_start_bh)
999                                                 ;
1000                                         if (err2 != -ENOMEM) {
1001                                                 do {
1002                                                         clear_buffer_dirty(
1003                                                                 rec_start_bh);
1004                                                 } while ((rec_start_bh =
1005                                                                 rec_start_bh->
1006                                                                 b_this_page) !=
1007                                                                 bh);
1008                                         }
1009                                 }
1010                                 continue;
1011                         }
1012                 }
1013                 BUG_ON(!buffer_uptodate(bh));
1014                 BUG_ON(nr_bhs >= max_bhs);
1015                 bhs[nr_bhs++] = bh;
1016         } while (block++, (bh = bh->b_this_page) != head);
1017         if (unlikely(rl))
1018                 up_read(&ni->runlist.lock);
1019         /* If there were no dirty buffers, we are done. */
1020         if (!nr_bhs)
1021                 goto done;
1022         /* Map the page so we can access its contents. */
1023         kaddr = kmap(page);
1024         /* Clear the page uptodate flag whilst the mst fixups are applied. */
1025         BUG_ON(!PageUptodate(page));
1026         ClearPageUptodate(page);
1027         for (i = 0; i < nr_bhs; i++) {
1028                 unsigned int ofs;
1029
1030                 /* Skip buffers which are not at the beginning of records. */
1031                 if (i % bhs_per_rec)
1032                         continue;
1033                 tbh = bhs[i];
1034                 ofs = bh_offset(tbh);
1035                 if (is_mft) {
1036                         ntfs_inode *tni;
1037                         unsigned long mft_no;
1038
1039                         /* Get the mft record number. */
1040                         mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1041                                         >> rec_size_bits;
1042                         /* Check whether to write this mft record. */
1043                         tni = NULL;
1044                         if (!ntfs_may_write_mft_record(vol, mft_no,
1045                                         (MFT_RECORD*)(kaddr + ofs), &tni)) {
1046                                 /*
1047                                  * The record should not be written.  This
1048                                  * means we need to redirty the page before
1049                                  * returning.
1050                                  */
1051                                 page_is_dirty = TRUE;
1052                                 /*
1053                                  * Remove the buffers in this mft record from
1054                                  * the list of buffers to write.
1055                                  */
1056                                 do {
1057                                         bhs[i] = NULL;
1058                                 } while (++i % bhs_per_rec);
1059                                 continue;
1060                         }
1061                         /*
1062                          * The record should be written.  If a locked ntfs
1063                          * inode was returned, add it to the array of locked
1064                          * ntfs inodes.
1065                          */
1066                         if (tni)
1067                                 locked_nis[nr_locked_nis++] = tni;
1068                 }
1069                 /* Apply the mst protection fixups. */
1070                 err2 = pre_write_mst_fixup((NTFS_RECORD*)(kaddr + ofs),
1071                                 rec_size);
1072                 if (unlikely(err2)) {
1073                         if (!err || err == -ENOMEM)
1074                                 err = -EIO;
1075                         ntfs_error(vol->sb, "Failed to apply mst fixups "
1076                                         "(inode 0x%lx, attribute type 0x%x, "
1077                                         "page index 0x%lx, page offset 0x%x)!"
1078                                         "  Unmount and run chkdsk.", vi->i_ino,
1079                                         ni->type, page->index, ofs);
1080                         /*
1081                          * Mark all the buffers in this record clean as we do
1082                          * not want to write corrupt data to disk.
1083                          */
1084                         do {
1085                                 clear_buffer_dirty(bhs[i]);
1086                                 bhs[i] = NULL;
1087                         } while (++i % bhs_per_rec);
1088                         continue;
1089                 }
1090                 nr_recs++;
1091         }
1092         /* If no records are to be written out, we are done. */
1093         if (!nr_recs)
1094                 goto unm_done;
1095         flush_dcache_page(page);
1096         /* Lock buffers and start synchronous write i/o on them. */
1097         for (i = 0; i < nr_bhs; i++) {
1098                 tbh = bhs[i];
1099                 if (!tbh)
1100                         continue;
1101                 if (unlikely(test_set_buffer_locked(tbh)))
1102                         BUG();
1103                 /* The buffer dirty state is now irrelevant, just clean it. */
1104                 clear_buffer_dirty(tbh);
1105                 BUG_ON(!buffer_uptodate(tbh));
1106                 BUG_ON(!buffer_mapped(tbh));
1107                 get_bh(tbh);
1108                 tbh->b_end_io = end_buffer_write_sync;
1109                 submit_bh(WRITE, tbh);
1110         }
1111         /* Synchronize the mft mirror now if not @sync. */
1112         if (is_mft && !sync)
1113                 goto do_mirror;
1114 do_wait:
1115         /* Wait on i/o completion of buffers. */
1116         for (i = 0; i < nr_bhs; i++) {
1117                 tbh = bhs[i];
1118                 if (!tbh)
1119                         continue;
1120                 wait_on_buffer(tbh);
1121                 if (unlikely(!buffer_uptodate(tbh))) {
1122                         ntfs_error(vol->sb, "I/O error while writing ntfs "
1123                                         "record buffer (inode 0x%lx, "
1124                                         "attribute type 0x%x, page index "
1125                                         "0x%lx, page offset 0x%lx)!  Unmount "
1126                                         "and run chkdsk.", vi->i_ino, ni->type,
1127                                         page->index, bh_offset(tbh));
1128                         if (!err || err == -ENOMEM)
1129                                 err = -EIO;
1130                         /*
1131                          * Set the buffer uptodate so the page and buffer
1132                          * states do not become out of sync.
1133                          */
1134                         set_buffer_uptodate(tbh);
1135                 }
1136         }
1137         /* If @sync, now synchronize the mft mirror. */
1138         if (is_mft && sync) {
1139 do_mirror:
1140                 for (i = 0; i < nr_bhs; i++) {
1141                         unsigned long mft_no;
1142                         unsigned int ofs;
1143
1144                         /*
1145                          * Skip buffers which are not at the beginning of
1146                          * records.
1147                          */
1148                         if (i % bhs_per_rec)
1149                                 continue;
1150                         tbh = bhs[i];
1151                         /* Skip removed buffers (and hence records). */
1152                         if (!tbh)
1153                                 continue;
1154                         ofs = bh_offset(tbh);
1155                         /* Get the mft record number. */
1156                         mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1157                                         >> rec_size_bits;
1158                         if (mft_no < vol->mftmirr_size)
1159                                 ntfs_sync_mft_mirror(vol, mft_no,
1160                                                 (MFT_RECORD*)(kaddr + ofs),
1161                                                 sync);
1162                 }
1163                 if (!sync)
1164                         goto do_wait;
1165         }
1166         /* Remove the mst protection fixups again. */
1167         for (i = 0; i < nr_bhs; i++) {
1168                 if (!(i % bhs_per_rec)) {
1169                         tbh = bhs[i];
1170                         if (!tbh)
1171                                 continue;
1172                         post_write_mst_fixup((NTFS_RECORD*)(kaddr +
1173                                         bh_offset(tbh)));
1174                 }
1175         }
1176         flush_dcache_page(page);
1177 unm_done:
1178         /* Unlock any locked inodes. */
1179         while (nr_locked_nis-- > 0) {
1180                 ntfs_inode *tni, *base_tni;
1181                 
1182                 tni = locked_nis[nr_locked_nis];
1183                 /* Get the base inode. */
1184                 down(&tni->extent_lock);
1185                 if (tni->nr_extents >= 0)
1186                         base_tni = tni;
1187                 else {
1188                         base_tni = tni->ext.base_ntfs_ino;
1189                         BUG_ON(!base_tni);
1190                 }
1191                 up(&tni->extent_lock);
1192                 ntfs_debug("Unlocking %s inode 0x%lx.",
1193                                 tni == base_tni ? "base" : "extent",
1194                                 tni->mft_no);
1195                 up(&tni->mrec_lock);
1196                 atomic_dec(&tni->count);
1197                 iput(VFS_I(base_tni));
1198         }
1199         SetPageUptodate(page);
1200         kunmap(page);
1201 done:
1202         if (unlikely(err && err != -ENOMEM)) {
1203                 /*
1204                  * Set page error if there is only one ntfs record in the page.
1205                  * Otherwise we would loose per-record granularity.
1206                  */
1207                 if (ni->itype.index.block_size == PAGE_CACHE_SIZE)
1208                         SetPageError(page);
1209                 NVolSetErrors(vol);
1210         }
1211         if (page_is_dirty) {
1212                 ntfs_debug("Page still contains one or more dirty ntfs "
1213                                 "records.  Redirtying the page starting at "
1214                                 "record 0x%lx.", page->index <<
1215                                 (PAGE_CACHE_SHIFT - rec_size_bits));
1216                 redirty_page_for_writepage(wbc, page);
1217                 unlock_page(page);
1218         } else {
1219                 /*
1220                  * Keep the VM happy.  This must be done otherwise the
1221                  * radix-tree tag PAGECACHE_TAG_DIRTY remains set even though
1222                  * the page is clean.
1223                  */
1224                 BUG_ON(PageWriteback(page));
1225                 set_page_writeback(page);
1226                 unlock_page(page);
1227                 end_page_writeback(page);
1228         }
1229         if (likely(!err))
1230                 ntfs_debug("Done.");
1231         return err;
1232 }
1233
1234 /**
1235  * ntfs_writepage - write a @page to the backing store
1236  * @page:       page cache page to write out
1237  * @wbc:        writeback control structure
1238  *
1239  * This is called from the VM when it wants to have a dirty ntfs page cache
1240  * page cleaned.  The VM has already locked the page and marked it clean.
1241  *
1242  * For non-resident attributes, ntfs_writepage() writes the @page by calling
1243  * the ntfs version of the generic block_write_full_page() function,
1244  * ntfs_write_block(), which in turn if necessary creates and writes the
1245  * buffers associated with the page asynchronously.
1246  *
1247  * For resident attributes, OTOH, ntfs_writepage() writes the @page by copying
1248  * the data to the mft record (which at this stage is most likely in memory).
1249  * The mft record is then marked dirty and written out asynchronously via the
1250  * vfs inode dirty code path for the inode the mft record belongs to or via the
1251  * vm page dirty code path for the page the mft record is in.
1252  *
1253  * Based on ntfs_readpage() and fs/buffer.c::block_write_full_page().
1254  *
1255  * Return 0 on success and -errno on error.
1256  */
1257 static int ntfs_writepage(struct page *page, struct writeback_control *wbc)
1258 {
1259         loff_t i_size;
1260         struct inode *vi = page->mapping->host;
1261         ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1262         char *kaddr;
1263         ntfs_attr_search_ctx *ctx = NULL;
1264         MFT_RECORD *m = NULL;
1265         u32 attr_len;
1266         int err;
1267
1268 retry_writepage:
1269         BUG_ON(!PageLocked(page));
1270         i_size = i_size_read(vi);
1271         /* Is the page fully outside i_size? (truncate in progress) */
1272         if (unlikely(page->index >= (i_size + PAGE_CACHE_SIZE - 1) >>
1273                         PAGE_CACHE_SHIFT)) {
1274                 /*
1275                  * The page may have dirty, unmapped buffers.  Make them
1276                  * freeable here, so the page does not leak.
1277                  */
1278                 block_invalidatepage(page, 0);
1279                 unlock_page(page);
1280                 ntfs_debug("Write outside i_size - truncated?");
1281                 return 0;
1282         }
1283         /* NInoNonResident() == NInoIndexAllocPresent() */
1284         if (NInoNonResident(ni)) {
1285                 /*
1286                  * Only unnamed $DATA attributes can be compressed, encrypted,
1287                  * and/or sparse.
1288                  */
1289                 if (ni->type == AT_DATA && !ni->name_len) {
1290                         /* If file is encrypted, deny access, just like NT4. */
1291                         if (NInoEncrypted(ni)) {
1292                                 unlock_page(page);
1293                                 ntfs_debug("Denying write access to encrypted "
1294                                                 "file.");
1295                                 return -EACCES;
1296                         }
1297                         /* Compressed data streams are handled in compress.c. */
1298                         if (NInoCompressed(ni)) {
1299                                 // TODO: Implement and replace this check with
1300                                 // return ntfs_write_compressed_block(page);
1301                                 unlock_page(page);
1302                                 ntfs_error(vi->i_sb, "Writing to compressed "
1303                                                 "files is not supported yet. "
1304                                                 "Sorry.");
1305                                 return -EOPNOTSUPP;
1306                         }
1307                         // TODO: Implement and remove this check.
1308                         if (NInoSparse(ni)) {
1309                                 unlock_page(page);
1310                                 ntfs_error(vi->i_sb, "Writing to sparse files "
1311                                                 "is not supported yet. Sorry.");
1312                                 return -EOPNOTSUPP;
1313                         }
1314                 }
1315                 /* We have to zero every time due to mmap-at-end-of-file. */
1316                 if (page->index >= (i_size >> PAGE_CACHE_SHIFT)) {
1317                         /* The page straddles i_size. */
1318                         unsigned int ofs = i_size & ~PAGE_CACHE_MASK;
1319                         kaddr = kmap_atomic(page, KM_USER0);
1320                         memset(kaddr + ofs, 0, PAGE_CACHE_SIZE - ofs);
1321                         flush_dcache_page(page);
1322                         kunmap_atomic(kaddr, KM_USER0);
1323                 }
1324                 /* Handle mst protected attributes. */
1325                 if (NInoMstProtected(ni))
1326                         return ntfs_write_mst_block(page, wbc);
1327                 /* Normal data stream. */
1328                 return ntfs_write_block(page, wbc);
1329         }
1330         /*
1331          * Attribute is resident, implying it is not compressed, encrypted,
1332          * sparse, or mst protected.  This also means the attribute is smaller
1333          * than an mft record and hence smaller than a page, so can simply
1334          * return error on any pages with index above 0.
1335          */
1336         BUG_ON(page_has_buffers(page));
1337         BUG_ON(!PageUptodate(page));
1338         if (unlikely(page->index > 0)) {
1339                 ntfs_error(vi->i_sb, "BUG()! page->index (0x%lx) > 0.  "
1340                                 "Aborting write.", page->index);
1341                 BUG_ON(PageWriteback(page));
1342                 set_page_writeback(page);
1343                 unlock_page(page);
1344                 end_page_writeback(page);
1345                 return -EIO;
1346         }
1347         if (!NInoAttr(ni))
1348                 base_ni = ni;
1349         else
1350                 base_ni = ni->ext.base_ntfs_ino;
1351         /* Map, pin, and lock the mft record. */
1352         m = map_mft_record(base_ni);
1353         if (IS_ERR(m)) {
1354                 err = PTR_ERR(m);
1355                 m = NULL;
1356                 ctx = NULL;
1357                 goto err_out;
1358         }
1359         /*
1360          * If a parallel write made the attribute non-resident, drop the mft
1361          * record and retry the writepage.
1362          */
1363         if (unlikely(NInoNonResident(ni))) {
1364                 unmap_mft_record(base_ni);
1365                 goto retry_writepage;
1366         }
1367         ctx = ntfs_attr_get_search_ctx(base_ni, m);
1368         if (unlikely(!ctx)) {
1369                 err = -ENOMEM;
1370                 goto err_out;
1371         }
1372         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1373                         CASE_SENSITIVE, 0, NULL, 0, ctx);
1374         if (unlikely(err))
1375                 goto err_out;
1376         /*
1377          * Keep the VM happy.  This must be done otherwise the radix-tree tag
1378          * PAGECACHE_TAG_DIRTY remains set even though the page is clean.
1379          */
1380         BUG_ON(PageWriteback(page));
1381         set_page_writeback(page);
1382         unlock_page(page);
1383
1384         /*
1385          * Here, we don't need to zero the out of bounds area everytime because
1386          * the below memcpy() already takes care of the mmap-at-end-of-file
1387          * requirements. If the file is converted to a non-resident one, then
1388          * the code path use is switched to the non-resident one where the
1389          * zeroing happens on each ntfs_writepage() invocation.
1390          *
1391          * The above also applies nicely when i_size is decreased.
1392          *
1393          * When i_size is increased, the memory between the old and new i_size
1394          * _must_ be zeroed (or overwritten with new data). Otherwise we will
1395          * expose data to userspace/disk which should never have been exposed.
1396          *
1397          * FIXME: Ensure that i_size increases do the zeroing/overwriting and
1398          * if we cannot guarantee that, then enable the zeroing below.  If the
1399          * zeroing below is enabled, we MUST move the unlock_page() from above
1400          * to after the kunmap_atomic(), i.e. just before the
1401          * end_page_writeback().
1402          * UPDATE: ntfs_prepare/commit_write() do the zeroing on i_size
1403          * increases for resident attributes so those are ok.
1404          * TODO: ntfs_truncate(), others?
1405          */
1406
1407         attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
1408         i_size = i_size_read(vi);
1409         if (unlikely(attr_len > i_size)) {
1410                 attr_len = i_size;
1411                 ctx->attr->data.resident.value_length = cpu_to_le32(attr_len);
1412         }
1413         kaddr = kmap_atomic(page, KM_USER0);
1414         /* Copy the data from the page to the mft record. */
1415         memcpy((u8*)ctx->attr +
1416                         le16_to_cpu(ctx->attr->data.resident.value_offset),
1417                         kaddr, attr_len);
1418         flush_dcache_mft_record_page(ctx->ntfs_ino);
1419         /* Zero out of bounds area in the page cache page. */
1420         memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
1421         flush_dcache_page(page);
1422         kunmap_atomic(kaddr, KM_USER0);
1423
1424         end_page_writeback(page);
1425
1426         /* Mark the mft record dirty, so it gets written back. */
1427         mark_mft_record_dirty(ctx->ntfs_ino);
1428         ntfs_attr_put_search_ctx(ctx);
1429         unmap_mft_record(base_ni);
1430         return 0;
1431 err_out:
1432         if (err == -ENOMEM) {
1433                 ntfs_warning(vi->i_sb, "Error allocating memory. Redirtying "
1434                                 "page so we try again later.");
1435                 /*
1436                  * Put the page back on mapping->dirty_pages, but leave its
1437                  * buffers' dirty state as-is.
1438                  */
1439                 redirty_page_for_writepage(wbc, page);
1440                 err = 0;
1441         } else {
1442                 ntfs_error(vi->i_sb, "Resident attribute write failed with "
1443                                 "error %i.", err);
1444                 SetPageError(page);
1445                 NVolSetErrors(ni->vol);
1446                 make_bad_inode(vi);
1447         }
1448         unlock_page(page);
1449         if (ctx)
1450                 ntfs_attr_put_search_ctx(ctx);
1451         if (m)
1452                 unmap_mft_record(base_ni);
1453         return err;
1454 }
1455
1456 /**
1457  * ntfs_prepare_nonresident_write -
1458  *
1459  */
1460 static int ntfs_prepare_nonresident_write(struct page *page,
1461                 unsigned from, unsigned to)
1462 {
1463         VCN vcn;
1464         LCN lcn;
1465         s64 initialized_size;
1466         loff_t i_size;
1467         sector_t block, ablock, iblock;
1468         struct inode *vi;
1469         ntfs_inode *ni;
1470         ntfs_volume *vol;
1471         runlist_element *rl;
1472         struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
1473         unsigned long flags;
1474         unsigned int vcn_ofs, block_start, block_end, blocksize;
1475         int err;
1476         BOOL is_retry;
1477         unsigned char blocksize_bits;
1478
1479         vi = page->mapping->host;
1480         ni = NTFS_I(vi);
1481         vol = ni->vol;
1482
1483         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1484                         "0x%lx, from = %u, to = %u.", ni->mft_no, ni->type,
1485                         page->index, from, to);
1486
1487         BUG_ON(!NInoNonResident(ni));
1488
1489         blocksize_bits = vi->i_blkbits;
1490         blocksize = 1 << blocksize_bits;
1491
1492         /*
1493          * create_empty_buffers() will create uptodate/dirty buffers if the
1494          * page is uptodate/dirty.
1495          */
1496         if (!page_has_buffers(page))
1497                 create_empty_buffers(page, blocksize, 0);
1498         bh = head = page_buffers(page);
1499         if (unlikely(!bh))
1500                 return -ENOMEM;
1501
1502         /* The first block in the page. */
1503         block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
1504
1505         read_lock_irqsave(&ni->size_lock, flags);
1506         /*
1507          * The first out of bounds block for the allocated size.  No need to
1508          * round up as allocated_size is in multiples of cluster size and the
1509          * minimum cluster size is 512 bytes, which is equal to the smallest
1510          * blocksize.
1511          */
1512         ablock = ni->allocated_size >> blocksize_bits;
1513         i_size = i_size_read(vi);
1514         initialized_size = ni->initialized_size;
1515         read_unlock_irqrestore(&ni->size_lock, flags);
1516
1517         /* The last (fully or partially) initialized block. */
1518         iblock = initialized_size >> blocksize_bits;
1519
1520         /* Loop through all the buffers in the page. */
1521         block_start = 0;
1522         rl = NULL;
1523         err = 0;
1524         do {
1525                 block_end = block_start + blocksize;
1526                 /*
1527                  * If buffer @bh is outside the write, just mark it uptodate
1528                  * if the page is uptodate and continue with the next buffer.
1529                  */
1530                 if (block_end <= from || block_start >= to) {
1531                         if (PageUptodate(page)) {
1532                                 if (!buffer_uptodate(bh))
1533                                         set_buffer_uptodate(bh);
1534                         }
1535                         continue;
1536                 }
1537                 /*
1538                  * @bh is at least partially being written to.
1539                  * Make sure it is not marked as new.
1540                  */
1541                 //if (buffer_new(bh))
1542                 //      clear_buffer_new(bh);
1543
1544                 if (block >= ablock) {
1545                         // TODO: block is above allocated_size, need to
1546                         // allocate it. Best done in one go to accommodate not
1547                         // only block but all above blocks up to and including:
1548                         // ((page->index << PAGE_CACHE_SHIFT) + to + blocksize
1549                         // - 1) >> blobksize_bits. Obviously will need to round
1550                         // up to next cluster boundary, too. This should be
1551                         // done with a helper function, so it can be reused.
1552                         ntfs_error(vol->sb, "Writing beyond allocated size "
1553                                         "is not supported yet. Sorry.");
1554                         err = -EOPNOTSUPP;
1555                         goto err_out;
1556                         // Need to update ablock.
1557                         // Need to set_buffer_new() on all block bhs that are
1558                         // newly allocated.
1559                 }
1560                 /*
1561                  * Now we have enough allocated size to fulfill the whole
1562                  * request, i.e. block < ablock is true.
1563                  */
1564                 if (unlikely((block >= iblock) &&
1565                                 (initialized_size < i_size))) {
1566                         /*
1567                          * If this page is fully outside initialized size, zero
1568                          * out all pages between the current initialized size
1569                          * and the current page. Just use ntfs_readpage() to do
1570                          * the zeroing transparently.
1571                          */
1572                         if (block > iblock) {
1573                                 // TODO:
1574                                 // For each page do:
1575                                 // - read_cache_page()
1576                                 // Again for each page do:
1577                                 // - wait_on_page_locked()
1578                                 // - Check (PageUptodate(page) &&
1579                                 //                      !PageError(page))
1580                                 // Update initialized size in the attribute and
1581                                 // in the inode.
1582                                 // Again, for each page do:
1583                                 //      __set_page_dirty_buffers();
1584                                 // page_cache_release()
1585                                 // We don't need to wait on the writes.
1586                                 // Update iblock.
1587                         }
1588                         /*
1589                          * The current page straddles initialized size. Zero
1590                          * all non-uptodate buffers and set them uptodate (and
1591                          * dirty?). Note, there aren't any non-uptodate buffers
1592                          * if the page is uptodate.
1593                          * FIXME: For an uptodate page, the buffers may need to
1594                          * be written out because they were not initialized on
1595                          * disk before.
1596                          */
1597                         if (!PageUptodate(page)) {
1598                                 // TODO:
1599                                 // Zero any non-uptodate buffers up to i_size.
1600                                 // Set them uptodate and dirty.
1601                         }
1602                         // TODO:
1603                         // Update initialized size in the attribute and in the
1604                         // inode (up to i_size).
1605                         // Update iblock.
1606                         // FIXME: This is inefficient. Try to batch the two
1607                         // size changes to happen in one go.
1608                         ntfs_error(vol->sb, "Writing beyond initialized size "
1609                                         "is not supported yet. Sorry.");
1610                         err = -EOPNOTSUPP;
1611                         goto err_out;
1612                         // Do NOT set_buffer_new() BUT DO clear buffer range
1613                         // outside write request range.
1614                         // set_buffer_uptodate() on complete buffers as well as
1615                         // set_buffer_dirty().
1616                 }
1617
1618                 /* Need to map unmapped buffers. */
1619                 if (!buffer_mapped(bh)) {
1620                         /* Unmapped buffer. Need to map it. */
1621                         bh->b_bdev = vol->sb->s_bdev;
1622
1623                         /* Convert block into corresponding vcn and offset. */
1624                         vcn = (VCN)block << blocksize_bits >>
1625                                         vol->cluster_size_bits;
1626                         vcn_ofs = ((VCN)block << blocksize_bits) &
1627                                         vol->cluster_size_mask;
1628
1629                         is_retry = FALSE;
1630                         if (!rl) {
1631 lock_retry_remap:
1632                                 down_read(&ni->runlist.lock);
1633                                 rl = ni->runlist.rl;
1634                         }
1635                         if (likely(rl != NULL)) {
1636                                 /* Seek to element containing target vcn. */
1637                                 while (rl->length && rl[1].vcn <= vcn)
1638                                         rl++;
1639                                 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
1640                         } else
1641                                 lcn = LCN_RL_NOT_MAPPED;
1642                         if (unlikely(lcn < 0)) {
1643                                 /*
1644                                  * We extended the attribute allocation above.
1645                                  * If we hit an ENOENT here it means that the
1646                                  * allocation was insufficient which is a bug.
1647                                  */
1648                                 BUG_ON(lcn == LCN_ENOENT);
1649
1650                                 /* It is a hole, need to instantiate it. */
1651                                 if (lcn == LCN_HOLE) {
1652                                         // TODO: Instantiate the hole.
1653                                         // clear_buffer_new(bh);
1654                                         // unmap_underlying_metadata(bh->b_bdev,
1655                                         //              bh->b_blocknr);
1656                                         // For non-uptodate buffers, need to
1657                                         // zero out the region outside the
1658                                         // request in this bh or all bhs,
1659                                         // depending on what we implemented
1660                                         // above.
1661                                         // Need to flush_dcache_page().
1662                                         // Or could use set_buffer_new()
1663                                         // instead?
1664                                         ntfs_error(vol->sb, "Writing into "
1665                                                         "sparse regions is "
1666                                                         "not supported yet. "
1667                                                         "Sorry.");
1668                                         err = -EOPNOTSUPP;
1669                                         if (!rl)
1670                                                 up_read(&ni->runlist.lock);
1671                                         goto err_out;
1672                                 } else if (!is_retry &&
1673                                                 lcn == LCN_RL_NOT_MAPPED) {
1674                                         is_retry = TRUE;
1675                                         /*
1676                                          * Attempt to map runlist, dropping
1677                                          * lock for the duration.
1678                                          */
1679                                         up_read(&ni->runlist.lock);
1680                                         err = ntfs_map_runlist(ni, vcn);
1681                                         if (likely(!err))
1682                                                 goto lock_retry_remap;
1683                                         rl = NULL;
1684                                         lcn = err;
1685                                 } else if (!rl)
1686                                         up_read(&ni->runlist.lock);
1687                                 /*
1688                                  * Failed to map the buffer, even after
1689                                  * retrying.
1690                                  */
1691                                 bh->b_blocknr = -1;
1692                                 ntfs_error(vol->sb, "Failed to write to inode "
1693                                                 "0x%lx, attribute type 0x%x, "
1694                                                 "vcn 0x%llx, offset 0x%x "
1695                                                 "because its location on disk "
1696                                                 "could not be determined%s "
1697                                                 "(error code %lli).",
1698                                                 ni->mft_no, ni->type,
1699                                                 (unsigned long long)vcn,
1700                                                 vcn_ofs, is_retry ? " even "
1701                                                 "after retrying" : "",
1702                                                 (long long)lcn);
1703                                 if (!err)
1704                                         err = -EIO;
1705                                 goto err_out;
1706                         }
1707                         /* We now have a successful remap, i.e. lcn >= 0. */
1708
1709                         /* Setup buffer head to correct block. */
1710                         bh->b_blocknr = ((lcn << vol->cluster_size_bits)
1711                                         + vcn_ofs) >> blocksize_bits;
1712                         set_buffer_mapped(bh);
1713
1714                         // FIXME: Something analogous to this is needed for
1715                         // each newly allocated block, i.e. BH_New.
1716                         // FIXME: Might need to take this out of the
1717                         // if (!buffer_mapped(bh)) {}, depending on how we
1718                         // implement things during the allocated_size and
1719                         // initialized_size extension code above.
1720                         if (buffer_new(bh)) {
1721                                 clear_buffer_new(bh);
1722                                 unmap_underlying_metadata(bh->b_bdev,
1723                                                 bh->b_blocknr);
1724                                 if (PageUptodate(page)) {
1725                                         set_buffer_uptodate(bh);
1726                                         continue;
1727                                 }
1728                                 /*
1729                                  * Page is _not_ uptodate, zero surrounding
1730                                  * region. NOTE: This is how we decide if to
1731                                  * zero or not!
1732                                  */
1733                                 if (block_end > to || block_start < from) {
1734                                         void *kaddr;
1735
1736                                         kaddr = kmap_atomic(page, KM_USER0);
1737                                         if (block_end > to)
1738                                                 memset(kaddr + to, 0,
1739                                                                 block_end - to);
1740                                         if (block_start < from)
1741                                                 memset(kaddr + block_start, 0,
1742                                                                 from -
1743                                                                 block_start);
1744                                         flush_dcache_page(page);
1745                                         kunmap_atomic(kaddr, KM_USER0);
1746                                 }
1747                                 continue;
1748                         }
1749                 }
1750                 /* @bh is mapped, set it uptodate if the page is uptodate. */
1751                 if (PageUptodate(page)) {
1752                         if (!buffer_uptodate(bh))
1753                                 set_buffer_uptodate(bh);
1754                         continue;
1755                 }
1756                 /*
1757                  * The page is not uptodate. The buffer is mapped. If it is not
1758                  * uptodate, and it is only partially being written to, we need
1759                  * to read the buffer in before the write, i.e. right now.
1760                  */
1761                 if (!buffer_uptodate(bh) &&
1762                                 (block_start < from || block_end > to)) {
1763                         ll_rw_block(READ, 1, &bh);
1764                         *wait_bh++ = bh;
1765                 }
1766         } while (block++, block_start = block_end,
1767                         (bh = bh->b_this_page) != head);
1768
1769         /* Release the lock if we took it. */
1770         if (rl) {
1771                 up_read(&ni->runlist.lock);
1772                 rl = NULL;
1773         }
1774
1775         /* If we issued read requests, let them complete. */
1776         while (wait_bh > wait) {
1777                 wait_on_buffer(*--wait_bh);
1778                 if (!buffer_uptodate(*wait_bh))
1779                         return -EIO;
1780         }
1781
1782         ntfs_debug("Done.");
1783         return 0;
1784 err_out:
1785         /*
1786          * Zero out any newly allocated blocks to avoid exposing stale data.
1787          * If BH_New is set, we know that the block was newly allocated in the
1788          * above loop.
1789          * FIXME: What about initialized_size increments? Have we done all the
1790          * required zeroing above? If not this error handling is broken, and
1791          * in particular the if (block_end <= from) check is completely bogus.
1792          */
1793         bh = head;
1794         block_start = 0;
1795         is_retry = FALSE;
1796         do {
1797                 block_end = block_start + blocksize;
1798                 if (block_end <= from)
1799                         continue;
1800                 if (block_start >= to)
1801                         break;
1802                 if (buffer_new(bh)) {
1803                         void *kaddr;
1804
1805                         clear_buffer_new(bh);
1806                         kaddr = kmap_atomic(page, KM_USER0);
1807                         memset(kaddr + block_start, 0, bh->b_size);
1808                         kunmap_atomic(kaddr, KM_USER0);
1809                         set_buffer_uptodate(bh);
1810                         mark_buffer_dirty(bh);
1811                         is_retry = TRUE;
1812                 }
1813         } while (block_start = block_end, (bh = bh->b_this_page) != head);
1814         if (is_retry)
1815                 flush_dcache_page(page);
1816         if (rl)
1817                 up_read(&ni->runlist.lock);
1818         return err;
1819 }
1820
1821 /**
1822  * ntfs_prepare_write - prepare a page for receiving data
1823  *
1824  * This is called from generic_file_write() with i_sem held on the inode
1825  * (@page->mapping->host).  The @page is locked but not kmap()ped.  The source
1826  * data has not yet been copied into the @page.
1827  *
1828  * Need to extend the attribute/fill in holes if necessary, create blocks and
1829  * make partially overwritten blocks uptodate,
1830  *
1831  * i_size is not to be modified yet.
1832  *
1833  * Return 0 on success or -errno on error.
1834  *
1835  * Should be using block_prepare_write() [support for sparse files] or
1836  * cont_prepare_write() [no support for sparse files].  Cannot do that due to
1837  * ntfs specifics but can look at them for implementation guidance.
1838  *
1839  * Note: In the range, @from is inclusive and @to is exclusive, i.e. @from is
1840  * the first byte in the page that will be written to and @to is the first byte
1841  * after the last byte that will be written to.
1842  */
1843 static int ntfs_prepare_write(struct file *file, struct page *page,
1844                 unsigned from, unsigned to)
1845 {
1846         s64 new_size;
1847         loff_t i_size;
1848         struct inode *vi = page->mapping->host;
1849         ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1850         ntfs_volume *vol = ni->vol;
1851         ntfs_attr_search_ctx *ctx = NULL;
1852         MFT_RECORD *m = NULL;
1853         ATTR_RECORD *a;
1854         u8 *kaddr;
1855         u32 attr_len;
1856         int err;
1857
1858         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1859                         "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
1860                         page->index, from, to);
1861         BUG_ON(!PageLocked(page));
1862         BUG_ON(from > PAGE_CACHE_SIZE);
1863         BUG_ON(to > PAGE_CACHE_SIZE);
1864         BUG_ON(from > to);
1865         BUG_ON(NInoMstProtected(ni));
1866         /*
1867          * If a previous ntfs_truncate() failed, repeat it and abort if it
1868          * fails again.
1869          */
1870         if (unlikely(NInoTruncateFailed(ni))) {
1871                 down_write(&vi->i_alloc_sem);
1872                 err = ntfs_truncate(vi);
1873                 up_write(&vi->i_alloc_sem);
1874                 if (err || NInoTruncateFailed(ni)) {
1875                         if (!err)
1876                                 err = -EIO;
1877                         goto err_out;
1878                 }
1879         }
1880         /* If the attribute is not resident, deal with it elsewhere. */
1881         if (NInoNonResident(ni)) {
1882                 /*
1883                  * Only unnamed $DATA attributes can be compressed, encrypted,
1884                  * and/or sparse.
1885                  */
1886                 if (ni->type == AT_DATA && !ni->name_len) {
1887                         /* If file is encrypted, deny access, just like NT4. */
1888                         if (NInoEncrypted(ni)) {
1889                                 ntfs_debug("Denying write access to encrypted "
1890                                                 "file.");
1891                                 return -EACCES;
1892                         }
1893                         /* Compressed data streams are handled in compress.c. */
1894                         if (NInoCompressed(ni)) {
1895                                 // TODO: Implement and replace this check with
1896                                 // return ntfs_write_compressed_block(page);
1897                                 ntfs_error(vi->i_sb, "Writing to compressed "
1898                                                 "files is not supported yet. "
1899                                                 "Sorry.");
1900                                 return -EOPNOTSUPP;
1901                         }
1902                         // TODO: Implement and remove this check.
1903                         if (NInoSparse(ni)) {
1904                                 ntfs_error(vi->i_sb, "Writing to sparse files "
1905                                                 "is not supported yet. Sorry.");
1906                                 return -EOPNOTSUPP;
1907                         }
1908                 }
1909                 /* Normal data stream. */
1910                 return ntfs_prepare_nonresident_write(page, from, to);
1911         }
1912         /*
1913          * Attribute is resident, implying it is not compressed, encrypted, or
1914          * sparse.
1915          */
1916         BUG_ON(page_has_buffers(page));
1917         new_size = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
1918         /* If we do not need to resize the attribute allocation we are done. */
1919         if (new_size <= i_size_read(vi))
1920                 goto done;
1921         /* Map, pin, and lock the (base) mft record. */
1922         if (!NInoAttr(ni))
1923                 base_ni = ni;
1924         else
1925                 base_ni = ni->ext.base_ntfs_ino;
1926         m = map_mft_record(base_ni);
1927         if (IS_ERR(m)) {
1928                 err = PTR_ERR(m);
1929                 m = NULL;
1930                 ctx = NULL;
1931                 goto err_out;
1932         }
1933         ctx = ntfs_attr_get_search_ctx(base_ni, m);
1934         if (unlikely(!ctx)) {
1935                 err = -ENOMEM;
1936                 goto err_out;
1937         }
1938         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1939                         CASE_SENSITIVE, 0, NULL, 0, ctx);
1940         if (unlikely(err)) {
1941                 if (err == -ENOENT)
1942                         err = -EIO;
1943                 goto err_out;
1944         }
1945         m = ctx->mrec;
1946         a = ctx->attr;
1947         /* The total length of the attribute value. */
1948         attr_len = le32_to_cpu(a->data.resident.value_length);
1949         /* Fix an eventual previous failure of ntfs_commit_write(). */
1950         i_size = i_size_read(vi);
1951         if (unlikely(attr_len > i_size)) {
1952                 attr_len = i_size;
1953                 a->data.resident.value_length = cpu_to_le32(attr_len);
1954         }
1955         /* If we do not need to resize the attribute allocation we are done. */
1956         if (new_size <= attr_len)
1957                 goto done_unm;
1958         /* Check if new size is allowed in $AttrDef. */
1959         err = ntfs_attr_size_bounds_check(vol, ni->type, new_size);
1960         if (unlikely(err)) {
1961                 if (err == -ERANGE) {
1962                         ntfs_error(vol->sb, "Write would cause the inode "
1963                                         "0x%lx to exceed the maximum size for "
1964                                         "its attribute type (0x%x).  Aborting "
1965                                         "write.", vi->i_ino,
1966                                         le32_to_cpu(ni->type));
1967                 } else {
1968                         ntfs_error(vol->sb, "Inode 0x%lx has unknown "
1969                                         "attribute type 0x%x.  Aborting "
1970                                         "write.", vi->i_ino,
1971                                         le32_to_cpu(ni->type));
1972                         err = -EIO;
1973                 }
1974                 goto err_out2;
1975         }
1976         /*
1977          * Extend the attribute record to be able to store the new attribute
1978          * size.
1979          */
1980         if (new_size >= vol->mft_record_size || ntfs_attr_record_resize(m, a,
1981                         le16_to_cpu(a->data.resident.value_offset) +
1982                         new_size)) {
1983                 /* Not enough space in the mft record. */
1984                 ntfs_error(vol->sb, "Not enough space in the mft record for "
1985                                 "the resized attribute value.  This is not "
1986                                 "supported yet.  Aborting write.");
1987                 err = -EOPNOTSUPP;
1988                 goto err_out2;
1989         }
1990         /*
1991          * We have enough space in the mft record to fit the write.  This
1992          * implies the attribute is smaller than the mft record and hence the
1993          * attribute must be in a single page and hence page->index must be 0.
1994          */
1995         BUG_ON(page->index);
1996         /*
1997          * If the beginning of the write is past the old size, enlarge the
1998          * attribute value up to the beginning of the write and fill it with
1999          * zeroes.
2000          */
2001         if (from > attr_len) {
2002                 memset((u8*)a + le16_to_cpu(a->data.resident.value_offset) +
2003                                 attr_len, 0, from - attr_len);
2004                 a->data.resident.value_length = cpu_to_le32(from);
2005                 /* Zero the corresponding area in the page as well. */
2006                 if (PageUptodate(page)) {
2007                         kaddr = kmap_atomic(page, KM_USER0);
2008                         memset(kaddr + attr_len, 0, from - attr_len);
2009                         kunmap_atomic(kaddr, KM_USER0);
2010                         flush_dcache_page(page);
2011                 }
2012         }
2013         flush_dcache_mft_record_page(ctx->ntfs_ino);
2014         mark_mft_record_dirty(ctx->ntfs_ino);
2015 done_unm:
2016         ntfs_attr_put_search_ctx(ctx);
2017         unmap_mft_record(base_ni);
2018         /*
2019          * Because resident attributes are handled by memcpy() to/from the
2020          * corresponding MFT record, and because this form of i/o is byte
2021          * aligned rather than block aligned, there is no need to bring the
2022          * page uptodate here as in the non-resident case where we need to
2023          * bring the buffers straddled by the write uptodate before
2024          * generic_file_write() does the copying from userspace.
2025          *
2026          * We thus defer the uptodate bringing of the page region outside the
2027          * region written to to ntfs_commit_write(), which makes the code
2028          * simpler and saves one atomic kmap which is good.
2029          */
2030 done:
2031         ntfs_debug("Done.");
2032         return 0;
2033 err_out:
2034         if (err == -ENOMEM)
2035                 ntfs_warning(vi->i_sb, "Error allocating memory required to "
2036                                 "prepare the write.");
2037         else {
2038                 ntfs_error(vi->i_sb, "Resident attribute prepare write failed "
2039                                 "with error %i.", err);
2040                 NVolSetErrors(vol);
2041                 make_bad_inode(vi);
2042         }
2043 err_out2:
2044         if (ctx)
2045                 ntfs_attr_put_search_ctx(ctx);
2046         if (m)
2047                 unmap_mft_record(base_ni);
2048         return err;
2049 }
2050
2051 /**
2052  * ntfs_commit_nonresident_write -
2053  *
2054  */
2055 static int ntfs_commit_nonresident_write(struct page *page,
2056                 unsigned from, unsigned to)
2057 {
2058         s64 pos = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
2059         struct inode *vi = page->mapping->host;
2060         struct buffer_head *bh, *head;
2061         unsigned int block_start, block_end, blocksize;
2062         BOOL partial;
2063
2064         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
2065                         "0x%lx, from = %u, to = %u.", vi->i_ino,
2066                         NTFS_I(vi)->type, page->index, from, to);
2067         blocksize = 1 << vi->i_blkbits;
2068
2069         // FIXME: We need a whole slew of special cases in here for compressed
2070         // files for example...
2071         // For now, we know ntfs_prepare_write() would have failed so we can't
2072         // get here in any of the cases which we have to special case, so we
2073         // are just a ripped off, unrolled generic_commit_write().
2074
2075         bh = head = page_buffers(page);
2076         block_start = 0;
2077         partial = FALSE;
2078         do {
2079                 block_end = block_start + blocksize;
2080                 if (block_end <= from || block_start >= to) {
2081                         if (!buffer_uptodate(bh))
2082                                 partial = TRUE;
2083                 } else {
2084                         set_buffer_uptodate(bh);
2085                         mark_buffer_dirty(bh);
2086                 }
2087         } while (block_start = block_end, (bh = bh->b_this_page) != head);
2088         /*
2089          * If this is a partial write which happened to make all buffers
2090          * uptodate then we can optimize away a bogus ->readpage() for the next
2091          * read().  Here we 'discover' whether the page went uptodate as a
2092          * result of this (potentially partial) write.
2093          */
2094         if (!partial)
2095                 SetPageUptodate(page);
2096         /*
2097          * Not convinced about this at all.  See disparity comment above.  For
2098          * now we know ntfs_prepare_write() would have failed in the write
2099          * exceeds i_size case, so this will never trigger which is fine.
2100          */
2101         if (pos > i_size_read(vi)) {
2102                 ntfs_error(vi->i_sb, "Writing beyond the existing file size is "
2103                                 "not supported yet.  Sorry.");
2104                 return -EOPNOTSUPP;
2105                 // vi->i_size = pos;
2106                 // mark_inode_dirty(vi);
2107         }
2108         ntfs_debug("Done.");
2109         return 0;
2110 }
2111
2112 /**
2113  * ntfs_commit_write - commit the received data
2114  *
2115  * This is called from generic_file_write() with i_sem held on the inode
2116  * (@page->mapping->host).  The @page is locked but not kmap()ped.  The source
2117  * data has already been copied into the @page.  ntfs_prepare_write() has been
2118  * called before the data copied and it returned success so we can take the
2119  * results of various BUG checks and some error handling for granted.
2120  *
2121  * Need to mark modified blocks dirty so they get written out later when
2122  * ntfs_writepage() is invoked by the VM.
2123  *
2124  * Return 0 on success or -errno on error.
2125  *
2126  * Should be using generic_commit_write().  This marks buffers uptodate and
2127  * dirty, sets the page uptodate if all buffers in the page are uptodate, and
2128  * updates i_size if the end of io is beyond i_size.  In that case, it also
2129  * marks the inode dirty.
2130  *
2131  * Cannot use generic_commit_write() due to ntfs specialities but can look at
2132  * it for implementation guidance.
2133  *
2134  * If things have gone as outlined in ntfs_prepare_write(), then we do not
2135  * need to do any page content modifications here at all, except in the write
2136  * to resident attribute case, where we need to do the uptodate bringing here
2137  * which we combine with the copying into the mft record which means we save
2138  * one atomic kmap.
2139  */
2140 static int ntfs_commit_write(struct file *file, struct page *page,
2141                 unsigned from, unsigned to)
2142 {
2143         struct inode *vi = page->mapping->host;
2144         ntfs_inode *base_ni, *ni = NTFS_I(vi);
2145         char *kaddr, *kattr;
2146         ntfs_attr_search_ctx *ctx;
2147         MFT_RECORD *m;
2148         ATTR_RECORD *a;
2149         u32 attr_len;
2150         int err;
2151
2152         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
2153                         "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
2154                         page->index, from, to);
2155         /* If the attribute is not resident, deal with it elsewhere. */
2156         if (NInoNonResident(ni)) {
2157                 /* Only unnamed $DATA attributes can be compressed/encrypted. */
2158                 if (ni->type == AT_DATA && !ni->name_len) {
2159                         /* Encrypted files need separate handling. */
2160                         if (NInoEncrypted(ni)) {
2161                                 // We never get here at present!
2162                                 BUG();
2163                         }
2164                         /* Compressed data streams are handled in compress.c. */
2165                         if (NInoCompressed(ni)) {
2166                                 // TODO: Implement this!
2167                                 // return ntfs_write_compressed_block(page);
2168                                 // We never get here at present!
2169                                 BUG();
2170                         }
2171                 }
2172                 /* Normal data stream. */
2173                 return ntfs_commit_nonresident_write(page, from, to);
2174         }
2175         /*
2176          * Attribute is resident, implying it is not compressed, encrypted, or
2177          * sparse.
2178          */
2179         if (!NInoAttr(ni))
2180                 base_ni = ni;
2181         else
2182                 base_ni = ni->ext.base_ntfs_ino;
2183         /* Map, pin, and lock the mft record. */
2184         m = map_mft_record(base_ni);
2185         if (IS_ERR(m)) {
2186                 err = PTR_ERR(m);
2187                 m = NULL;
2188                 ctx = NULL;
2189                 goto err_out;
2190         }
2191         ctx = ntfs_attr_get_search_ctx(base_ni, m);
2192         if (unlikely(!ctx)) {
2193                 err = -ENOMEM;
2194                 goto err_out;
2195         }
2196         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2197                         CASE_SENSITIVE, 0, NULL, 0, ctx);
2198         if (unlikely(err)) {
2199                 if (err == -ENOENT)
2200                         err = -EIO;
2201                 goto err_out;
2202         }
2203         a = ctx->attr;
2204         /* The total length of the attribute value. */
2205         attr_len = le32_to_cpu(a->data.resident.value_length);
2206         BUG_ON(from > attr_len);
2207         kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
2208         kaddr = kmap_atomic(page, KM_USER0);
2209         /* Copy the received data from the page to the mft record. */
2210         memcpy(kattr + from, kaddr + from, to - from);
2211         /* Update the attribute length if necessary. */
2212         if (to > attr_len) {
2213                 attr_len = to;
2214                 a->data.resident.value_length = cpu_to_le32(attr_len);
2215         }
2216         /*
2217          * If the page is not uptodate, bring the out of bounds area(s)
2218          * uptodate by copying data from the mft record to the page.
2219          */
2220         if (!PageUptodate(page)) {
2221                 if (from > 0)
2222                         memcpy(kaddr, kattr, from);
2223                 if (to < attr_len)
2224                         memcpy(kaddr + to, kattr + to, attr_len - to);
2225                 /* Zero the region outside the end of the attribute value. */
2226                 if (attr_len < PAGE_CACHE_SIZE)
2227                         memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
2228                 /*
2229                  * The probability of not having done any of the above is
2230                  * extremely small, so we just flush unconditionally.
2231                  */
2232                 flush_dcache_page(page);
2233                 SetPageUptodate(page);
2234         }
2235         kunmap_atomic(kaddr, KM_USER0);
2236         /* Update i_size if necessary. */
2237         if (i_size_read(vi) < attr_len) {
2238                 unsigned long flags;
2239
2240                 write_lock_irqsave(&ni->size_lock, flags);
2241                 ni->allocated_size = ni->initialized_size = attr_len;
2242                 i_size_write(vi, attr_len);
2243                 write_unlock_irqrestore(&ni->size_lock, flags);
2244         }
2245         /* Mark the mft record dirty, so it gets written back. */
2246         flush_dcache_mft_record_page(ctx->ntfs_ino);
2247         mark_mft_record_dirty(ctx->ntfs_ino);
2248         ntfs_attr_put_search_ctx(ctx);
2249         unmap_mft_record(base_ni);
2250         ntfs_debug("Done.");
2251         return 0;
2252 err_out:
2253         if (err == -ENOMEM) {
2254                 ntfs_warning(vi->i_sb, "Error allocating memory required to "
2255                                 "commit the write.");
2256                 if (PageUptodate(page)) {
2257                         ntfs_warning(vi->i_sb, "Page is uptodate, setting "
2258                                         "dirty so the write will be retried "
2259                                         "later on by the VM.");
2260                         /*
2261                          * Put the page on mapping->dirty_pages, but leave its
2262                          * buffers' dirty state as-is.
2263                          */
2264                         __set_page_dirty_nobuffers(page);
2265                         err = 0;
2266                 } else
2267                         ntfs_error(vi->i_sb, "Page is not uptodate.  Written "
2268                                         "data has been lost.");
2269         } else {
2270                 ntfs_error(vi->i_sb, "Resident attribute commit write failed "
2271                                 "with error %i.", err);
2272                 NVolSetErrors(ni->vol);
2273                 make_bad_inode(vi);
2274         }
2275         if (ctx)
2276                 ntfs_attr_put_search_ctx(ctx);
2277         if (m)
2278                 unmap_mft_record(base_ni);
2279         return err;
2280 }
2281
2282 #endif  /* NTFS_RW */
2283
2284 /**
2285  * ntfs_aops - general address space operations for inodes and attributes
2286  */
2287 struct address_space_operations ntfs_aops = {
2288         .readpage       = ntfs_readpage,        /* Fill page with data. */
2289         .sync_page      = block_sync_page,      /* Currently, just unplugs the
2290                                                    disk request queue. */
2291 #ifdef NTFS_RW
2292         .writepage      = ntfs_writepage,       /* Write dirty page to disk. */
2293         .prepare_write  = ntfs_prepare_write,   /* Prepare page and buffers
2294                                                    ready to receive data. */
2295         .commit_write   = ntfs_commit_write,    /* Commit received data. */
2296 #endif /* NTFS_RW */
2297 };
2298
2299 /**
2300  * ntfs_mst_aops - general address space operations for mst protecteed inodes
2301  *                 and attributes
2302  */
2303 struct address_space_operations ntfs_mst_aops = {
2304         .readpage       = ntfs_readpage,        /* Fill page with data. */
2305         .sync_page      = block_sync_page,      /* Currently, just unplugs the
2306                                                    disk request queue. */
2307 #ifdef NTFS_RW
2308         .writepage      = ntfs_writepage,       /* Write dirty page to disk. */
2309         .set_page_dirty = __set_page_dirty_nobuffers,   /* Set the page dirty
2310                                                    without touching the buffers
2311                                                    belonging to the page. */
2312 #endif /* NTFS_RW */
2313 };
2314
2315 #ifdef NTFS_RW
2316
2317 /**
2318  * mark_ntfs_record_dirty - mark an ntfs record dirty
2319  * @page:       page containing the ntfs record to mark dirty
2320  * @ofs:        byte offset within @page at which the ntfs record begins
2321  *
2322  * Set the buffers and the page in which the ntfs record is located dirty.
2323  *
2324  * The latter also marks the vfs inode the ntfs record belongs to dirty
2325  * (I_DIRTY_PAGES only).
2326  *
2327  * If the page does not have buffers, we create them and set them uptodate.
2328  * The page may not be locked which is why we need to handle the buffers under
2329  * the mapping->private_lock.  Once the buffers are marked dirty we no longer
2330  * need the lock since try_to_free_buffers() does not free dirty buffers.
2331  */
2332 void mark_ntfs_record_dirty(struct page *page, const unsigned int ofs) {
2333         struct address_space *mapping = page->mapping;
2334         ntfs_inode *ni = NTFS_I(mapping->host);
2335         struct buffer_head *bh, *head, *buffers_to_free = NULL;
2336         unsigned int end, bh_size, bh_ofs;
2337
2338         BUG_ON(!PageUptodate(page));
2339         end = ofs + ni->itype.index.block_size;
2340         bh_size = 1 << VFS_I(ni)->i_blkbits;
2341         spin_lock(&mapping->private_lock);
2342         if (unlikely(!page_has_buffers(page))) {
2343                 spin_unlock(&mapping->private_lock);
2344                 bh = head = alloc_page_buffers(page, bh_size, 1);
2345                 spin_lock(&mapping->private_lock);
2346                 if (likely(!page_has_buffers(page))) {
2347                         struct buffer_head *tail;
2348
2349                         do {
2350                                 set_buffer_uptodate(bh);
2351                                 tail = bh;
2352                                 bh = bh->b_this_page;
2353                         } while (bh);
2354                         tail->b_this_page = head;
2355                         attach_page_buffers(page, head);
2356                 } else
2357                         buffers_to_free = bh;
2358         }
2359         bh = head = page_buffers(page);
2360         do {
2361                 bh_ofs = bh_offset(bh);
2362                 if (bh_ofs + bh_size <= ofs)
2363                         continue;
2364                 if (unlikely(bh_ofs >= end))
2365                         break;
2366                 set_buffer_dirty(bh);
2367         } while ((bh = bh->b_this_page) != head);
2368         spin_unlock(&mapping->private_lock);
2369         __set_page_dirty_nobuffers(page);
2370         if (unlikely(buffers_to_free)) {
2371                 do {
2372                         bh = buffers_to_free->b_this_page;
2373                         free_buffer_head(buffers_to_free);
2374                         buffers_to_free = bh;
2375                 } while (buffers_to_free);
2376         }
2377 }
2378
2379 #endif /* NTFS_RW */