xfs: factor our a helper to calculate the EOF alignment
[cascardo/linux.git] / fs / xfs / xfs_iomap.c
1 /*
2  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 #include <linux/iomap.h>
19 #include "xfs.h"
20 #include "xfs_fs.h"
21 #include "xfs_shared.h"
22 #include "xfs_format.h"
23 #include "xfs_log_format.h"
24 #include "xfs_trans_resv.h"
25 #include "xfs_mount.h"
26 #include "xfs_defer.h"
27 #include "xfs_inode.h"
28 #include "xfs_btree.h"
29 #include "xfs_bmap_btree.h"
30 #include "xfs_bmap.h"
31 #include "xfs_bmap_util.h"
32 #include "xfs_error.h"
33 #include "xfs_trans.h"
34 #include "xfs_trans_space.h"
35 #include "xfs_iomap.h"
36 #include "xfs_trace.h"
37 #include "xfs_icache.h"
38 #include "xfs_quota.h"
39 #include "xfs_dquot_item.h"
40 #include "xfs_dquot.h"
41
42
43 #define XFS_WRITEIO_ALIGN(mp,off)       (((off) >> mp->m_writeio_log) \
44                                                 << mp->m_writeio_log)
45 #define XFS_WRITE_IMAPS         XFS_BMAP_MAX_NMAP
46
47 void
48 xfs_bmbt_to_iomap(
49         struct xfs_inode        *ip,
50         struct iomap            *iomap,
51         struct xfs_bmbt_irec    *imap)
52 {
53         struct xfs_mount        *mp = ip->i_mount;
54
55         if (imap->br_startblock == HOLESTARTBLOCK) {
56                 iomap->blkno = IOMAP_NULL_BLOCK;
57                 iomap->type = IOMAP_HOLE;
58         } else if (imap->br_startblock == DELAYSTARTBLOCK) {
59                 iomap->blkno = IOMAP_NULL_BLOCK;
60                 iomap->type = IOMAP_DELALLOC;
61         } else {
62                 iomap->blkno = xfs_fsb_to_db(ip, imap->br_startblock);
63                 if (imap->br_state == XFS_EXT_UNWRITTEN)
64                         iomap->type = IOMAP_UNWRITTEN;
65                 else
66                         iomap->type = IOMAP_MAPPED;
67         }
68         iomap->offset = XFS_FSB_TO_B(mp, imap->br_startoff);
69         iomap->length = XFS_FSB_TO_B(mp, imap->br_blockcount);
70         iomap->bdev = xfs_find_bdev_for_inode(VFS_I(ip));
71 }
72
73 static xfs_extlen_t
74 xfs_eof_alignment(
75         struct xfs_inode        *ip,
76         xfs_extlen_t            extsize)
77 {
78         struct xfs_mount        *mp = ip->i_mount;
79         xfs_extlen_t            align = 0;
80
81         if (!XFS_IS_REALTIME_INODE(ip)) {
82                 /*
83                  * Round up the allocation request to a stripe unit
84                  * (m_dalign) boundary if the file size is >= stripe unit
85                  * size, and we are allocating past the allocation eof.
86                  *
87                  * If mounted with the "-o swalloc" option the alignment is
88                  * increased from the strip unit size to the stripe width.
89                  */
90                 if (mp->m_swidth && (mp->m_flags & XFS_MOUNT_SWALLOC))
91                         align = mp->m_swidth;
92                 else if (mp->m_dalign)
93                         align = mp->m_dalign;
94
95                 if (align && XFS_ISIZE(ip) < XFS_FSB_TO_B(mp, align))
96                         align = 0;
97         }
98
99         /*
100          * Always round up the allocation request to an extent boundary
101          * (when file on a real-time subvolume or has di_extsize hint).
102          */
103         if (extsize) {
104                 if (align)
105                         align = roundup_64(align, extsize);
106                 else
107                         align = extsize;
108         }
109
110         return align;
111 }
112
113 STATIC int
114 xfs_iomap_eof_align_last_fsb(
115         struct xfs_inode        *ip,
116         xfs_extlen_t            extsize,
117         xfs_fileoff_t           *last_fsb)
118 {
119         xfs_extlen_t            align = xfs_eof_alignment(ip, extsize);
120
121         if (align) {
122                 xfs_fileoff_t   new_last_fsb = roundup_64(*last_fsb, align);
123                 int             eof, error;
124
125                 error = xfs_bmap_eof(ip, new_last_fsb, XFS_DATA_FORK, &eof);
126                 if (error)
127                         return error;
128                 if (eof)
129                         *last_fsb = new_last_fsb;
130         }
131         return 0;
132 }
133
134 STATIC int
135 xfs_alert_fsblock_zero(
136         xfs_inode_t     *ip,
137         xfs_bmbt_irec_t *imap)
138 {
139         xfs_alert_tag(ip->i_mount, XFS_PTAG_FSBLOCK_ZERO,
140                         "Access to block zero in inode %llu "
141                         "start_block: %llx start_off: %llx "
142                         "blkcnt: %llx extent-state: %x",
143                 (unsigned long long)ip->i_ino,
144                 (unsigned long long)imap->br_startblock,
145                 (unsigned long long)imap->br_startoff,
146                 (unsigned long long)imap->br_blockcount,
147                 imap->br_state);
148         return -EFSCORRUPTED;
149 }
150
151 int
152 xfs_iomap_write_direct(
153         xfs_inode_t     *ip,
154         xfs_off_t       offset,
155         size_t          count,
156         xfs_bmbt_irec_t *imap,
157         int             nmaps)
158 {
159         xfs_mount_t     *mp = ip->i_mount;
160         xfs_fileoff_t   offset_fsb;
161         xfs_fileoff_t   last_fsb;
162         xfs_filblks_t   count_fsb, resaligned;
163         xfs_fsblock_t   firstfsb;
164         xfs_extlen_t    extsz, temp;
165         int             nimaps;
166         int             quota_flag;
167         int             rt;
168         xfs_trans_t     *tp;
169         struct xfs_defer_ops dfops;
170         uint            qblocks, resblks, resrtextents;
171         int             error;
172         int             lockmode;
173         int             bmapi_flags = XFS_BMAPI_PREALLOC;
174         uint            tflags = 0;
175
176         rt = XFS_IS_REALTIME_INODE(ip);
177         extsz = xfs_get_extsz_hint(ip);
178         lockmode = XFS_ILOCK_SHARED;    /* locked by caller */
179
180         ASSERT(xfs_isilocked(ip, lockmode));
181
182         offset_fsb = XFS_B_TO_FSBT(mp, offset);
183         last_fsb = XFS_B_TO_FSB(mp, ((xfs_ufsize_t)(offset + count)));
184         if ((offset + count) > XFS_ISIZE(ip)) {
185                 /*
186                  * Assert that the in-core extent list is present since this can
187                  * call xfs_iread_extents() and we only have the ilock shared.
188                  * This should be safe because the lock was held around a bmapi
189                  * call in the caller and we only need it to access the in-core
190                  * list.
191                  */
192                 ASSERT(XFS_IFORK_PTR(ip, XFS_DATA_FORK)->if_flags &
193                                                                 XFS_IFEXTENTS);
194                 error = xfs_iomap_eof_align_last_fsb(ip, extsz, &last_fsb);
195                 if (error)
196                         goto out_unlock;
197         } else {
198                 if (nmaps && (imap->br_startblock == HOLESTARTBLOCK))
199                         last_fsb = MIN(last_fsb, (xfs_fileoff_t)
200                                         imap->br_blockcount +
201                                         imap->br_startoff);
202         }
203         count_fsb = last_fsb - offset_fsb;
204         ASSERT(count_fsb > 0);
205
206         resaligned = count_fsb;
207         if (unlikely(extsz)) {
208                 if ((temp = do_mod(offset_fsb, extsz)))
209                         resaligned += temp;
210                 if ((temp = do_mod(resaligned, extsz)))
211                         resaligned += extsz - temp;
212         }
213
214         if (unlikely(rt)) {
215                 resrtextents = qblocks = resaligned;
216                 resrtextents /= mp->m_sb.sb_rextsize;
217                 resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
218                 quota_flag = XFS_QMOPT_RES_RTBLKS;
219         } else {
220                 resrtextents = 0;
221                 resblks = qblocks = XFS_DIOSTRAT_SPACE_RES(mp, resaligned);
222                 quota_flag = XFS_QMOPT_RES_REGBLKS;
223         }
224
225         /*
226          * Drop the shared lock acquired by the caller, attach the dquot if
227          * necessary and move on to transaction setup.
228          */
229         xfs_iunlock(ip, lockmode);
230         error = xfs_qm_dqattach(ip, 0);
231         if (error)
232                 return error;
233
234         /*
235          * For DAX, we do not allocate unwritten extents, but instead we zero
236          * the block before we commit the transaction.  Ideally we'd like to do
237          * this outside the transaction context, but if we commit and then crash
238          * we may not have zeroed the blocks and this will be exposed on
239          * recovery of the allocation. Hence we must zero before commit.
240          *
241          * Further, if we are mapping unwritten extents here, we need to zero
242          * and convert them to written so that we don't need an unwritten extent
243          * callback for DAX. This also means that we need to be able to dip into
244          * the reserve block pool for bmbt block allocation if there is no space
245          * left but we need to do unwritten extent conversion.
246          */
247         if (IS_DAX(VFS_I(ip))) {
248                 bmapi_flags = XFS_BMAPI_CONVERT | XFS_BMAPI_ZERO;
249                 if (ISUNWRITTEN(imap)) {
250                         tflags |= XFS_TRANS_RESERVE;
251                         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0) << 1;
252                 }
253         }
254         error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks, resrtextents,
255                         tflags, &tp);
256         if (error)
257                 return error;
258
259         lockmode = XFS_ILOCK_EXCL;
260         xfs_ilock(ip, lockmode);
261
262         error = xfs_trans_reserve_quota_nblks(tp, ip, qblocks, 0, quota_flag);
263         if (error)
264                 goto out_trans_cancel;
265
266         xfs_trans_ijoin(tp, ip, 0);
267
268         /*
269          * From this point onwards we overwrite the imap pointer that the
270          * caller gave to us.
271          */
272         xfs_defer_init(&dfops, &firstfsb);
273         nimaps = 1;
274         error = xfs_bmapi_write(tp, ip, offset_fsb, count_fsb,
275                                 bmapi_flags, &firstfsb, resblks, imap,
276                                 &nimaps, &dfops);
277         if (error)
278                 goto out_bmap_cancel;
279
280         /*
281          * Complete the transaction
282          */
283         error = xfs_defer_finish(&tp, &dfops, NULL);
284         if (error)
285                 goto out_bmap_cancel;
286
287         error = xfs_trans_commit(tp);
288         if (error)
289                 goto out_unlock;
290
291         /*
292          * Copy any maps to caller's array and return any error.
293          */
294         if (nimaps == 0) {
295                 error = -ENOSPC;
296                 goto out_unlock;
297         }
298
299         if (!(imap->br_startblock || XFS_IS_REALTIME_INODE(ip)))
300                 error = xfs_alert_fsblock_zero(ip, imap);
301
302 out_unlock:
303         xfs_iunlock(ip, lockmode);
304         return error;
305
306 out_bmap_cancel:
307         xfs_defer_cancel(&dfops);
308         xfs_trans_unreserve_quota_nblks(tp, ip, (long)qblocks, 0, quota_flag);
309 out_trans_cancel:
310         xfs_trans_cancel(tp);
311         goto out_unlock;
312 }
313
314 /*
315  * If the caller is doing a write at the end of the file, then extend the
316  * allocation out to the file system's write iosize.  We clean up any extra
317  * space left over when the file is closed in xfs_inactive().
318  *
319  * If we find we already have delalloc preallocation beyond EOF, don't do more
320  * preallocation as it it not needed.
321  */
322 STATIC int
323 xfs_iomap_eof_want_preallocate(
324         xfs_mount_t     *mp,
325         xfs_inode_t     *ip,
326         xfs_off_t       offset,
327         size_t          count,
328         xfs_bmbt_irec_t *imap,
329         int             nimaps,
330         int             *prealloc)
331 {
332         xfs_fileoff_t   start_fsb;
333         xfs_filblks_t   count_fsb;
334         int             n, error, imaps;
335         int             found_delalloc = 0;
336
337         *prealloc = 0;
338         if (offset + count <= XFS_ISIZE(ip))
339                 return 0;
340
341         /*
342          * If the file is smaller than the minimum prealloc and we are using
343          * dynamic preallocation, don't do any preallocation at all as it is
344          * likely this is the only write to the file that is going to be done.
345          */
346         if (!(mp->m_flags & XFS_MOUNT_DFLT_IOSIZE) &&
347             XFS_ISIZE(ip) < XFS_FSB_TO_B(mp, mp->m_writeio_blocks))
348                 return 0;
349
350         /*
351          * If there are any real blocks past eof, then don't
352          * do any speculative allocation.
353          */
354         start_fsb = XFS_B_TO_FSBT(mp, ((xfs_ufsize_t)(offset + count - 1)));
355         count_fsb = XFS_B_TO_FSB(mp, mp->m_super->s_maxbytes);
356         while (count_fsb > 0) {
357                 imaps = nimaps;
358                 error = xfs_bmapi_read(ip, start_fsb, count_fsb, imap, &imaps,
359                                        0);
360                 if (error)
361                         return error;
362                 for (n = 0; n < imaps; n++) {
363                         if ((imap[n].br_startblock != HOLESTARTBLOCK) &&
364                             (imap[n].br_startblock != DELAYSTARTBLOCK))
365                                 return 0;
366                         start_fsb += imap[n].br_blockcount;
367                         count_fsb -= imap[n].br_blockcount;
368
369                         if (imap[n].br_startblock == DELAYSTARTBLOCK)
370                                 found_delalloc = 1;
371                 }
372         }
373         if (!found_delalloc)
374                 *prealloc = 1;
375         return 0;
376 }
377
378 /*
379  * Determine the initial size of the preallocation. We are beyond the current
380  * EOF here, but we need to take into account whether this is a sparse write or
381  * an extending write when determining the preallocation size.  Hence we need to
382  * look up the extent that ends at the current write offset and use the result
383  * to determine the preallocation size.
384  *
385  * If the extent is a hole, then preallocation is essentially disabled.
386  * Otherwise we take the size of the preceeding data extent as the basis for the
387  * preallocation size. If the size of the extent is greater than half the
388  * maximum extent length, then use the current offset as the basis. This ensures
389  * that for large files the preallocation size always extends to MAXEXTLEN
390  * rather than falling short due to things like stripe unit/width alignment of
391  * real extents.
392  */
393 STATIC xfs_fsblock_t
394 xfs_iomap_eof_prealloc_initial_size(
395         struct xfs_mount        *mp,
396         struct xfs_inode        *ip,
397         xfs_off_t               offset,
398         xfs_bmbt_irec_t         *imap,
399         int                     nimaps)
400 {
401         xfs_fileoff_t   start_fsb;
402         int             imaps = 1;
403         int             error;
404
405         ASSERT(nimaps >= imaps);
406
407         /* if we are using a specific prealloc size, return now */
408         if (mp->m_flags & XFS_MOUNT_DFLT_IOSIZE)
409                 return 0;
410
411         /* If the file is small, then use the minimum prealloc */
412         if (XFS_ISIZE(ip) < XFS_FSB_TO_B(mp, mp->m_dalign))
413                 return 0;
414
415         /*
416          * As we write multiple pages, the offset will always align to the
417          * start of a page and hence point to a hole at EOF. i.e. if the size is
418          * 4096 bytes, we only have one block at FSB 0, but XFS_B_TO_FSB(4096)
419          * will return FSB 1. Hence if there are blocks in the file, we want to
420          * point to the block prior to the EOF block and not the hole that maps
421          * directly at @offset.
422          */
423         start_fsb = XFS_B_TO_FSB(mp, offset);
424         if (start_fsb)
425                 start_fsb--;
426         error = xfs_bmapi_read(ip, start_fsb, 1, imap, &imaps, XFS_BMAPI_ENTIRE);
427         if (error)
428                 return 0;
429
430         ASSERT(imaps == 1);
431         if (imap[0].br_startblock == HOLESTARTBLOCK)
432                 return 0;
433         if (imap[0].br_blockcount <= (MAXEXTLEN >> 1))
434                 return imap[0].br_blockcount << 1;
435         return XFS_B_TO_FSB(mp, offset);
436 }
437
438 STATIC bool
439 xfs_quota_need_throttle(
440         struct xfs_inode *ip,
441         int type,
442         xfs_fsblock_t alloc_blocks)
443 {
444         struct xfs_dquot *dq = xfs_inode_dquot(ip, type);
445
446         if (!dq || !xfs_this_quota_on(ip->i_mount, type))
447                 return false;
448
449         /* no hi watermark, no throttle */
450         if (!dq->q_prealloc_hi_wmark)
451                 return false;
452
453         /* under the lo watermark, no throttle */
454         if (dq->q_res_bcount + alloc_blocks < dq->q_prealloc_lo_wmark)
455                 return false;
456
457         return true;
458 }
459
460 STATIC void
461 xfs_quota_calc_throttle(
462         struct xfs_inode *ip,
463         int type,
464         xfs_fsblock_t *qblocks,
465         int *qshift,
466         int64_t *qfreesp)
467 {
468         int64_t freesp;
469         int shift = 0;
470         struct xfs_dquot *dq = xfs_inode_dquot(ip, type);
471
472         /* no dq, or over hi wmark, squash the prealloc completely */
473         if (!dq || dq->q_res_bcount >= dq->q_prealloc_hi_wmark) {
474                 *qblocks = 0;
475                 *qfreesp = 0;
476                 return;
477         }
478
479         freesp = dq->q_prealloc_hi_wmark - dq->q_res_bcount;
480         if (freesp < dq->q_low_space[XFS_QLOWSP_5_PCNT]) {
481                 shift = 2;
482                 if (freesp < dq->q_low_space[XFS_QLOWSP_3_PCNT])
483                         shift += 2;
484                 if (freesp < dq->q_low_space[XFS_QLOWSP_1_PCNT])
485                         shift += 2;
486         }
487
488         if (freesp < *qfreesp)
489                 *qfreesp = freesp;
490
491         /* only overwrite the throttle values if we are more aggressive */
492         if ((freesp >> shift) < (*qblocks >> *qshift)) {
493                 *qblocks = freesp;
494                 *qshift = shift;
495         }
496 }
497
498 /*
499  * If we don't have a user specified preallocation size, dynamically increase
500  * the preallocation size as the size of the file grows. Cap the maximum size
501  * at a single extent or less if the filesystem is near full. The closer the
502  * filesystem is to full, the smaller the maximum prealocation.
503  */
504 STATIC xfs_fsblock_t
505 xfs_iomap_prealloc_size(
506         struct xfs_mount        *mp,
507         struct xfs_inode        *ip,
508         xfs_off_t               offset,
509         struct xfs_bmbt_irec    *imap,
510         int                     nimaps)
511 {
512         xfs_fsblock_t           alloc_blocks = 0;
513         int                     shift = 0;
514         int64_t                 freesp;
515         xfs_fsblock_t           qblocks;
516         int                     qshift = 0;
517
518         alloc_blocks = xfs_iomap_eof_prealloc_initial_size(mp, ip, offset,
519                                                            imap, nimaps);
520         if (!alloc_blocks)
521                 goto check_writeio;
522         qblocks = alloc_blocks;
523
524         /*
525          * MAXEXTLEN is not a power of two value but we round the prealloc down
526          * to the nearest power of two value after throttling. To prevent the
527          * round down from unconditionally reducing the maximum supported prealloc
528          * size, we round up first, apply appropriate throttling, round down and
529          * cap the value to MAXEXTLEN.
530          */
531         alloc_blocks = XFS_FILEOFF_MIN(roundup_pow_of_two(MAXEXTLEN),
532                                        alloc_blocks);
533
534         freesp = percpu_counter_read_positive(&mp->m_fdblocks);
535         if (freesp < mp->m_low_space[XFS_LOWSP_5_PCNT]) {
536                 shift = 2;
537                 if (freesp < mp->m_low_space[XFS_LOWSP_4_PCNT])
538                         shift++;
539                 if (freesp < mp->m_low_space[XFS_LOWSP_3_PCNT])
540                         shift++;
541                 if (freesp < mp->m_low_space[XFS_LOWSP_2_PCNT])
542                         shift++;
543                 if (freesp < mp->m_low_space[XFS_LOWSP_1_PCNT])
544                         shift++;
545         }
546
547         /*
548          * Check each quota to cap the prealloc size, provide a shift value to
549          * throttle with and adjust amount of available space.
550          */
551         if (xfs_quota_need_throttle(ip, XFS_DQ_USER, alloc_blocks))
552                 xfs_quota_calc_throttle(ip, XFS_DQ_USER, &qblocks, &qshift,
553                                         &freesp);
554         if (xfs_quota_need_throttle(ip, XFS_DQ_GROUP, alloc_blocks))
555                 xfs_quota_calc_throttle(ip, XFS_DQ_GROUP, &qblocks, &qshift,
556                                         &freesp);
557         if (xfs_quota_need_throttle(ip, XFS_DQ_PROJ, alloc_blocks))
558                 xfs_quota_calc_throttle(ip, XFS_DQ_PROJ, &qblocks, &qshift,
559                                         &freesp);
560
561         /*
562          * The final prealloc size is set to the minimum of free space available
563          * in each of the quotas and the overall filesystem.
564          *
565          * The shift throttle value is set to the maximum value as determined by
566          * the global low free space values and per-quota low free space values.
567          */
568         alloc_blocks = MIN(alloc_blocks, qblocks);
569         shift = MAX(shift, qshift);
570
571         if (shift)
572                 alloc_blocks >>= shift;
573         /*
574          * rounddown_pow_of_two() returns an undefined result if we pass in
575          * alloc_blocks = 0.
576          */
577         if (alloc_blocks)
578                 alloc_blocks = rounddown_pow_of_two(alloc_blocks);
579         if (alloc_blocks > MAXEXTLEN)
580                 alloc_blocks = MAXEXTLEN;
581
582         /*
583          * If we are still trying to allocate more space than is
584          * available, squash the prealloc hard. This can happen if we
585          * have a large file on a small filesystem and the above
586          * lowspace thresholds are smaller than MAXEXTLEN.
587          */
588         while (alloc_blocks && alloc_blocks >= freesp)
589                 alloc_blocks >>= 4;
590
591 check_writeio:
592         if (alloc_blocks < mp->m_writeio_blocks)
593                 alloc_blocks = mp->m_writeio_blocks;
594
595         trace_xfs_iomap_prealloc_size(ip, alloc_blocks, shift,
596                                       mp->m_writeio_blocks);
597
598         return alloc_blocks;
599 }
600
601 int
602 xfs_iomap_write_delay(
603         xfs_inode_t     *ip,
604         xfs_off_t       offset,
605         size_t          count,
606         xfs_bmbt_irec_t *ret_imap)
607 {
608         xfs_mount_t     *mp = ip->i_mount;
609         xfs_fileoff_t   offset_fsb;
610         xfs_fileoff_t   last_fsb;
611         xfs_off_t       aligned_offset;
612         xfs_fileoff_t   ioalign;
613         xfs_extlen_t    extsz;
614         int             nimaps;
615         xfs_bmbt_irec_t imap[XFS_WRITE_IMAPS];
616         int             prealloc;
617         int             error;
618
619         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
620
621         /*
622          * Make sure that the dquots are there. This doesn't hold
623          * the ilock across a disk read.
624          */
625         error = xfs_qm_dqattach_locked(ip, 0);
626         if (error)
627                 return error;
628
629         extsz = xfs_get_extsz_hint(ip);
630         offset_fsb = XFS_B_TO_FSBT(mp, offset);
631
632         error = xfs_iomap_eof_want_preallocate(mp, ip, offset, count,
633                                 imap, XFS_WRITE_IMAPS, &prealloc);
634         if (error)
635                 return error;
636
637 retry:
638         if (prealloc) {
639                 xfs_fsblock_t   alloc_blocks;
640
641                 alloc_blocks = xfs_iomap_prealloc_size(mp, ip, offset, imap,
642                                                        XFS_WRITE_IMAPS);
643
644                 aligned_offset = XFS_WRITEIO_ALIGN(mp, (offset + count - 1));
645                 ioalign = XFS_B_TO_FSBT(mp, aligned_offset);
646                 last_fsb = ioalign + alloc_blocks;
647         } else {
648                 last_fsb = XFS_B_TO_FSB(mp, ((xfs_ufsize_t)(offset + count)));
649         }
650
651         if (prealloc || extsz) {
652                 error = xfs_iomap_eof_align_last_fsb(ip, extsz, &last_fsb);
653                 if (error)
654                         return error;
655         }
656
657         /*
658          * Make sure preallocation does not create extents beyond the range we
659          * actually support in this filesystem.
660          */
661         if (last_fsb > XFS_B_TO_FSB(mp, mp->m_super->s_maxbytes))
662                 last_fsb = XFS_B_TO_FSB(mp, mp->m_super->s_maxbytes);
663
664         ASSERT(last_fsb > offset_fsb);
665
666         nimaps = XFS_WRITE_IMAPS;
667         error = xfs_bmapi_delay(ip, offset_fsb, last_fsb - offset_fsb,
668                                 imap, &nimaps, XFS_BMAPI_ENTIRE);
669         switch (error) {
670         case 0:
671         case -ENOSPC:
672         case -EDQUOT:
673                 break;
674         default:
675                 return error;
676         }
677
678         /*
679          * If bmapi returned us nothing, we got either ENOSPC or EDQUOT. Retry
680          * without EOF preallocation.
681          */
682         if (nimaps == 0) {
683                 trace_xfs_delalloc_enospc(ip, offset, count);
684                 if (prealloc) {
685                         prealloc = 0;
686                         error = 0;
687                         goto retry;
688                 }
689                 return error ? error : -ENOSPC;
690         }
691
692         if (!(imap[0].br_startblock || XFS_IS_REALTIME_INODE(ip)))
693                 return xfs_alert_fsblock_zero(ip, &imap[0]);
694
695         /*
696          * Tag the inode as speculatively preallocated so we can reclaim this
697          * space on demand, if necessary.
698          */
699         if (prealloc)
700                 xfs_inode_set_eofblocks_tag(ip);
701
702         *ret_imap = imap[0];
703         return 0;
704 }
705
706 /*
707  * Pass in a delayed allocate extent, convert it to real extents;
708  * return to the caller the extent we create which maps on top of
709  * the originating callers request.
710  *
711  * Called without a lock on the inode.
712  *
713  * We no longer bother to look at the incoming map - all we have to
714  * guarantee is that whatever we allocate fills the required range.
715  */
716 int
717 xfs_iomap_write_allocate(
718         xfs_inode_t     *ip,
719         xfs_off_t       offset,
720         xfs_bmbt_irec_t *imap)
721 {
722         xfs_mount_t     *mp = ip->i_mount;
723         xfs_fileoff_t   offset_fsb, last_block;
724         xfs_fileoff_t   end_fsb, map_start_fsb;
725         xfs_fsblock_t   first_block;
726         struct xfs_defer_ops    dfops;
727         xfs_filblks_t   count_fsb;
728         xfs_trans_t     *tp;
729         int             nimaps;
730         int             error = 0;
731         int             nres;
732
733         /*
734          * Make sure that the dquots are there.
735          */
736         error = xfs_qm_dqattach(ip, 0);
737         if (error)
738                 return error;
739
740         offset_fsb = XFS_B_TO_FSBT(mp, offset);
741         count_fsb = imap->br_blockcount;
742         map_start_fsb = imap->br_startoff;
743
744         XFS_STATS_ADD(mp, xs_xstrat_bytes, XFS_FSB_TO_B(mp, count_fsb));
745
746         while (count_fsb != 0) {
747                 /*
748                  * Set up a transaction with which to allocate the
749                  * backing store for the file.  Do allocations in a
750                  * loop until we get some space in the range we are
751                  * interested in.  The other space that might be allocated
752                  * is in the delayed allocation extent on which we sit
753                  * but before our buffer starts.
754                  */
755                 nimaps = 0;
756                 while (nimaps == 0) {
757                         nres = XFS_EXTENTADD_SPACE_RES(mp, XFS_DATA_FORK);
758                         /*
759                          * We have already reserved space for the extent and any
760                          * indirect blocks when creating the delalloc extent,
761                          * there is no need to reserve space in this transaction
762                          * again.
763                          */
764                         error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, 0,
765                                         0, XFS_TRANS_RESERVE, &tp);
766                         if (error)
767                                 return error;
768
769                         xfs_ilock(ip, XFS_ILOCK_EXCL);
770                         xfs_trans_ijoin(tp, ip, 0);
771
772                         xfs_defer_init(&dfops, &first_block);
773
774                         /*
775                          * it is possible that the extents have changed since
776                          * we did the read call as we dropped the ilock for a
777                          * while. We have to be careful about truncates or hole
778                          * punchs here - we are not allowed to allocate
779                          * non-delalloc blocks here.
780                          *
781                          * The only protection against truncation is the pages
782                          * for the range we are being asked to convert are
783                          * locked and hence a truncate will block on them
784                          * first.
785                          *
786                          * As a result, if we go beyond the range we really
787                          * need and hit an delalloc extent boundary followed by
788                          * a hole while we have excess blocks in the map, we
789                          * will fill the hole incorrectly and overrun the
790                          * transaction reservation.
791                          *
792                          * Using a single map prevents this as we are forced to
793                          * check each map we look for overlap with the desired
794                          * range and abort as soon as we find it. Also, given
795                          * that we only return a single map, having one beyond
796                          * what we can return is probably a bit silly.
797                          *
798                          * We also need to check that we don't go beyond EOF;
799                          * this is a truncate optimisation as a truncate sets
800                          * the new file size before block on the pages we
801                          * currently have locked under writeback. Because they
802                          * are about to be tossed, we don't need to write them
803                          * back....
804                          */
805                         nimaps = 1;
806                         end_fsb = XFS_B_TO_FSB(mp, XFS_ISIZE(ip));
807                         error = xfs_bmap_last_offset(ip, &last_block,
808                                                         XFS_DATA_FORK);
809                         if (error)
810                                 goto trans_cancel;
811
812                         last_block = XFS_FILEOFF_MAX(last_block, end_fsb);
813                         if ((map_start_fsb + count_fsb) > last_block) {
814                                 count_fsb = last_block - map_start_fsb;
815                                 if (count_fsb == 0) {
816                                         error = -EAGAIN;
817                                         goto trans_cancel;
818                                 }
819                         }
820
821                         /*
822                          * From this point onwards we overwrite the imap
823                          * pointer that the caller gave to us.
824                          */
825                         error = xfs_bmapi_write(tp, ip, map_start_fsb,
826                                                 count_fsb, 0, &first_block,
827                                                 nres, imap, &nimaps,
828                                                 &dfops);
829                         if (error)
830                                 goto trans_cancel;
831
832                         error = xfs_defer_finish(&tp, &dfops, NULL);
833                         if (error)
834                                 goto trans_cancel;
835
836                         error = xfs_trans_commit(tp);
837                         if (error)
838                                 goto error0;
839
840                         xfs_iunlock(ip, XFS_ILOCK_EXCL);
841                 }
842
843                 /*
844                  * See if we were able to allocate an extent that
845                  * covers at least part of the callers request
846                  */
847                 if (!(imap->br_startblock || XFS_IS_REALTIME_INODE(ip)))
848                         return xfs_alert_fsblock_zero(ip, imap);
849
850                 if ((offset_fsb >= imap->br_startoff) &&
851                     (offset_fsb < (imap->br_startoff +
852                                    imap->br_blockcount))) {
853                         XFS_STATS_INC(mp, xs_xstrat_quick);
854                         return 0;
855                 }
856
857                 /*
858                  * So far we have not mapped the requested part of the
859                  * file, just surrounding data, try again.
860                  */
861                 count_fsb -= imap->br_blockcount;
862                 map_start_fsb = imap->br_startoff + imap->br_blockcount;
863         }
864
865 trans_cancel:
866         xfs_defer_cancel(&dfops);
867         xfs_trans_cancel(tp);
868 error0:
869         xfs_iunlock(ip, XFS_ILOCK_EXCL);
870         return error;
871 }
872
873 int
874 xfs_iomap_write_unwritten(
875         xfs_inode_t     *ip,
876         xfs_off_t       offset,
877         xfs_off_t       count)
878 {
879         xfs_mount_t     *mp = ip->i_mount;
880         xfs_fileoff_t   offset_fsb;
881         xfs_filblks_t   count_fsb;
882         xfs_filblks_t   numblks_fsb;
883         xfs_fsblock_t   firstfsb;
884         int             nimaps;
885         xfs_trans_t     *tp;
886         xfs_bmbt_irec_t imap;
887         struct xfs_defer_ops dfops;
888         xfs_fsize_t     i_size;
889         uint            resblks;
890         int             error;
891
892         trace_xfs_unwritten_convert(ip, offset, count);
893
894         offset_fsb = XFS_B_TO_FSBT(mp, offset);
895         count_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)offset + count);
896         count_fsb = (xfs_filblks_t)(count_fsb - offset_fsb);
897
898         /*
899          * Reserve enough blocks in this transaction for two complete extent
900          * btree splits.  We may be converting the middle part of an unwritten
901          * extent and in this case we will insert two new extents in the btree
902          * each of which could cause a full split.
903          *
904          * This reservation amount will be used in the first call to
905          * xfs_bmbt_split() to select an AG with enough space to satisfy the
906          * rest of the operation.
907          */
908         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0) << 1;
909
910         do {
911                 /*
912                  * Set up a transaction to convert the range of extents
913                  * from unwritten to real. Do allocations in a loop until
914                  * we have covered the range passed in.
915                  *
916                  * Note that we can't risk to recursing back into the filesystem
917                  * here as we might be asked to write out the same inode that we
918                  * complete here and might deadlock on the iolock.
919                  */
920                 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks, 0,
921                                 XFS_TRANS_RESERVE | XFS_TRANS_NOFS, &tp);
922                 if (error)
923                         return error;
924
925                 xfs_ilock(ip, XFS_ILOCK_EXCL);
926                 xfs_trans_ijoin(tp, ip, 0);
927
928                 /*
929                  * Modify the unwritten extent state of the buffer.
930                  */
931                 xfs_defer_init(&dfops, &firstfsb);
932                 nimaps = 1;
933                 error = xfs_bmapi_write(tp, ip, offset_fsb, count_fsb,
934                                         XFS_BMAPI_CONVERT, &firstfsb, resblks,
935                                         &imap, &nimaps, &dfops);
936                 if (error)
937                         goto error_on_bmapi_transaction;
938
939                 /*
940                  * Log the updated inode size as we go.  We have to be careful
941                  * to only log it up to the actual write offset if it is
942                  * halfway into a block.
943                  */
944                 i_size = XFS_FSB_TO_B(mp, offset_fsb + count_fsb);
945                 if (i_size > offset + count)
946                         i_size = offset + count;
947
948                 i_size = xfs_new_eof(ip, i_size);
949                 if (i_size) {
950                         ip->i_d.di_size = i_size;
951                         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
952                 }
953
954                 error = xfs_defer_finish(&tp, &dfops, NULL);
955                 if (error)
956                         goto error_on_bmapi_transaction;
957
958                 error = xfs_trans_commit(tp);
959                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
960                 if (error)
961                         return error;
962
963                 if (!(imap.br_startblock || XFS_IS_REALTIME_INODE(ip)))
964                         return xfs_alert_fsblock_zero(ip, &imap);
965
966                 if ((numblks_fsb = imap.br_blockcount) == 0) {
967                         /*
968                          * The numblks_fsb value should always get
969                          * smaller, otherwise the loop is stuck.
970                          */
971                         ASSERT(imap.br_blockcount);
972                         break;
973                 }
974                 offset_fsb += numblks_fsb;
975                 count_fsb -= numblks_fsb;
976         } while (count_fsb > 0);
977
978         return 0;
979
980 error_on_bmapi_transaction:
981         xfs_defer_cancel(&dfops);
982         xfs_trans_cancel(tp);
983         xfs_iunlock(ip, XFS_ILOCK_EXCL);
984         return error;
985 }
986
987 static inline bool imap_needs_alloc(struct xfs_bmbt_irec *imap, int nimaps)
988 {
989         return !nimaps ||
990                 imap->br_startblock == HOLESTARTBLOCK ||
991                 imap->br_startblock == DELAYSTARTBLOCK;
992 }
993
994 static int
995 xfs_file_iomap_begin(
996         struct inode            *inode,
997         loff_t                  offset,
998         loff_t                  length,
999         unsigned                flags,
1000         struct iomap            *iomap)
1001 {
1002         struct xfs_inode        *ip = XFS_I(inode);
1003         struct xfs_mount        *mp = ip->i_mount;
1004         struct xfs_bmbt_irec    imap;
1005         xfs_fileoff_t           offset_fsb, end_fsb;
1006         int                     nimaps = 1, error = 0;
1007
1008         if (XFS_FORCED_SHUTDOWN(mp))
1009                 return -EIO;
1010
1011         xfs_ilock(ip, XFS_ILOCK_EXCL);
1012
1013         ASSERT(offset <= mp->m_super->s_maxbytes);
1014         if ((xfs_fsize_t)offset + length > mp->m_super->s_maxbytes)
1015                 length = mp->m_super->s_maxbytes - offset;
1016         offset_fsb = XFS_B_TO_FSBT(mp, offset);
1017         end_fsb = XFS_B_TO_FSB(mp, offset + length);
1018
1019         error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap,
1020                                &nimaps, XFS_BMAPI_ENTIRE);
1021         if (error) {
1022                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1023                 return error;
1024         }
1025
1026         if ((flags & IOMAP_WRITE) && imap_needs_alloc(&imap, nimaps)) {
1027                 /*
1028                  * We cap the maximum length we map here to MAX_WRITEBACK_PAGES
1029                  * pages to keep the chunks of work done where somewhat symmetric
1030                  * with the work writeback does. This is a completely arbitrary
1031                  * number pulled out of thin air as a best guess for initial
1032                  * testing.
1033                  *
1034                  * Note that the values needs to be less than 32-bits wide until
1035                  * the lower level functions are updated.
1036                  */
1037                 length = min_t(loff_t, length, 1024 * PAGE_SIZE);
1038                 if (xfs_get_extsz_hint(ip)) {
1039                         /*
1040                          * xfs_iomap_write_direct() expects the shared lock. It
1041                          * is unlocked on return.
1042                          */
1043                         xfs_ilock_demote(ip, XFS_ILOCK_EXCL);
1044                         error = xfs_iomap_write_direct(ip, offset, length, &imap,
1045                                         nimaps);
1046                 } else {
1047                         error = xfs_iomap_write_delay(ip, offset, length, &imap);
1048                         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1049                 }
1050
1051                 if (error)
1052                         return error;
1053
1054                 trace_xfs_iomap_alloc(ip, offset, length, 0, &imap);
1055         } else {
1056                 ASSERT(nimaps);
1057
1058                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1059                 trace_xfs_iomap_found(ip, offset, length, 0, &imap);
1060         }
1061
1062         xfs_bmbt_to_iomap(ip, iomap, &imap);
1063         return 0;
1064 }
1065
1066 static int
1067 xfs_file_iomap_end_delalloc(
1068         struct xfs_inode        *ip,
1069         loff_t                  offset,
1070         loff_t                  length,
1071         ssize_t                 written)
1072 {
1073         struct xfs_mount        *mp = ip->i_mount;
1074         xfs_fileoff_t           start_fsb;
1075         xfs_fileoff_t           end_fsb;
1076         int                     error = 0;
1077
1078         start_fsb = XFS_B_TO_FSB(mp, offset + written);
1079         end_fsb = XFS_B_TO_FSB(mp, offset + length);
1080
1081         /*
1082          * Trim back delalloc blocks if we didn't manage to write the whole
1083          * range reserved.
1084          *
1085          * We don't need to care about racing delalloc as we hold i_mutex
1086          * across the reserve/allocate/unreserve calls. If there are delalloc
1087          * blocks in the range, they are ours.
1088          */
1089         if (start_fsb < end_fsb) {
1090                 xfs_ilock(ip, XFS_ILOCK_EXCL);
1091                 error = xfs_bmap_punch_delalloc_range(ip, start_fsb,
1092                                                end_fsb - start_fsb);
1093                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1094
1095                 if (error && !XFS_FORCED_SHUTDOWN(mp)) {
1096                         xfs_alert(mp, "%s: unable to clean up ino %lld",
1097                                 __func__, ip->i_ino);
1098                         return error;
1099                 }
1100         }
1101
1102         return 0;
1103 }
1104
1105 static int
1106 xfs_file_iomap_end(
1107         struct inode            *inode,
1108         loff_t                  offset,
1109         loff_t                  length,
1110         ssize_t                 written,
1111         unsigned                flags,
1112         struct iomap            *iomap)
1113 {
1114         if ((flags & IOMAP_WRITE) && iomap->type == IOMAP_DELALLOC)
1115                 return xfs_file_iomap_end_delalloc(XFS_I(inode), offset,
1116                                 length, written);
1117         return 0;
1118 }
1119
1120 struct iomap_ops xfs_iomap_ops = {
1121         .iomap_begin            = xfs_file_iomap_begin,
1122         .iomap_end              = xfs_file_iomap_end,
1123 };
1124
1125 static int
1126 xfs_xattr_iomap_begin(
1127         struct inode            *inode,
1128         loff_t                  offset,
1129         loff_t                  length,
1130         unsigned                flags,
1131         struct iomap            *iomap)
1132 {
1133         struct xfs_inode        *ip = XFS_I(inode);
1134         struct xfs_mount        *mp = ip->i_mount;
1135         xfs_fileoff_t           offset_fsb = XFS_B_TO_FSBT(mp, offset);
1136         xfs_fileoff_t           end_fsb = XFS_B_TO_FSB(mp, offset + length);
1137         struct xfs_bmbt_irec    imap;
1138         int                     nimaps = 1, error = 0;
1139         unsigned                lockmode;
1140
1141         if (XFS_FORCED_SHUTDOWN(mp))
1142                 return -EIO;
1143
1144         lockmode = xfs_ilock_data_map_shared(ip);
1145
1146         /* if there are no attribute fork or extents, return ENOENT */
1147         if (XFS_IFORK_Q(ip) || !ip->i_d.di_anextents) {
1148                 error = -ENOENT;
1149                 goto out_unlock;
1150         }
1151
1152         ASSERT(ip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL);
1153         error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap,
1154                                &nimaps, XFS_BMAPI_ENTIRE | XFS_BMAPI_ATTRFORK);
1155 out_unlock:
1156         xfs_iunlock(ip, lockmode);
1157
1158         if (!error) {
1159                 ASSERT(nimaps);
1160                 xfs_bmbt_to_iomap(ip, iomap, &imap);
1161         }
1162
1163         return error;
1164 }
1165
1166 struct iomap_ops xfs_xattr_iomap_ops = {
1167         .iomap_begin            = xfs_xattr_iomap_begin,
1168 };