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