Whamcloud - gitweb
LU-10683 osd_zfs: set offset in page correctly
[fs/lustre-release.git] / lustre / osd-zfs / osd_io.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/osd-zfs/osd_io.c
33  *
34  * Author: Alex Zhuravlev <bzzz@whamcloud.com>
35  * Author: Mike Pershin <tappro@whamcloud.com>
36  */
37
38 #define DEBUG_SUBSYSTEM S_OSD
39
40 #include <libcfs/libcfs.h>
41 #include <obd_support.h>
42 #include <lustre_net.h>
43 #include <obd.h>
44 #include <obd_class.h>
45 #include <lustre_disk.h>
46 #include <lustre_fid.h>
47 #include <lustre_quota.h>
48
49 #include "osd_internal.h"
50
51 #include <sys/dnode.h>
52 #include <sys/dbuf.h>
53 #include <sys/spa.h>
54 #include <sys/stat.h>
55 #include <sys/zap.h>
56 #include <sys/spa_impl.h>
57 #include <sys/zfs_znode.h>
58 #include <sys/dmu_tx.h>
59 #include <sys/dmu_objset.h>
60 #include <sys/dsl_prop.h>
61 #include <sys/sa_impl.h>
62 #include <sys/txg.h>
63
64 static char *osd_0copy_tag = "zerocopy";
65
66
67 static void record_start_io(struct osd_device *osd, int rw, int discont_pages)
68 {
69         struct obd_histogram *h = osd->od_brw_stats.hist;
70
71         if (rw == READ) {
72                 atomic_inc(&osd->od_r_in_flight);
73                 lprocfs_oh_tally(&h[BRW_R_RPC_HIST],
74                                  atomic_read(&osd->od_r_in_flight));
75                 lprocfs_oh_tally(&h[BRW_R_DISCONT_PAGES], discont_pages);
76
77         } else {
78                 atomic_inc(&osd->od_w_in_flight);
79                 lprocfs_oh_tally(&h[BRW_W_RPC_HIST],
80                                  atomic_read(&osd->od_w_in_flight));
81                 lprocfs_oh_tally(&h[BRW_W_DISCONT_PAGES], discont_pages);
82
83         }
84 }
85
86 static void record_end_io(struct osd_device *osd, int rw,
87                           unsigned long elapsed, int disksize, int npages)
88 {
89         struct obd_histogram *h = osd->od_brw_stats.hist;
90
91         if (rw == READ) {
92                 atomic_dec(&osd->od_r_in_flight);
93                 lprocfs_oh_tally_log2(&h[BRW_R_PAGES], npages);
94                 if (disksize > 0)
95                         lprocfs_oh_tally_log2(&h[BRW_R_DISK_IOSIZE], disksize);
96                 if (elapsed)
97                         lprocfs_oh_tally_log2(&h[BRW_R_IO_TIME], elapsed);
98
99         } else {
100                 atomic_dec(&osd->od_w_in_flight);
101                 lprocfs_oh_tally_log2(&h[BRW_W_PAGES], npages);
102                 if (disksize > 0)
103                         lprocfs_oh_tally_log2(&h[BRW_W_DISK_IOSIZE], disksize);
104                 if (elapsed)
105                         lprocfs_oh_tally_log2(&h[BRW_W_IO_TIME], elapsed);
106         }
107 }
108
109 static ssize_t __osd_read(const struct lu_env *env, struct dt_object *dt,
110                           struct lu_buf *buf, loff_t *pos, size_t *size)
111 {
112         struct osd_object *obj = osd_dt_obj(dt);
113         uint64_t old_size;
114         int rc;
115
116         LASSERT(dt_object_exists(dt));
117         LASSERT(obj->oo_dn);
118
119         read_lock(&obj->oo_attr_lock);
120         old_size = obj->oo_attr.la_size;
121         read_unlock(&obj->oo_attr_lock);
122
123         if (*pos + *size > old_size) {
124                 if (old_size < *pos)
125                         return 0;
126
127                 *size = old_size - *pos;
128         }
129
130         rc = osd_dmu_read(osd_obj2dev(obj), obj->oo_dn, *pos, *size,
131                           buf->lb_buf, DMU_READ_PREFETCH);
132         if (!rc) {
133                 rc = *size;
134                 *pos += *size;
135         }
136
137         return rc;
138 }
139
140 static ssize_t osd_read(const struct lu_env *env, struct dt_object *dt,
141                         struct lu_buf *buf, loff_t *pos)
142 {
143         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
144         size_t size = buf->lb_len;
145         ktime_t start;
146         s64 delta_ms;
147         int rc;
148
149         start = ktime_get();
150         record_start_io(osd, READ, 0);
151         rc = __osd_read(env, dt, buf, pos, &size);
152         delta_ms = ktime_ms_delta(ktime_get(), start);
153         record_end_io(osd, READ, delta_ms, size, size >> PAGE_SHIFT);
154
155         return rc;
156 }
157
158 static inline ssize_t osd_read_no_record(const struct lu_env *env,
159                                          struct dt_object *dt,
160                                          struct lu_buf *buf, loff_t *pos)
161 {
162         size_t size = buf->lb_len;
163
164         return __osd_read(env, dt, buf, pos, &size);
165 }
166
167 static ssize_t osd_declare_write(const struct lu_env *env, struct dt_object *dt,
168                                 const struct lu_buf *buf, loff_t pos,
169                                 struct thandle *th)
170 {
171         struct osd_object  *obj  = osd_dt_obj(dt);
172         struct osd_device  *osd = osd_obj2dev(obj);
173         struct osd_thandle *oh;
174         uint64_t            oid;
175         ENTRY;
176
177         oh = container_of0(th, struct osd_thandle, ot_super);
178
179         /* in some cases declare can race with creation (e.g. llog)
180          * and we need to wait till object is initialized. notice
181          * LOHA_EXISTs is supposed to be the last step in the
182          * initialization */
183
184         /* size change (in dnode) will be declared by dmu_tx_hold_write() */
185         if (dt_object_exists(dt))
186                 oid = obj->oo_dn->dn_object;
187         else
188                 oid = DMU_NEW_OBJECT;
189
190         /* XXX: we still miss for append declaration support in ZFS
191          *      -1 means append which is used by llog mostly, llog
192          *      can grow upto LLOG_MIN_CHUNK_SIZE*8 records */
193         if (pos == -1)
194                 pos = max_t(loff_t, 256 * 8 * LLOG_MIN_CHUNK_SIZE,
195                             obj->oo_attr.la_size + (2 << 20));
196         osd_tx_hold_write(oh->ot_tx, oid, obj->oo_dn, pos, buf->lb_len);
197
198         /* dt_declare_write() is usually called for system objects, such
199          * as llog or last_rcvd files. We needn't enforce quota on those
200          * objects, so always set the lqi_space as 0. */
201         RETURN(osd_declare_quota(env, osd, obj->oo_attr.la_uid,
202                                  obj->oo_attr.la_gid, obj->oo_attr.la_projid,
203                                  0, oh, NULL, OSD_QID_BLK));
204 }
205
206 static ssize_t osd_write(const struct lu_env *env, struct dt_object *dt,
207                         const struct lu_buf *buf, loff_t *pos,
208                         struct thandle *th, int ignore_quota)
209 {
210         struct osd_object  *obj  = osd_dt_obj(dt);
211         struct osd_device  *osd = osd_obj2dev(obj);
212         struct osd_thandle *oh;
213         uint64_t            offset = *pos;
214         int                 rc;
215
216         ENTRY;
217
218         LASSERT(dt_object_exists(dt));
219         LASSERT(obj->oo_dn);
220
221         LASSERT(th != NULL);
222         oh = container_of0(th, struct osd_thandle, ot_super);
223
224         osd_dmu_write(osd, obj->oo_dn, offset, (uint64_t)buf->lb_len,
225                       buf->lb_buf, oh->ot_tx);
226         write_lock(&obj->oo_attr_lock);
227         if (obj->oo_attr.la_size < offset + buf->lb_len) {
228                 obj->oo_attr.la_size = offset + buf->lb_len;
229                 write_unlock(&obj->oo_attr_lock);
230                 /* osd_object_sa_update() will be copying directly from oo_attr
231                  * into dbuf.  any update within a single txg will copy the
232                  * most actual */
233                 rc = osd_object_sa_update(obj, SA_ZPL_SIZE(osd),
234                                         &obj->oo_attr.la_size, 8, oh);
235                 if (unlikely(rc))
236                         GOTO(out, rc);
237         } else {
238                 write_unlock(&obj->oo_attr_lock);
239         }
240
241         *pos += buf->lb_len;
242         rc = buf->lb_len;
243
244 out:
245         RETURN(rc);
246 }
247
248 /*
249  * XXX: for the moment I don't want to use lnb_flags for osd-internal
250  *      purposes as it's not very well defined ...
251  *      instead I use the lowest bit of the address so that:
252  *        arc buffer:  .lnb_data = abuf          (arc we loan for write)
253  *        dbuf buffer: .lnb_data = dbuf | 1      (dbuf we get for read)
254  *        copy buffer: .lnb_page->mapping = obj (page we allocate for write)
255  *
256  *      bzzz, to blame
257  */
258 static int osd_bufs_put(const struct lu_env *env, struct dt_object *dt,
259                         struct niobuf_local *lnb, int npages)
260 {
261         struct osd_object *obj  = osd_dt_obj(dt);
262         struct osd_device *osd = osd_obj2dev(obj);
263         unsigned long      ptr;
264         int                i;
265
266         LASSERT(dt_object_exists(dt));
267         LASSERT(obj->oo_dn);
268
269         for (i = 0; i < npages; i++) {
270                 if (lnb[i].lnb_page == NULL)
271                         continue;
272                 if (lnb[i].lnb_page->mapping == (void *)obj) {
273                         /* this is anonymous page allocated for copy-write */
274                         lnb[i].lnb_page->mapping = NULL;
275                         __free_page(lnb[i].lnb_page);
276                         atomic_dec(&osd->od_zerocopy_alloc);
277                 } else {
278                         /* see comment in osd_bufs_get_read() */
279                         ptr = (unsigned long)lnb[i].lnb_data;
280                         if (ptr & 1UL) {
281                                 ptr &= ~1UL;
282                                 dmu_buf_rele((void *)ptr, osd_0copy_tag);
283                                 atomic_dec(&osd->od_zerocopy_pin);
284                         } else if (lnb[i].lnb_data != NULL) {
285                                 int j, apages, abufsz;
286                                 abufsz = arc_buf_size(lnb[i].lnb_data);
287                                 apages = abufsz / PAGE_SIZE;
288                                 /* these references to pages must be invalidated
289                                  * to prevent access in osd_bufs_put() */
290                                 for (j = 0; j < apages; j++)
291                                         lnb[i + j].lnb_page = NULL;
292                                 dmu_return_arcbuf(lnb[i].lnb_data);
293                                 atomic_dec(&osd->od_zerocopy_loan);
294                         }
295                 }
296                 lnb[i].lnb_page = NULL;
297                 lnb[i].lnb_data = NULL;
298         }
299
300         return 0;
301 }
302
303 static inline struct page *kmem_to_page(void *addr)
304 {
305         LASSERT(!((unsigned long)addr & ~PAGE_MASK));
306         if (is_vmalloc_addr(addr))
307                 return vmalloc_to_page(addr);
308         else
309                 return virt_to_page(addr);
310 }
311
312 /**
313  * Prepare buffers for read.
314  *
315  * The function maps the range described by \a off and \a len to \a lnb array.
316  * dmu_buf_hold_array_by_bonus() finds/creates appropriate ARC buffers, then
317  * we fill \a lnb array with the pages storing ARC buffers. Notice the current
318  * implementationt passes TRUE to dmu_buf_hold_array_by_bonus() to fill ARC
319  * buffers with actual data, I/O is done in the conext of osd_bufs_get_read().
320  * A better implementation would just return the buffers (potentially unfilled)
321  * and subsequent osd_read_prep() would do I/O for many ranges concurrently.
322  *
323  * \param[in] env       environment
324  * \param[in] obj       object
325  * \param[in] off       offset in bytes
326  * \param[in] len       the number of bytes to access
327  * \param[out] lnb      array of local niobufs pointing to the buffers with data
328  *
329  * \retval              0 for success
330  * \retval              negative error number of failure
331  */
332 static int osd_bufs_get_read(const struct lu_env *env, struct osd_object *obj,
333                              loff_t off, ssize_t len, struct niobuf_local *lnb)
334 {
335         struct osd_device *osd = osd_obj2dev(obj);
336         int rc, i, numbufs, npages = 0;
337         ktime_t start = ktime_get();
338         dmu_buf_t **dbp;
339         s64 delta_ms;
340
341         ENTRY;
342         record_start_io(osd, READ, 0);
343
344         /* grab buffers for read:
345          * OSD API let us to grab buffers first, then initiate IO(s)
346          * so that all required IOs will be done in parallel, but at the
347          * moment DMU doesn't provide us with a method to grab buffers.
348          * If we discover this is a vital for good performance we
349          * can get own replacement for dmu_buf_hold_array_by_bonus().
350          */
351         while (len > 0 &&
352                (obj->oo_dn->dn_datablkshift != 0 ||
353                 off < obj->oo_dn->dn_datablksz)) {
354                 if (obj->oo_dn->dn_datablkshift == 0 &&
355                     off + len > obj->oo_dn->dn_datablksz)
356                         len = obj->oo_dn->dn_datablksz - off;
357
358                 rc = -dmu_buf_hold_array_by_bonus(&obj->oo_dn->dn_bonus->db,
359                                                   off, len, TRUE, osd_0copy_tag,
360                                                   &numbufs, &dbp);
361                 if (unlikely(rc))
362                         GOTO(err, rc);
363
364                 for (i = 0; i < numbufs; i++) {
365                         int bufoff, tocpy, thispage;
366                         void *dbf = dbp[i];
367
368                         LASSERT(len > 0);
369
370                         atomic_inc(&osd->od_zerocopy_pin);
371
372                         bufoff = off - dbp[i]->db_offset;
373                         tocpy = min_t(int, dbp[i]->db_size - bufoff, len);
374
375                         /* kind of trick to differentiate dbuf vs. arcbuf */
376                         LASSERT(((unsigned long)dbp[i] & 1) == 0);
377                         dbf = (void *) ((unsigned long)dbp[i] | 1);
378
379                         while (tocpy > 0) {
380                                 thispage = PAGE_SIZE;
381                                 thispage -= bufoff & (PAGE_SIZE - 1);
382                                 thispage = min(tocpy, thispage);
383
384                                 lnb->lnb_rc = 0;
385                                 lnb->lnb_file_offset = off;
386                                 lnb->lnb_page_offset = bufoff & ~PAGE_MASK;
387                                 lnb->lnb_len = thispage;
388                                 lnb->lnb_page = kmem_to_page(dbp[i]->db_data +
389                                                              bufoff);
390                                 /* mark just a single slot: we need this
391                                  * reference to dbuf to be released once */
392                                 lnb->lnb_data = dbf;
393                                 dbf = NULL;
394
395                                 tocpy -= thispage;
396                                 len -= thispage;
397                                 bufoff += thispage;
398                                 off += thispage;
399
400                                 npages++;
401                                 lnb++;
402                         }
403
404                         /* steal dbuf so dmu_buf_rele_array() can't release
405                          * it */
406                         dbp[i] = NULL;
407                 }
408
409                 dmu_buf_rele_array(dbp, numbufs, osd_0copy_tag);
410         }
411
412         delta_ms = ktime_ms_delta(ktime_get(), start);
413         record_end_io(osd, READ, delta_ms, npages * PAGE_SIZE, npages);
414
415         RETURN(npages);
416
417 err:
418         LASSERT(rc < 0);
419         osd_bufs_put(env, &obj->oo_dt, lnb - npages, npages);
420         RETURN(rc);
421 }
422
423 static inline arc_buf_t *osd_request_arcbuf(dnode_t *dn, size_t bs)
424 {
425         arc_buf_t *abuf;
426
427         abuf = dmu_request_arcbuf(&dn->dn_bonus->db, bs);
428         if (unlikely(!abuf))
429                 return ERR_PTR(-ENOMEM);
430
431 #if ZFS_VERSION_CODE < OBD_OCD_VERSION(0, 7, 0, 0)
432         /**
433          * ZFS prior to 0.7.0 doesn't guarantee PAGE_SIZE alignment for zio
434          * blocks smaller than (PAGE_SIZE << 2). This poses a problem of
435          * setting up page array for RDMA transfer. See LU-9305.
436          */
437         if ((unsigned long)abuf->b_data & ~PAGE_MASK) {
438                 dmu_return_arcbuf(abuf);
439                 return NULL;
440         }
441 #endif
442
443         return abuf;
444 }
445
446 static int osd_bufs_get_write(const struct lu_env *env, struct osd_object *obj,
447                               loff_t off, ssize_t len, struct niobuf_local *lnb)
448 {
449         struct osd_device *osd = osd_obj2dev(obj);
450         int                poff, plen, off_in_block, sz_in_block;
451         int                rc, i = 0, npages = 0;
452         dnode_t *dn = obj->oo_dn;
453         arc_buf_t *abuf;
454         uint32_t bs = dn->dn_datablksz;
455         ENTRY;
456
457         /*
458          * currently only full blocks are subject to zerocopy approach:
459          * so that we're sure nobody is trying to update the same block
460          */
461         while (len > 0) {
462                 LASSERT(npages < PTLRPC_MAX_BRW_PAGES);
463
464                 off_in_block = off & (bs - 1);
465                 sz_in_block = min_t(int, bs - off_in_block, len);
466
467                 abuf = NULL;
468                 if (sz_in_block == bs) {
469                         /* full block, try to use zerocopy */
470                         abuf = osd_request_arcbuf(dn, bs);
471                         if (unlikely(IS_ERR(abuf)))
472                                 GOTO(out_err, rc = PTR_ERR(abuf));
473                 }
474
475                 if (abuf != NULL) {
476                         atomic_inc(&osd->od_zerocopy_loan);
477
478                         /* go over pages arcbuf contains, put them as
479                          * local niobufs for ptlrpc's bulks */
480                         while (sz_in_block > 0) {
481                                 plen = min_t(int, sz_in_block, PAGE_SIZE);
482
483                                 lnb[i].lnb_file_offset = off;
484                                 lnb[i].lnb_page_offset = 0;
485                                 lnb[i].lnb_len = plen;
486                                 lnb[i].lnb_rc = 0;
487                                 if (sz_in_block == bs)
488                                         lnb[i].lnb_data = abuf;
489                                 else
490                                         lnb[i].lnb_data = NULL;
491
492                                 /* this one is not supposed to fail */
493                                 lnb[i].lnb_page = kmem_to_page(abuf->b_data +
494                                                         off_in_block);
495                                 LASSERT(lnb[i].lnb_page);
496
497                                 lprocfs_counter_add(osd->od_stats,
498                                                 LPROC_OSD_ZEROCOPY_IO, 1);
499
500                                 sz_in_block -= plen;
501                                 len -= plen;
502                                 off += plen;
503                                 off_in_block += plen;
504                                 i++;
505                                 npages++;
506                         }
507                 } else {
508                         if (off_in_block == 0 && len < bs &&
509                                         off + len >= obj->oo_attr.la_size)
510                                 lprocfs_counter_add(osd->od_stats,
511                                                 LPROC_OSD_TAIL_IO, 1);
512
513                         /* can't use zerocopy, allocate temp. buffers */
514                         poff = off & (PAGE_SIZE - 1);
515                         while (sz_in_block > 0) {
516                                 plen = min_t(int, poff + sz_in_block,
517                                              PAGE_SIZE);
518                                 plen -= poff;
519
520                                 lnb[i].lnb_file_offset = off;
521                                 lnb[i].lnb_page_offset = poff;
522                                 poff = 0;
523
524                                 lnb[i].lnb_len = plen;
525                                 lnb[i].lnb_rc = 0;
526                                 lnb[i].lnb_data = NULL;
527
528                                 lnb[i].lnb_page = alloc_page(OSD_GFP_IO);
529                                 if (unlikely(lnb[i].lnb_page == NULL))
530                                         GOTO(out_err, rc = -ENOMEM);
531
532                                 LASSERT(lnb[i].lnb_page->mapping == NULL);
533                                 lnb[i].lnb_page->mapping = (void *)obj;
534
535                                 atomic_inc(&osd->od_zerocopy_alloc);
536                                 lprocfs_counter_add(osd->od_stats,
537                                                 LPROC_OSD_COPY_IO, 1);
538
539                                 sz_in_block -= plen;
540                                 len -= plen;
541                                 off += plen;
542                                 i++;
543                                 npages++;
544                         }
545                 }
546         }
547
548         RETURN(npages);
549
550 out_err:
551         osd_bufs_put(env, &obj->oo_dt, lnb, npages);
552         RETURN(rc);
553 }
554
555 static int osd_bufs_get(const struct lu_env *env, struct dt_object *dt,
556                         loff_t offset, ssize_t len, struct niobuf_local *lnb,
557                         enum dt_bufs_type rw)
558 {
559         struct osd_object *obj  = osd_dt_obj(dt);
560         int                rc;
561
562         LASSERT(dt_object_exists(dt));
563         LASSERT(obj->oo_dn);
564
565         if (rw & DT_BUFS_TYPE_WRITE)
566                 rc = osd_bufs_get_write(env, obj, offset, len, lnb);
567         else
568                 rc = osd_bufs_get_read(env, obj, offset, len, lnb);
569
570         return rc;
571 }
572
573 static int osd_write_prep(const struct lu_env *env, struct dt_object *dt,
574                         struct niobuf_local *lnb, int npages)
575 {
576         struct osd_object *obj = osd_dt_obj(dt);
577
578         LASSERT(dt_object_exists(dt));
579         LASSERT(obj->oo_dn);
580
581         return 0;
582 }
583
584 static inline uint64_t osd_roundup2blocksz(uint64_t size,
585                                            uint64_t offset,
586                                            uint32_t blksz)
587 {
588         LASSERT(blksz > 0);
589
590         size += offset % blksz;
591
592         if (likely(is_power_of_2(blksz)))
593                 return PO2_ROUNDUP_TYPED(size, blksz, uint64_t);
594
595         size += blksz - 1;
596         do_div(size, blksz);
597         return size * blksz;
598 }
599
600 static int osd_declare_write_commit(const struct lu_env *env,
601                                     struct dt_object *dt,
602                                     struct niobuf_local *lnb, int npages,
603                                     struct thandle *th)
604 {
605         struct osd_object  *obj = osd_dt_obj(dt);
606         struct osd_device  *osd = osd_obj2dev(obj);
607         struct osd_thandle *oh;
608         uint64_t            offset = 0;
609         uint32_t            size = 0;
610         uint32_t blksz = obj->oo_dn->dn_datablksz;
611         int                 i, rc, flags = 0;
612         bool synced = false;
613         long long           space = 0;
614         struct page        *last_page = NULL;
615         unsigned long       discont_pages = 0;
616         enum osd_qid_declare_flags declare_flags = OSD_QID_BLK;
617         ENTRY;
618
619         LASSERT(dt_object_exists(dt));
620         LASSERT(obj->oo_dn);
621
622         LASSERT(lnb);
623         LASSERT(npages > 0);
624
625         oh = container_of0(th, struct osd_thandle, ot_super);
626
627         for (i = 0; i < npages; i++) {
628                 if (last_page && lnb[i].lnb_page->index != (last_page->index + 1))
629                         ++discont_pages;
630                 last_page = lnb[i].lnb_page;
631                 if (lnb[i].lnb_rc)
632                         /* ENOSPC, network RPC error, etc.
633                          * We don't want to book space for pages which will be
634                          * skipped in osd_write_commit(). Hence we skip pages
635                          * with lnb_rc != 0 here too */
636                         continue;
637                 /* ignore quota for the whole request if any page is from
638                  * client cache or written by root.
639                  *
640                  * XXX once we drop the 1.8 client support, the checking
641                  * for whether page is from cache can be simplified as:
642                  * !(lnb[i].flags & OBD_BRW_SYNC)
643                  *
644                  * XXX we could handle this on per-lnb basis as done by
645                  * grant. */
646                 if ((lnb[i].lnb_flags & OBD_BRW_NOQUOTA) ||
647                     (lnb[i].lnb_flags & (OBD_BRW_FROM_GRANT | OBD_BRW_SYNC)) ==
648                     OBD_BRW_FROM_GRANT)
649                         declare_flags |= OSD_QID_FORCE;
650
651                 if (size == 0) {
652                         /* first valid lnb */
653                         offset = lnb[i].lnb_file_offset;
654                         size = lnb[i].lnb_len;
655                         continue;
656                 }
657                 if (offset + size == lnb[i].lnb_file_offset) {
658                         /* this lnb is contiguous to the previous one */
659                         size += lnb[i].lnb_len;
660                         continue;
661                 }
662
663                 osd_tx_hold_write(oh->ot_tx, obj->oo_dn->dn_object,
664                                   obj->oo_dn, offset, size);
665                 /* Estimating space to be consumed by a write is rather
666                  * complicated with ZFS. As a consequence, we don't account for
667                  * indirect blocks and just use as a rough estimate the worse
668                  * case where the old space is being held by a snapshot. Quota
669                  * overrun will be adjusted once the operation is committed, if
670                  * required. */
671                 space += osd_roundup2blocksz(size, offset, blksz);
672
673                 offset = lnb[i].lnb_file_offset;
674                 size = lnb[i].lnb_len;
675         }
676
677         if (size) {
678                 osd_tx_hold_write(oh->ot_tx, obj->oo_dn->dn_object, obj->oo_dn,
679                                   offset, size);
680                 space += osd_roundup2blocksz(size, offset, blksz);
681         }
682
683         oh->ot_write_commit = 1; /* used in osd_trans_start() for fail_loc */
684
685         /* backend zfs filesystem might be configured to store multiple data
686          * copies */
687         space  *= osd->od_os->os_copies;
688         space   = toqb(space);
689         CDEBUG(D_QUOTA, "writing %d pages, reserving %lldK of quota space\n",
690                npages, space);
691
692         record_start_io(osd, WRITE, discont_pages);
693 retry:
694         /* acquire quota space if needed */
695         rc = osd_declare_quota(env, osd, obj->oo_attr.la_uid,
696                                obj->oo_attr.la_gid, obj->oo_attr.la_projid,
697                                space, oh, &flags, declare_flags);
698
699         if (!synced && rc == -EDQUOT && (flags & QUOTA_FL_SYNC) != 0) {
700                 dt_sync(env, th->th_dev);
701                 synced = true;
702                 CDEBUG(D_QUOTA, "retry after sync\n");
703                 flags = 0;
704                 goto retry;
705         }
706
707         /* we need only to store the overquota flags in the first lnb for
708          * now, once we support multiple objects BRW, this code needs be
709          * revised. */
710         if (flags & QUOTA_FL_OVER_USRQUOTA)
711                 lnb[0].lnb_flags |= OBD_BRW_OVER_USRQUOTA;
712         if (flags & QUOTA_FL_OVER_GRPQUOTA)
713                 lnb[0].lnb_flags |= OBD_BRW_OVER_GRPQUOTA;
714 #ifdef ZFS_PROJINHERIT
715         if (flags & QUOTA_FL_OVER_PRJQUOTA)
716                 lnb[0].lnb_flags |= OBD_BRW_OVER_PRJQUOTA;
717 #endif
718
719         RETURN(rc);
720 }
721
722 /**
723  * Policy to grow ZFS block size by write pattern.
724  * For sequential write, it grows block size gradually until it reaches the
725  * maximum blocksize the dataset can support. Otherwise, it will pick a
726  * a block size by the writing region of this I/O.
727  */
728 static int osd_grow_blocksize(struct osd_object *obj, struct osd_thandle *oh,
729                               uint64_t start, uint64_t end)
730 {
731         struct osd_device       *osd = osd_obj2dev(obj);
732         dnode_t *dn = obj->oo_dn;
733         uint32_t                 blksz;
734         int                      rc = 0;
735
736         ENTRY;
737
738         if (dn->dn_maxblkid > 0) /* can't change block size */
739                 GOTO(out, rc);
740
741         if (dn->dn_datablksz >= osd->od_max_blksz)
742                 GOTO(out, rc);
743
744         down_write(&obj->oo_guard);
745
746         blksz = dn->dn_datablksz;
747         if (blksz >= osd->od_max_blksz) /* check again after grabbing lock */
748                 GOTO(out_unlock, rc);
749
750         /* now ZFS can support up to 16MB block size, and if the write
751          * is sequential, it just increases the block size gradually */
752         if (start <= blksz) { /* sequential */
753                 blksz = (uint32_t)min_t(uint64_t, osd->od_max_blksz, end);
754         } else { /* sparse, pick a block size by write region */
755                 blksz = (uint32_t)min_t(uint64_t, osd->od_max_blksz,
756                                         end - start);
757         }
758
759         if (!is_power_of_2(blksz))
760                 blksz = size_roundup_power2(blksz);
761
762         if (blksz > dn->dn_datablksz) {
763                 rc = -dmu_object_set_blocksize(osd->od_os, dn->dn_object,
764                                                blksz, 0, oh->ot_tx);
765                 LASSERT(ergo(rc == 0, dn->dn_datablksz >= blksz));
766                 if (rc < 0)
767                         CDEBUG(D_INODE, "object "DFID": change block size"
768                                "%u -> %u error rc = %d\n",
769                                PFID(lu_object_fid(&obj->oo_dt.do_lu)),
770                                dn->dn_datablksz, blksz, rc);
771         }
772         EXIT;
773 out_unlock:
774         up_write(&obj->oo_guard);
775 out:
776         return rc;
777 }
778
779 static int osd_write_commit(const struct lu_env *env, struct dt_object *dt,
780                         struct niobuf_local *lnb, int npages,
781                         struct thandle *th)
782 {
783         struct osd_object  *obj  = osd_dt_obj(dt);
784         struct osd_device  *osd = osd_obj2dev(obj);
785         struct osd_thandle *oh;
786         uint64_t            new_size = 0;
787         int                 i, rc = 0;
788         unsigned long      iosize = 0;
789         ENTRY;
790
791         LASSERT(dt_object_exists(dt));
792         LASSERT(obj->oo_dn);
793
794         LASSERT(th != NULL);
795         oh = container_of0(th, struct osd_thandle, ot_super);
796
797         /* adjust block size. Assume the buffers are sorted. */
798         (void)osd_grow_blocksize(obj, oh, lnb[0].lnb_file_offset,
799                                  lnb[npages - 1].lnb_file_offset +
800                                  lnb[npages - 1].lnb_len);
801
802         /* LU-8791: take oo_guard to avoid the deadlock that changing block
803          * size and assigning arcbuf take place at the same time.
804          *
805          * Thread 1:
806          * osd_write_commit()
807          *  -> osd_grow_blocksize() with osd_object::oo_guard held
808          *   -> dmu_object_set_blocksize()
809          *    -> dnode_set_blksz(), with dnode_t::dn_struct_rwlock
810          *       write lock held
811          *     -> dbuf_new_size()
812          *      -> dmu_buf_will_dirty()
813          *       -> dbuf_read()
814          *        -> wait for the dbuf state to change
815          * Thread 2:
816          * osd_write_commit()
817          *  -> dmu_assign_arcbuf()
818          *   -> dbuf_assign_arcbuf(), set dbuf state to DB_FILL
819          *    -> dbuf_dirty()
820          *     -> try to hold the read lock of dnode_t::dn_struct_rwlock
821          *
822          * By taking the read lock, it can avoid thread 2 to enter into the
823          * critical section of assigning the arcbuf, while thread 1 is
824          * changing the block size.
825          */
826         down_read(&obj->oo_guard);
827         for (i = 0; i < npages; i++) {
828                 CDEBUG(D_INODE, "write %u bytes at %u\n",
829                         (unsigned) lnb[i].lnb_len,
830                         (unsigned) lnb[i].lnb_file_offset);
831
832                 if (lnb[i].lnb_rc) {
833                         /* ENOSPC, network RPC error, etc.
834                          * Unlike ldiskfs, zfs allocates new blocks on rewrite,
835                          * so we skip this page if lnb_rc is set to -ENOSPC */
836                         CDEBUG(D_INODE, "obj "DFID": skipping lnb[%u]: rc=%d\n",
837                                 PFID(lu_object_fid(&dt->do_lu)), i,
838                                 lnb[i].lnb_rc);
839                         continue;
840                 }
841
842                 if (new_size < lnb[i].lnb_file_offset + lnb[i].lnb_len)
843                         new_size = lnb[i].lnb_file_offset + lnb[i].lnb_len;
844                 if (lnb[i].lnb_page == NULL)
845                         continue;
846
847                 if (lnb[i].lnb_page->mapping == (void *)obj) {
848                         osd_dmu_write(osd, obj->oo_dn, lnb[i].lnb_file_offset,
849                                       lnb[i].lnb_len, kmap(lnb[i].lnb_page),
850                                       oh->ot_tx);
851                         kunmap(lnb[i].lnb_page);
852                         iosize += lnb[i].lnb_len;
853                 } else if (lnb[i].lnb_data) {
854                         int j, apages, abufsz;
855                         LASSERT(((unsigned long)lnb[i].lnb_data & 1) == 0);
856                         /* buffer loaned for zerocopy, try to use it.
857                          * notice that dmu_assign_arcbuf() is smart
858                          * enough to recognize changed blocksize
859                          * in this case it fallbacks to dmu_write() */
860                         abufsz = arc_buf_size(lnb[i].lnb_data);
861                         LASSERT(abufsz & PAGE_MASK);
862                         apages = abufsz / PAGE_SIZE;
863                         LASSERT(i + apages <= npages);
864                         /* these references to pages must be invalidated
865                          * to prevent access in osd_bufs_put() */
866                         for (j = 0; j < apages; j++)
867                                 lnb[i + j].lnb_page = NULL;
868                         dmu_assign_arcbuf(&obj->oo_dn->dn_bonus->db,
869                                           lnb[i].lnb_file_offset,
870                                           lnb[i].lnb_data, oh->ot_tx);
871                         /* drop the reference, otherwise osd_put_bufs()
872                          * will be releasing it - bad! */
873                         lnb[i].lnb_data = NULL;
874                         atomic_dec(&osd->od_zerocopy_loan);
875                         iosize += abufsz;
876                 }
877
878         }
879         up_read(&obj->oo_guard);
880
881         if (unlikely(new_size == 0)) {
882                 /* no pages to write, no transno is needed */
883                 th->th_local = 1;
884                 /* it is important to return 0 even when all lnb_rc == -ENOSPC
885                  * since ofd_commitrw_write() retries several times on ENOSPC */
886                 record_end_io(osd, WRITE, 0, 0, 0);
887                 RETURN(0);
888         }
889
890         write_lock(&obj->oo_attr_lock);
891         if (obj->oo_attr.la_size < new_size) {
892                 obj->oo_attr.la_size = new_size;
893                 write_unlock(&obj->oo_attr_lock);
894                 /* osd_object_sa_update() will be copying directly from
895                  * oo_attr into dbuf. any update within a single txg will copy
896                  * the most actual */
897                 rc = osd_object_sa_update(obj, SA_ZPL_SIZE(osd),
898                                           &obj->oo_attr.la_size, 8, oh);
899         } else {
900                 write_unlock(&obj->oo_attr_lock);
901         }
902
903         record_end_io(osd, WRITE, 0, iosize, npages);
904
905         RETURN(rc);
906 }
907
908 static int osd_read_prep(const struct lu_env *env, struct dt_object *dt,
909                         struct niobuf_local *lnb, int npages)
910 {
911         struct osd_object *obj  = osd_dt_obj(dt);
912         int                i;
913         loff_t             eof;
914
915         LASSERT(dt_object_exists(dt));
916         LASSERT(obj->oo_dn);
917
918         read_lock(&obj->oo_attr_lock);
919         eof = obj->oo_attr.la_size;
920         read_unlock(&obj->oo_attr_lock);
921
922         for (i = 0; i < npages; i++) {
923                 if (unlikely(lnb[i].lnb_rc < 0))
924                         continue;
925
926                 lnb[i].lnb_rc = lnb[i].lnb_len;
927
928                 if (lnb[i].lnb_file_offset + lnb[i].lnb_len >= eof) {
929                         if (eof <= lnb[i].lnb_file_offset)
930                                 lnb[i].lnb_rc = 0;
931                         else
932                                 lnb[i].lnb_rc = eof - lnb[i].lnb_file_offset;
933
934                         /* all subsequent rc should be 0 */
935                         while (++i < npages)
936                                 lnb[i].lnb_rc = 0;
937                         break;
938                 }
939         }
940
941         return 0;
942 }
943
944 /*
945  * Punch/truncate an object
946  *
947  *      IN:     db  - dmu_buf of the object to free data in.
948  *              off - start of section to free.
949  *              len - length of section to free (DMU_OBJECT_END => to EOF).
950  *
951  *      RETURN: 0 if success
952  *              error code if failure
953  *
954  * The transaction passed to this routine must have
955  * dmu_tx_hold_sa() and if off < size, dmu_tx_hold_free()
956  * called and then assigned to a transaction group.
957  */
958 static int __osd_object_punch(objset_t *os, dnode_t *dn, dmu_tx_t *tx,
959                                 uint64_t size, uint64_t off, uint64_t len)
960 {
961         int rc = 0;
962
963         /* Assert that the transaction has been assigned to a
964            transaction group. */
965         LASSERT(tx->tx_txg != 0);
966         /*
967          * Nothing to do if file already at desired length.
968          */
969         if (len == DMU_OBJECT_END && size == off)
970                 return 0;
971
972         /* XXX: dnode_free_range() can be used to save on dnode lookup */
973         if (off < size)
974                 dmu_free_range(os, dn->dn_object, off, len, tx);
975
976         return rc;
977 }
978
979 static int osd_punch(const struct lu_env *env, struct dt_object *dt,
980                         __u64 start, __u64 end, struct thandle *th)
981 {
982         struct osd_object  *obj = osd_dt_obj(dt);
983         struct osd_device  *osd = osd_obj2dev(obj);
984         struct osd_thandle *oh;
985         __u64               len;
986         int                 rc = 0;
987         ENTRY;
988
989         LASSERT(dt_object_exists(dt));
990         LASSERT(osd_invariant(obj));
991
992         LASSERT(th != NULL);
993         oh = container_of0(th, struct osd_thandle, ot_super);
994
995         write_lock(&obj->oo_attr_lock);
996         /* truncate */
997         if (end == OBD_OBJECT_EOF || end >= obj->oo_attr.la_size)
998                 len = DMU_OBJECT_END;
999         else
1000                 len = end - start;
1001         write_unlock(&obj->oo_attr_lock);
1002
1003         rc = __osd_object_punch(osd->od_os, obj->oo_dn, oh->ot_tx,
1004                                 obj->oo_attr.la_size, start, len);
1005         /* set new size */
1006         if (len == DMU_OBJECT_END) {
1007                 write_lock(&obj->oo_attr_lock);
1008                 obj->oo_attr.la_size = start;
1009                 write_unlock(&obj->oo_attr_lock);
1010                 rc = osd_object_sa_update(obj, SA_ZPL_SIZE(osd),
1011                                           &obj->oo_attr.la_size, 8, oh);
1012         }
1013         RETURN(rc);
1014 }
1015
1016 static int osd_declare_punch(const struct lu_env *env, struct dt_object *dt,
1017                         __u64 start, __u64 end, struct thandle *handle)
1018 {
1019         struct osd_object  *obj = osd_dt_obj(dt);
1020         struct osd_device  *osd = osd_obj2dev(obj);
1021         struct osd_thandle *oh;
1022         __u64               len;
1023         ENTRY;
1024
1025         oh = container_of0(handle, struct osd_thandle, ot_super);
1026
1027         read_lock(&obj->oo_attr_lock);
1028         if (end == OBD_OBJECT_EOF || end >= obj->oo_attr.la_size)
1029                 len = DMU_OBJECT_END;
1030         else
1031                 len = end - start;
1032
1033         /* declare we'll free some blocks ... */
1034         if (start < obj->oo_attr.la_size) {
1035                 read_unlock(&obj->oo_attr_lock);
1036                 dmu_tx_mark_netfree(oh->ot_tx);
1037                 dmu_tx_hold_free(oh->ot_tx, obj->oo_dn->dn_object, start, len);
1038         } else {
1039                 read_unlock(&obj->oo_attr_lock);
1040         }
1041
1042         RETURN(osd_declare_quota(env, osd, obj->oo_attr.la_uid,
1043                                  obj->oo_attr.la_gid, obj->oo_attr.la_projid,
1044                                  0, oh, NULL, OSD_QID_BLK));
1045 }
1046
1047 static int osd_ladvise(const struct lu_env *env, struct dt_object *dt,
1048                        __u64 start, __u64 end, enum lu_ladvise_type advice)
1049 {
1050         int     rc;
1051         ENTRY;
1052
1053         switch (advice) {
1054         default:
1055                 rc = -ENOTSUPP;
1056                 break;
1057         }
1058
1059         RETURN(rc);
1060 }
1061
1062 struct dt_body_operations osd_body_ops = {
1063         .dbo_read                       = osd_read,
1064         .dbo_declare_write              = osd_declare_write,
1065         .dbo_write                      = osd_write,
1066         .dbo_bufs_get                   = osd_bufs_get,
1067         .dbo_bufs_put                   = osd_bufs_put,
1068         .dbo_write_prep                 = osd_write_prep,
1069         .dbo_declare_write_commit       = osd_declare_write_commit,
1070         .dbo_write_commit               = osd_write_commit,
1071         .dbo_read_prep                  = osd_read_prep,
1072         .dbo_declare_punch              = osd_declare_punch,
1073         .dbo_punch                      = osd_punch,
1074         .dbo_ladvise                    = osd_ladvise,
1075 };
1076
1077 struct dt_body_operations osd_body_scrub_ops = {
1078         .dbo_read                       = osd_read_no_record,
1079         .dbo_declare_write              = osd_declare_write,
1080         .dbo_write                      = osd_write,
1081 };