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