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