Whamcloud - gitweb
LU-13043 quota: remove annoying message in osd_declare_inode_qid()
[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 dbuf_set_pending_evict(dmu_buf_t *db)
68 {
69         dmu_buf_impl_t *dbi = (dmu_buf_impl_t *)db;
70         dbi->db_pending_evict = TRUE;
71 }
72
73 static void record_start_io(struct osd_device *osd, int rw, int discont_pages)
74 {
75         struct obd_histogram *h = osd->od_brw_stats.hist;
76
77         if (rw == READ) {
78                 atomic_inc(&osd->od_r_in_flight);
79                 lprocfs_oh_tally(&h[BRW_R_RPC_HIST],
80                                  atomic_read(&osd->od_r_in_flight));
81                 lprocfs_oh_tally(&h[BRW_R_DISCONT_PAGES], discont_pages);
82
83         } else {
84                 atomic_inc(&osd->od_w_in_flight);
85                 lprocfs_oh_tally(&h[BRW_W_RPC_HIST],
86                                  atomic_read(&osd->od_w_in_flight));
87                 lprocfs_oh_tally(&h[BRW_W_DISCONT_PAGES], discont_pages);
88
89         }
90 }
91
92 static void record_end_io(struct osd_device *osd, int rw,
93                           unsigned long elapsed, int disksize, int npages)
94 {
95         struct obd_histogram *h = osd->od_brw_stats.hist;
96
97         if (rw == READ)
98                 atomic_dec(&osd->od_r_in_flight);
99         else
100                 atomic_dec(&osd->od_w_in_flight);
101
102         lprocfs_oh_tally_log2(&h[BRW_R_PAGES + rw], npages);
103         if (disksize > 0)
104                 lprocfs_oh_tally_log2(&h[BRW_R_DISK_IOSIZE + rw], disksize);
105         if (elapsed)
106                 lprocfs_oh_tally_log2(&h[BRW_R_IO_TIME + rw], elapsed);
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)
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                              int maxlnb)
335 {
336         struct osd_device *osd = osd_obj2dev(obj);
337         int rc, i, numbufs, npages = 0, drop_cache = 0;
338         ktime_t start = ktime_get();
339         dmu_buf_t **dbp;
340         s64 delta_ms;
341
342         ENTRY;
343         record_start_io(osd, READ, 0);
344
345         if (obj->oo_attr.la_size >= osd->od_readcache_max_filesize)
346                 drop_cache = 1;
347
348         /* grab buffers for read:
349          * OSD API let us to grab buffers first, then initiate IO(s)
350          * so that all required IOs will be done in parallel, but at the
351          * moment DMU doesn't provide us with a method to grab buffers.
352          * If we discover this is a vital for good performance we
353          * can get own replacement for dmu_buf_hold_array_by_bonus().
354          */
355         while (len > 0 &&
356                (obj->oo_dn->dn_datablkshift != 0 ||
357                 off < obj->oo_dn->dn_datablksz)) {
358                 if (obj->oo_dn->dn_datablkshift == 0 &&
359                     off + len > obj->oo_dn->dn_datablksz)
360                         len = obj->oo_dn->dn_datablksz - off;
361
362                 dbp = NULL;
363                 if (unlikely(npages >= maxlnb))
364                         GOTO(err, rc = -EOVERFLOW);
365
366                 rc = -dmu_buf_hold_array_by_bonus(&obj->oo_dn->dn_bonus->db,
367                                                   off, len, TRUE, osd_0copy_tag,
368                                                   &numbufs, &dbp);
369                 if (unlikely(rc))
370                         GOTO(err, rc);
371
372                 for (i = 0; i < numbufs; i++) {
373                         int bufoff, tocpy, thispage;
374                         void *dbf = dbp[i];
375
376                         LASSERT(len > 0);
377
378                         atomic_inc(&osd->od_zerocopy_pin);
379
380                         bufoff = off - dbp[i]->db_offset;
381                         tocpy = min_t(int, dbp[i]->db_size - bufoff, len);
382
383                         /* kind of trick to differentiate dbuf vs. arcbuf */
384                         LASSERT(((unsigned long)dbp[i] & 1) == 0);
385                         dbf = (void *) ((unsigned long)dbp[i] | 1);
386
387                         while (tocpy > 0) {
388                                 if (unlikely(npages >= maxlnb))
389                                         GOTO(err, rc = -EOVERFLOW);
390
391                                 thispage = PAGE_SIZE;
392                                 thispage -= bufoff & (PAGE_SIZE - 1);
393                                 thispage = min(tocpy, thispage);
394
395                                 lnb->lnb_rc = 0;
396                                 lnb->lnb_file_offset = off;
397                                 lnb->lnb_page_offset = bufoff & ~PAGE_MASK;
398                                 lnb->lnb_len = thispage;
399                                 lnb->lnb_page = kmem_to_page(dbp[i]->db_data +
400                                                              bufoff);
401                                 /* mark just a single slot: we need this
402                                  * reference to dbuf to be released once */
403                                 lnb->lnb_data = dbf;
404                                 dbf = NULL;
405
406                                 tocpy -= thispage;
407                                 len -= thispage;
408                                 bufoff += thispage;
409                                 off += thispage;
410
411                                 npages++;
412                                 lnb++;
413                         }
414
415                         if (drop_cache)
416                                 dbuf_set_pending_evict(dbp[i]);
417
418                         /* steal dbuf so dmu_buf_rele_array() can't release
419                          * it */
420                         dbp[i] = NULL;
421                 }
422
423                 dmu_buf_rele_array(dbp, numbufs, osd_0copy_tag);
424         }
425
426         delta_ms = ktime_ms_delta(ktime_get(), start);
427         record_end_io(osd, READ, delta_ms, npages * PAGE_SIZE, npages);
428
429         RETURN(npages);
430
431 err:
432         LASSERT(rc < 0);
433         if (dbp)
434                 dmu_buf_rele_array(dbp, numbufs, osd_0copy_tag);
435         osd_bufs_put(env, &obj->oo_dt, lnb - npages, npages);
436         RETURN(rc);
437 }
438
439 static inline arc_buf_t *osd_request_arcbuf(dnode_t *dn, size_t bs)
440 {
441         arc_buf_t *abuf;
442
443         abuf = dmu_request_arcbuf(&dn->dn_bonus->db, bs);
444         if (unlikely(!abuf))
445                 return ERR_PTR(-ENOMEM);
446
447 #if ZFS_VERSION_CODE < OBD_OCD_VERSION(0, 7, 0, 0)
448         /**
449          * ZFS prior to 0.7.0 doesn't guarantee PAGE_SIZE alignment for zio
450          * blocks smaller than (PAGE_SIZE << 2). This poses a problem of
451          * setting up page array for RDMA transfer. See LU-9305.
452          */
453         if ((unsigned long)abuf->b_data & ~PAGE_MASK) {
454                 dmu_return_arcbuf(abuf);
455                 return NULL;
456         }
457 #endif
458
459         return abuf;
460 }
461
462 static int osd_bufs_get_write(const struct lu_env *env, struct osd_object *obj,
463                               loff_t off, ssize_t len, struct niobuf_local *lnb,
464                               int maxlnb)
465 {
466         struct osd_device *osd = osd_obj2dev(obj);
467         int                poff, plen, off_in_block, sz_in_block;
468         int                rc, i = 0, npages = 0;
469         dnode_t *dn = obj->oo_dn;
470         arc_buf_t *abuf;
471         uint32_t bs = dn->dn_datablksz;
472         ENTRY;
473
474         /*
475          * currently only full blocks are subject to zerocopy approach:
476          * so that we're sure nobody is trying to update the same block
477          */
478         while (len > 0) {
479                 if (unlikely(npages >= maxlnb))
480                         GOTO(out_err, rc = -EOVERFLOW);
481
482                 off_in_block = off & (bs - 1);
483                 sz_in_block = min_t(int, bs - off_in_block, len);
484
485                 abuf = NULL;
486                 if (sz_in_block == bs) {
487                         /* full block, try to use zerocopy */
488                         abuf = osd_request_arcbuf(dn, bs);
489                         if (unlikely(IS_ERR(abuf)))
490                                 GOTO(out_err, rc = PTR_ERR(abuf));
491                 }
492
493                 if (abuf != NULL) {
494                         atomic_inc(&osd->od_zerocopy_loan);
495
496                         /* go over pages arcbuf contains, put them as
497                          * local niobufs for ptlrpc's bulks */
498                         while (sz_in_block > 0) {
499                                 plen = min_t(int, sz_in_block, PAGE_SIZE);
500
501                                 if (unlikely(npages >= maxlnb))
502                                         GOTO(out_err, rc = -EOVERFLOW);
503
504                                 lnb[i].lnb_file_offset = off;
505                                 lnb[i].lnb_page_offset = 0;
506                                 lnb[i].lnb_len = plen;
507                                 lnb[i].lnb_rc = 0;
508                                 if (sz_in_block == bs)
509                                         lnb[i].lnb_data = abuf;
510                                 else
511                                         lnb[i].lnb_data = NULL;
512
513                                 /* this one is not supposed to fail */
514                                 lnb[i].lnb_page = kmem_to_page(abuf->b_data +
515                                                         off_in_block);
516                                 LASSERT(lnb[i].lnb_page);
517
518                                 lprocfs_counter_add(osd->od_stats,
519                                                 LPROC_OSD_ZEROCOPY_IO, 1);
520
521                                 sz_in_block -= plen;
522                                 len -= plen;
523                                 off += plen;
524                                 off_in_block += plen;
525                                 i++;
526                                 npages++;
527                         }
528                 } else {
529                         if (off_in_block == 0 && len < bs &&
530                                         off + len >= obj->oo_attr.la_size)
531                                 lprocfs_counter_add(osd->od_stats,
532                                                 LPROC_OSD_TAIL_IO, 1);
533
534                         /* can't use zerocopy, allocate temp. buffers */
535                         poff = off & (PAGE_SIZE - 1);
536                         while (sz_in_block > 0) {
537                                 plen = min_t(int, poff + sz_in_block,
538                                              PAGE_SIZE);
539                                 plen -= poff;
540
541                                 if (unlikely(npages >= maxlnb))
542                                         GOTO(out_err, rc = -EOVERFLOW);
543
544                                 lnb[i].lnb_file_offset = off;
545                                 lnb[i].lnb_page_offset = poff;
546                                 poff = 0;
547
548                                 lnb[i].lnb_len = plen;
549                                 lnb[i].lnb_rc = 0;
550                                 lnb[i].lnb_data = NULL;
551
552                                 lnb[i].lnb_page = alloc_page(OSD_GFP_IO);
553                                 if (unlikely(lnb[i].lnb_page == NULL))
554                                         GOTO(out_err, rc = -ENOMEM);
555
556                                 LASSERT(lnb[i].lnb_page->mapping == NULL);
557                                 lnb[i].lnb_page->mapping = (void *)obj;
558
559                                 atomic_inc(&osd->od_zerocopy_alloc);
560                                 lprocfs_counter_add(osd->od_stats,
561                                                 LPROC_OSD_COPY_IO, 1);
562
563                                 sz_in_block -= plen;
564                                 len -= plen;
565                                 off += plen;
566                                 i++;
567                                 npages++;
568                         }
569                 }
570         }
571
572         RETURN(npages);
573
574 out_err:
575         osd_bufs_put(env, &obj->oo_dt, lnb, npages);
576         RETURN(rc);
577 }
578
579 static int osd_bufs_get(const struct lu_env *env, struct dt_object *dt,
580                         loff_t offset, ssize_t len, struct niobuf_local *lnb,
581                         int maxlnb, enum dt_bufs_type rw)
582 {
583         struct osd_object *obj  = osd_dt_obj(dt);
584         int                rc;
585
586         LASSERT(dt_object_exists(dt));
587         LASSERT(obj->oo_dn);
588
589         if (rw & DT_BUFS_TYPE_WRITE)
590                 rc = osd_bufs_get_write(env, obj, offset, len, lnb, maxlnb);
591         else
592                 rc = osd_bufs_get_read(env, obj, offset, len, lnb, maxlnb);
593
594         return rc;
595 }
596
597 static int osd_write_prep(const struct lu_env *env, struct dt_object *dt,
598                         struct niobuf_local *lnb, int npages)
599 {
600         struct osd_object *obj = osd_dt_obj(dt);
601
602         LASSERT(dt_object_exists(dt));
603         LASSERT(obj->oo_dn);
604
605         return 0;
606 }
607
608 static inline uint64_t osd_roundup2blocksz(uint64_t size,
609                                            uint64_t offset,
610                                            uint32_t blksz)
611 {
612         LASSERT(blksz > 0);
613
614         size += offset % blksz;
615
616         if (likely(is_power_of_2(blksz)))
617                 return PO2_ROUNDUP_TYPED(size, blksz, uint64_t);
618
619         size += blksz - 1;
620         do_div(size, blksz);
621         return size * blksz;
622 }
623
624 static int osd_declare_write_commit(const struct lu_env *env,
625                                     struct dt_object *dt,
626                                     struct niobuf_local *lnb, int npages,
627                                     struct thandle *th)
628 {
629         struct osd_object  *obj = osd_dt_obj(dt);
630         struct osd_device  *osd = osd_obj2dev(obj);
631         struct osd_thandle *oh;
632         uint64_t            offset = 0;
633         uint32_t            size = 0;
634         uint32_t blksz = obj->oo_dn->dn_datablksz;
635         int                 i, rc;
636         bool synced = false;
637         long long           space = 0;
638         struct page        *last_page = NULL;
639         unsigned long       discont_pages = 0;
640         enum osd_quota_local_flags local_flags = 0;
641         enum osd_qid_declare_flags declare_flags = OSD_QID_BLK;
642         ENTRY;
643
644         LASSERT(dt_object_exists(dt));
645         LASSERT(obj->oo_dn);
646
647         LASSERT(lnb);
648         LASSERT(npages > 0);
649
650         oh = container_of0(th, struct osd_thandle, ot_super);
651
652         for (i = 0; i < npages; i++) {
653                 if (last_page && lnb[i].lnb_page->index != (last_page->index + 1))
654                         ++discont_pages;
655                 last_page = lnb[i].lnb_page;
656                 if (lnb[i].lnb_rc)
657                         /* ENOSPC, network RPC error, etc.
658                          * We don't want to book space for pages which will be
659                          * skipped in osd_write_commit(). Hence we skip pages
660                          * with lnb_rc != 0 here too */
661                         continue;
662                 /* ignore quota for the whole request if any page is from
663                  * client cache or written by root.
664                  *
665                  * XXX once we drop the 1.8 client support, the checking
666                  * for whether page is from cache can be simplified as:
667                  * !(lnb[i].flags & OBD_BRW_SYNC)
668                  *
669                  * XXX we could handle this on per-lnb basis as done by
670                  * grant. */
671                 if ((lnb[i].lnb_flags & OBD_BRW_NOQUOTA) ||
672                     (lnb[i].lnb_flags & (OBD_BRW_FROM_GRANT | OBD_BRW_SYNC)) ==
673                     OBD_BRW_FROM_GRANT)
674                         declare_flags |= OSD_QID_FORCE;
675
676                 if (size == 0) {
677                         /* first valid lnb */
678                         offset = lnb[i].lnb_file_offset;
679                         size = lnb[i].lnb_len;
680                         continue;
681                 }
682                 if (offset + size == lnb[i].lnb_file_offset) {
683                         /* this lnb is contiguous to the previous one */
684                         size += lnb[i].lnb_len;
685                         continue;
686                 }
687
688                 osd_tx_hold_write(oh->ot_tx, obj->oo_dn->dn_object,
689                                   obj->oo_dn, offset, size);
690                 /* Estimating space to be consumed by a write is rather
691                  * complicated with ZFS. As a consequence, we don't account for
692                  * indirect blocks and just use as a rough estimate the worse
693                  * case where the old space is being held by a snapshot. Quota
694                  * overrun will be adjusted once the operation is committed, if
695                  * required. */
696                 space += osd_roundup2blocksz(size, offset, blksz);
697
698                 offset = lnb[i].lnb_file_offset;
699                 size = lnb[i].lnb_len;
700         }
701
702         if (size) {
703                 osd_tx_hold_write(oh->ot_tx, obj->oo_dn->dn_object, obj->oo_dn,
704                                   offset, size);
705                 space += osd_roundup2blocksz(size, offset, blksz);
706         }
707
708         /* backend zfs filesystem might be configured to store multiple data
709          * copies */
710         space  *= osd->od_os->os_copies;
711         space   = toqb(space);
712         CDEBUG(D_QUOTA, "writing %d pages, reserving %lldK of quota space\n",
713                npages, space);
714
715         record_start_io(osd, WRITE, discont_pages);
716 retry:
717         /* acquire quota space if needed */
718         rc = osd_declare_quota(env, osd, obj->oo_attr.la_uid,
719                                obj->oo_attr.la_gid, obj->oo_attr.la_projid,
720                                space, oh, &local_flags, declare_flags);
721
722         if (!synced && rc == -EDQUOT &&
723             (local_flags & QUOTA_FL_SYNC) != 0) {
724                 dt_sync(env, th->th_dev);
725                 synced = true;
726                 CDEBUG(D_QUOTA, "retry after sync\n");
727                 local_flags = 0;
728                 goto retry;
729         }
730
731         /* we need only to store the overquota flags in the first lnb for
732          * now, once we support multiple objects BRW, this code needs be
733          * revised. */
734         if (local_flags & QUOTA_FL_OVER_USRQUOTA)
735                 lnb[0].lnb_flags |= OBD_BRW_OVER_USRQUOTA;
736         if (local_flags & QUOTA_FL_OVER_GRPQUOTA)
737                 lnb[0].lnb_flags |= OBD_BRW_OVER_GRPQUOTA;
738 #ifdef ZFS_PROJINHERIT
739         if (local_flags & QUOTA_FL_OVER_PRJQUOTA)
740                 lnb[0].lnb_flags |= OBD_BRW_OVER_PRJQUOTA;
741 #endif
742
743         RETURN(rc);
744 }
745
746 /**
747  * Policy to grow ZFS block size by write pattern.
748  * For sequential write, it grows block size gradually until it reaches the
749  * maximum blocksize the dataset can support. Otherwise, it will pick a
750  * a block size by the writing region of this I/O.
751  */
752 static int osd_grow_blocksize(struct osd_object *obj, struct osd_thandle *oh,
753                               uint64_t start, uint64_t end)
754 {
755         struct osd_device       *osd = osd_obj2dev(obj);
756         dnode_t *dn = obj->oo_dn;
757         uint32_t                 blksz;
758         int                      rc = 0;
759
760         ENTRY;
761
762         if (dn->dn_maxblkid > 0) /* can't change block size */
763                 GOTO(out, rc);
764
765         if (dn->dn_datablksz >= osd->od_max_blksz)
766                 GOTO(out, rc);
767
768         down_write(&obj->oo_guard);
769
770         blksz = dn->dn_datablksz;
771         if (blksz >= osd->od_max_blksz) /* check again after grabbing lock */
772                 GOTO(out_unlock, rc);
773
774         /* now ZFS can support up to 16MB block size, and if the write
775          * is sequential, it just increases the block size gradually */
776         if (start <= blksz) { /* sequential */
777                 blksz = (uint32_t)min_t(uint64_t, osd->od_max_blksz, end);
778         } else { /* sparse, pick a block size by write region */
779                 blksz = (uint32_t)min_t(uint64_t, osd->od_max_blksz,
780                                         end - start);
781         }
782
783         if (!is_power_of_2(blksz))
784                 blksz = size_roundup_power2(blksz);
785
786         if (blksz > dn->dn_datablksz) {
787                 rc = -dmu_object_set_blocksize(osd->od_os, dn->dn_object,
788                                                blksz, 0, oh->ot_tx);
789                 LASSERT(ergo(rc == 0, dn->dn_datablksz >= blksz));
790                 if (rc < 0)
791                         CDEBUG(D_INODE, "object "DFID": change block size"
792                                "%u -> %u error rc = %d\n",
793                                PFID(lu_object_fid(&obj->oo_dt.do_lu)),
794                                dn->dn_datablksz, blksz, rc);
795         }
796         EXIT;
797 out_unlock:
798         up_write(&obj->oo_guard);
799 out:
800         return rc;
801 }
802
803 static void osd_evict_dbufs_after_write(struct osd_object *obj,
804                                         loff_t off, ssize_t len)
805 {
806         dmu_buf_t **dbp;
807         int i, rc, numbufs;
808
809         rc = -dmu_buf_hold_array_by_bonus(&obj->oo_dn->dn_bonus->db, off, len,
810                                           TRUE, osd_0copy_tag, &numbufs, &dbp);
811         if (unlikely(rc))
812                 return;
813
814         for (i = 0; i < numbufs; i++)
815                 dbuf_set_pending_evict(dbp[i]);
816
817         dmu_buf_rele_array(dbp, numbufs, osd_0copy_tag);
818 }
819
820 static int osd_write_commit(const struct lu_env *env, struct dt_object *dt,
821                         struct niobuf_local *lnb, int npages,
822                         struct thandle *th)
823 {
824         struct osd_object  *obj  = osd_dt_obj(dt);
825         struct osd_device  *osd = osd_obj2dev(obj);
826         struct osd_thandle *oh;
827         uint64_t            new_size = 0;
828         int                 i, abufsz, rc = 0, drop_cache = 0;
829         unsigned long      iosize = 0;
830         ENTRY;
831
832         LASSERT(dt_object_exists(dt));
833         LASSERT(obj->oo_dn);
834
835         LASSERT(th != NULL);
836         oh = container_of0(th, struct osd_thandle, ot_super);
837
838         /* adjust block size. Assume the buffers are sorted. */
839         (void)osd_grow_blocksize(obj, oh, lnb[0].lnb_file_offset,
840                                  lnb[npages - 1].lnb_file_offset +
841                                  lnb[npages - 1].lnb_len);
842
843         if (obj->oo_attr.la_size >= osd->od_readcache_max_filesize ||
844             lnb[npages - 1].lnb_file_offset + lnb[npages - 1].lnb_len >=
845             osd->od_readcache_max_filesize)
846                 drop_cache = 1;
847
848         if (OBD_FAIL_CHECK(OBD_FAIL_OST_MAPBLK_ENOSPC))
849                 RETURN(-ENOSPC);
850
851         /* LU-8791: take oo_guard to avoid the deadlock that changing block
852          * size and assigning arcbuf take place at the same time.
853          *
854          * Thread 1:
855          * osd_write_commit()
856          *  -> osd_grow_blocksize() with osd_object::oo_guard held
857          *   -> dmu_object_set_blocksize()
858          *    -> dnode_set_blksz(), with dnode_t::dn_struct_rwlock
859          *       write lock held
860          *     -> dbuf_new_size()
861          *      -> dmu_buf_will_dirty()
862          *       -> dbuf_read()
863          *        -> wait for the dbuf state to change
864          * Thread 2:
865          * osd_write_commit()
866          *  -> dmu_assign_arcbuf()
867          *   -> dbuf_assign_arcbuf(), set dbuf state to DB_FILL
868          *    -> dbuf_dirty()
869          *     -> try to hold the read lock of dnode_t::dn_struct_rwlock
870          *
871          * By taking the read lock, it can avoid thread 2 to enter into the
872          * critical section of assigning the arcbuf, while thread 1 is
873          * changing the block size.
874          */
875         down_read(&obj->oo_guard);
876         for (i = 0; i < npages; i++) {
877                 CDEBUG(D_INODE, "write %u bytes at %u\n",
878                         (unsigned) lnb[i].lnb_len,
879                         (unsigned) lnb[i].lnb_file_offset);
880
881                 if (lnb[i].lnb_rc) {
882                         /* ENOSPC, network RPC error, etc.
883                          * Unlike ldiskfs, zfs allocates new blocks on rewrite,
884                          * so we skip this page if lnb_rc is set to -ENOSPC */
885                         CDEBUG(D_INODE, "obj "DFID": skipping lnb[%u]: rc=%d\n",
886                                 PFID(lu_object_fid(&dt->do_lu)), i,
887                                 lnb[i].lnb_rc);
888                         continue;
889                 }
890
891                 if (new_size < lnb[i].lnb_file_offset + lnb[i].lnb_len)
892                         new_size = lnb[i].lnb_file_offset + lnb[i].lnb_len;
893                 if (lnb[i].lnb_page == NULL)
894                         continue;
895
896                 if (lnb[i].lnb_page->mapping == (void *)obj) {
897                         osd_dmu_write(osd, obj->oo_dn, lnb[i].lnb_file_offset,
898                                       lnb[i].lnb_len, kmap(lnb[i].lnb_page) +
899                                       lnb[i].lnb_page_offset, oh->ot_tx);
900                         kunmap(lnb[i].lnb_page);
901                         iosize += lnb[i].lnb_len;
902                         abufsz = lnb[i].lnb_len; /* to drop cache below */
903                 } else if (lnb[i].lnb_data) {
904                         int j, apages;
905                         LASSERT(((unsigned long)lnb[i].lnb_data & 1) == 0);
906                         /* buffer loaned for zerocopy, try to use it.
907                          * notice that dmu_assign_arcbuf() is smart
908                          * enough to recognize changed blocksize
909                          * in this case it fallbacks to dmu_write() */
910                         abufsz = arc_buf_size(lnb[i].lnb_data);
911                         LASSERT(abufsz & PAGE_MASK);
912                         apages = abufsz / PAGE_SIZE;
913                         LASSERT(i + apages <= npages);
914                         /* these references to pages must be invalidated
915                          * to prevent access in osd_bufs_put() */
916                         for (j = 0; j < apages; j++)
917                                 lnb[i + j].lnb_page = NULL;
918                         dmu_assign_arcbuf(&obj->oo_dn->dn_bonus->db,
919                                           lnb[i].lnb_file_offset,
920                                           lnb[i].lnb_data, oh->ot_tx);
921                         /* drop the reference, otherwise osd_put_bufs()
922                          * will be releasing it - bad! */
923                         lnb[i].lnb_data = NULL;
924                         atomic_dec(&osd->od_zerocopy_loan);
925                         iosize += abufsz;
926                 } else {
927                         /* we don't want to deal with cache if nothing
928                          * has been send to ZFS at this step */
929                         continue;
930                 }
931
932                 if (!drop_cache)
933                         continue;
934
935                 /* we have to mark dbufs for eviction here because
936                  * dmu_assign_arcbuf() may create a new dbuf for
937                  * loaned abuf */
938                 osd_evict_dbufs_after_write(obj, lnb[i].lnb_file_offset,
939                                             abufsz);
940         }
941         up_read(&obj->oo_guard);
942
943         if (unlikely(new_size == 0)) {
944                 /* no pages to write, no transno is needed */
945                 th->th_local = 1;
946                 /* it is important to return 0 even when all lnb_rc == -ENOSPC
947                  * since ofd_commitrw_write() retries several times on ENOSPC */
948                 record_end_io(osd, WRITE, 0, 0, 0);
949                 RETURN(0);
950         }
951
952         write_lock(&obj->oo_attr_lock);
953         if (obj->oo_attr.la_size < new_size) {
954                 obj->oo_attr.la_size = new_size;
955                 write_unlock(&obj->oo_attr_lock);
956                 /* osd_object_sa_update() will be copying directly from
957                  * oo_attr into dbuf. any update within a single txg will copy
958                  * the most actual */
959                 rc = osd_object_sa_update(obj, SA_ZPL_SIZE(osd),
960                                           &obj->oo_attr.la_size, 8, oh);
961         } else {
962                 write_unlock(&obj->oo_attr_lock);
963         }
964
965         record_end_io(osd, WRITE, 0, iosize, npages);
966
967         RETURN(rc);
968 }
969
970 static int osd_read_prep(const struct lu_env *env, struct dt_object *dt,
971                         struct niobuf_local *lnb, int npages)
972 {
973         struct osd_object *obj  = osd_dt_obj(dt);
974         int                i;
975         loff_t             eof;
976
977         LASSERT(dt_object_exists(dt));
978         LASSERT(obj->oo_dn);
979
980         read_lock(&obj->oo_attr_lock);
981         eof = obj->oo_attr.la_size;
982         read_unlock(&obj->oo_attr_lock);
983
984         for (i = 0; i < npages; i++) {
985                 if (unlikely(lnb[i].lnb_rc < 0))
986                         continue;
987
988                 lnb[i].lnb_rc = lnb[i].lnb_len;
989
990                 if (lnb[i].lnb_file_offset + lnb[i].lnb_len >= eof) {
991                         /* send complete pages all the time */
992                         if (eof <= lnb[i].lnb_file_offset)
993                                 lnb[i].lnb_rc = 0;
994
995                         /* all subsequent rc should be 0 */
996                         while (++i < npages)
997                                 lnb[i].lnb_rc = 0;
998                         break;
999                 }
1000         }
1001
1002         return 0;
1003 }
1004
1005 /*
1006  * Punch/truncate an object
1007  *
1008  *      IN:     db  - dmu_buf of the object to free data in.
1009  *              off - start of section to free.
1010  *              len - length of section to free (DMU_OBJECT_END => to EOF).
1011  *
1012  *      RETURN: 0 if success
1013  *              error code if failure
1014  *
1015  * The transaction passed to this routine must have
1016  * dmu_tx_hold_sa() and if off < size, dmu_tx_hold_free()
1017  * called and then assigned to a transaction group.
1018  */
1019 static int __osd_object_punch(objset_t *os, dnode_t *dn, dmu_tx_t *tx,
1020                                 uint64_t size, uint64_t off, uint64_t len)
1021 {
1022         int rc = 0;
1023
1024         /* Assert that the transaction has been assigned to a
1025            transaction group. */
1026         LASSERT(tx->tx_txg != 0);
1027         /*
1028          * Nothing to do if file already at desired length.
1029          */
1030         if (len == DMU_OBJECT_END && size == off)
1031                 return 0;
1032
1033         /* XXX: dnode_free_range() can be used to save on dnode lookup */
1034         if (off < size)
1035                 dmu_free_range(os, dn->dn_object, off, len, tx);
1036
1037         return rc;
1038 }
1039
1040 static int osd_punch(const struct lu_env *env, struct dt_object *dt,
1041                         __u64 start, __u64 end, struct thandle *th)
1042 {
1043         struct osd_object  *obj = osd_dt_obj(dt);
1044         struct osd_device  *osd = osd_obj2dev(obj);
1045         struct osd_thandle *oh;
1046         __u64               len;
1047         int                 rc = 0;
1048         ENTRY;
1049
1050         LASSERT(dt_object_exists(dt));
1051         LASSERT(osd_invariant(obj));
1052
1053         LASSERT(th != NULL);
1054         oh = container_of0(th, struct osd_thandle, ot_super);
1055
1056         write_lock(&obj->oo_attr_lock);
1057         /* truncate */
1058         if (end == OBD_OBJECT_EOF || end >= obj->oo_attr.la_size)
1059                 len = DMU_OBJECT_END;
1060         else
1061                 len = end - start;
1062         write_unlock(&obj->oo_attr_lock);
1063
1064         rc = __osd_object_punch(osd->od_os, obj->oo_dn, oh->ot_tx,
1065                                 obj->oo_attr.la_size, start, len);
1066         /* set new size */
1067         if (len == DMU_OBJECT_END) {
1068                 write_lock(&obj->oo_attr_lock);
1069                 obj->oo_attr.la_size = start;
1070                 write_unlock(&obj->oo_attr_lock);
1071                 rc = osd_object_sa_update(obj, SA_ZPL_SIZE(osd),
1072                                           &obj->oo_attr.la_size, 8, oh);
1073         }
1074         RETURN(rc);
1075 }
1076
1077 static int osd_declare_punch(const struct lu_env *env, struct dt_object *dt,
1078                         __u64 start, __u64 end, struct thandle *handle)
1079 {
1080         struct osd_object  *obj = osd_dt_obj(dt);
1081         struct osd_device  *osd = osd_obj2dev(obj);
1082         struct osd_thandle *oh;
1083         __u64               len;
1084         ENTRY;
1085
1086         oh = container_of0(handle, struct osd_thandle, ot_super);
1087
1088         read_lock(&obj->oo_attr_lock);
1089         if (end == OBD_OBJECT_EOF || end >= obj->oo_attr.la_size)
1090                 len = DMU_OBJECT_END;
1091         else
1092                 len = end - start;
1093
1094         /* declare we'll free some blocks ... */
1095         if (start < obj->oo_attr.la_size) {
1096                 read_unlock(&obj->oo_attr_lock);
1097                 dmu_tx_mark_netfree(oh->ot_tx);
1098                 dmu_tx_hold_free(oh->ot_tx, obj->oo_dn->dn_object, start, len);
1099         } else {
1100                 read_unlock(&obj->oo_attr_lock);
1101         }
1102
1103         RETURN(osd_declare_quota(env, osd, obj->oo_attr.la_uid,
1104                                  obj->oo_attr.la_gid, obj->oo_attr.la_projid,
1105                                  0, oh, NULL, OSD_QID_BLK));
1106 }
1107
1108 static int osd_ladvise(const struct lu_env *env, struct dt_object *dt,
1109                        __u64 start, __u64 end, enum lu_ladvise_type advice)
1110 {
1111         int     rc;
1112         ENTRY;
1113
1114         switch (advice) {
1115         default:
1116                 rc = -ENOTSUPP;
1117                 break;
1118         }
1119
1120         RETURN(rc);
1121 }
1122
1123 struct dt_body_operations osd_body_ops = {
1124         .dbo_read                       = osd_read,
1125         .dbo_declare_write              = osd_declare_write,
1126         .dbo_write                      = osd_write,
1127         .dbo_bufs_get                   = osd_bufs_get,
1128         .dbo_bufs_put                   = osd_bufs_put,
1129         .dbo_write_prep                 = osd_write_prep,
1130         .dbo_declare_write_commit       = osd_declare_write_commit,
1131         .dbo_write_commit               = osd_write_commit,
1132         .dbo_read_prep                  = osd_read_prep,
1133         .dbo_declare_punch              = osd_declare_punch,
1134         .dbo_punch                      = osd_punch,
1135         .dbo_ladvise                    = osd_ladvise,
1136 };
1137
1138 struct dt_body_operations osd_body_scrub_ops = {
1139         .dbo_read                       = osd_read_no_record,
1140         .dbo_declare_write              = osd_declare_write,
1141         .dbo_write                      = osd_write,
1142 };