Whamcloud - gitweb
LU-17022 osd: convert od_connects to atomic_t
[fs/lustre-release.git] / lustre / osd-ldiskfs / osd_handler.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) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/osd/osd_handler.c
32  *
33  * Top-level entry points into osd module
34  *
35  * Author: Nikita Danilov <nikita@clusterfs.com>
36  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
37  */
38
39 #define DEBUG_SUBSYSTEM S_OSD
40
41 #include <linux/fs_struct.h>
42 #include <linux/module.h>
43 #include <linux/user_namespace.h>
44 #include <linux/uidgid.h>
45 #ifdef HAVE_INODE_IVERSION
46 #include <linux/iversion.h>
47 #else
48 #define inode_peek_iversion(__inode)    ((__inode)->i_version)
49 #endif
50
51 /* prerequisite for linux/xattr.h */
52 #include <linux/types.h>
53 /* prerequisite for linux/xattr.h */
54 #include <linux/fs.h>
55 /* XATTR_{REPLACE,CREATE} */
56 #include <linux/xattr.h>
57
58 #include <ldiskfs/ldiskfs.h>
59 #include <ldiskfs/xattr.h>
60 #include <ldiskfs/ldiskfs_extents.h>
61 #undef ENTRY
62 /*
63  * struct OBD_{ALLOC,FREE}*()
64  */
65 #include <obd_support.h>
66 #include <libcfs/libcfs.h>
67 /* struct ptlrpc_thread */
68 #include <lustre_net.h>
69 #include <lustre_fid.h>
70 /* process_config */
71 #include <uapi/linux/lustre/lustre_param.h>
72 #include <uapi/linux/lustre/lustre_disk.h>
73
74 #include "osd_internal.h"
75 #include "osd_dynlocks.h"
76
77 /* llo_* api support */
78 #include <md_object.h>
79 #include <lustre_quota.h>
80
81 #include <lustre_linkea.h>
82
83 /* encoding routines */
84 #include <lustre_crypto.h>
85
86 /* Maximum EA size is limited by LNET_MTU for remote objects */
87 #define OSD_MAX_EA_SIZE 1048364
88
89 int ldiskfs_pdo = 1;
90 module_param(ldiskfs_pdo, int, 0644);
91 MODULE_PARM_DESC(ldiskfs_pdo, "ldiskfs with parallel directory operations");
92
93 int ldiskfs_track_declares_assert;
94 module_param(ldiskfs_track_declares_assert, int, 0644);
95 MODULE_PARM_DESC(ldiskfs_track_declares_assert, "LBUG during tracking of declares");
96
97 /* 1 GiB in 512-byte sectors */
98 int ldiskfs_delayed_unlink_blocks = (1 << (30 - 9));
99
100 /* Slab to allocate dynlocks */
101 struct kmem_cache *dynlock_cachep;
102
103 /* Slab to allocate osd_it_ea */
104 struct kmem_cache *osd_itea_cachep;
105
106 static struct lu_kmem_descr ldiskfs_caches[] = {
107         {
108                 .ckd_cache = &biop_cachep,
109                 .ckd_name  = "biop_cache",
110                 .ckd_size  = sizeof(struct osd_bio_private)
111         },
112         {
113                 .ckd_cache = &dynlock_cachep,
114                 .ckd_name  = "dynlock_cache",
115                 .ckd_size  = sizeof(struct dynlock_handle)
116         },
117         {
118                 .ckd_cache = &osd_itea_cachep,
119                 .ckd_name  = "osd_itea_cache",
120                 .ckd_size  = sizeof(struct osd_it_ea)
121         },
122         {
123                 .ckd_cache = NULL
124         }
125 };
126
127 static atomic_t osd_mount_seq;
128
129 static const char dot[] = ".";
130 static const char dotdot[] = "..";
131
132 static const struct lu_object_operations      osd_lu_obj_ops;
133 static const struct dt_object_operations      osd_obj_ops;
134 static const struct dt_object_operations      osd_obj_otable_it_ops;
135 static const struct dt_index_operations       osd_index_iam_ops;
136 static const struct dt_index_operations       osd_index_ea_ops;
137
138 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
139                           const struct lu_fid *fid);
140 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
141                                                 struct osd_device *osd);
142 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
143                          const struct lu_buf *buf, const char *name, int fl,
144                          struct thandle *handle);
145
146 int osd_trans_declare_op2rb[] = {
147         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
148         [OSD_OT_PUNCH]          = OSD_OT_MAX,
149         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
150         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
151         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
152         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
153         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
154         [OSD_OT_WRITE]          = OSD_OT_WRITE,
155         [OSD_OT_INSERT]         = OSD_OT_DELETE,
156         [OSD_OT_DELETE]         = OSD_OT_INSERT,
157         [OSD_OT_QUOTA]          = OSD_OT_MAX,
158 };
159
160 static int osd_has_index(const struct osd_object *obj)
161 {
162         return obj->oo_dt.do_index_ops != NULL;
163 }
164
165 static int osd_object_invariant(const struct lu_object *l)
166 {
167         return osd_invariant(osd_obj(l));
168 }
169
170 /*
171  * Concurrency: doesn't matter
172  */
173 static int osd_is_write_locked(const struct lu_env *env, struct osd_object *o)
174 {
175         struct osd_thread_info *oti = osd_oti_get(env);
176
177         return oti->oti_w_locks > 0 && o->oo_owner == env;
178 }
179
180 /*
181  * Concurrency: doesn't access mutable data
182  */
183 static int osd_root_get(const struct lu_env *env,
184                         struct dt_device *dev, struct lu_fid *f)
185 {
186         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
187         return 0;
188 }
189
190 /*
191  * the following set of functions are used to maintain per-thread
192  * cache of FID->ino mapping. this mechanism is needed to resolve
193  * FID to inode at dt_insert() which in turn stores ino in the
194  * directory entries to keep ldiskfs compatible with ext[34].
195  * due to locking-originated restrictions we can't lookup ino
196  * using LU cache (deadlock is possible). lookup using OI is quite
197  * expensive. so instead we maintain this cache and methods like
198  * dt_create() fill it. so in the majority of cases dt_insert() is
199  * able to find needed mapping in lockless manner.
200  */
201 static struct osd_idmap_cache *
202 osd_idc_find(const struct lu_env *env, struct osd_device *osd,
203              const struct lu_fid *fid)
204 {
205         struct osd_thread_info *oti = osd_oti_get(env);
206         struct osd_idmap_cache *idc = oti->oti_ins_cache;
207         int i;
208
209         for (i = 0; i < oti->oti_ins_cache_used; i++) {
210                 if (!lu_fid_eq(&idc[i].oic_fid, fid))
211                         continue;
212                 if (idc[i].oic_dev != osd)
213                         continue;
214
215                 return idc + i;
216         }
217
218         return NULL;
219 }
220
221 static struct osd_idmap_cache *
222 osd_idc_add(const struct lu_env *env, struct osd_device *osd,
223             const struct lu_fid *fid)
224 {
225         struct osd_thread_info *oti   = osd_oti_get(env);
226         struct osd_idmap_cache *idc;
227         int i;
228
229         if (unlikely(oti->oti_ins_cache_used >= oti->oti_ins_cache_size)) {
230                 i = oti->oti_ins_cache_size * 2;
231                 if (i == 0)
232                         i = OSD_INS_CACHE_SIZE;
233                 OBD_ALLOC_PTR_ARRAY_LARGE(idc, i);
234                 if (idc == NULL)
235                         return ERR_PTR(-ENOMEM);
236                 if (oti->oti_ins_cache != NULL) {
237                         memcpy(idc, oti->oti_ins_cache,
238                                oti->oti_ins_cache_used * sizeof(*idc));
239                         OBD_FREE_PTR_ARRAY_LARGE(oti->oti_ins_cache,
240                                            oti->oti_ins_cache_used);
241                 }
242                 oti->oti_ins_cache = idc;
243                 oti->oti_ins_cache_size = i;
244         }
245
246         idc = oti->oti_ins_cache + oti->oti_ins_cache_used++;
247         idc->oic_fid = *fid;
248         idc->oic_dev = osd;
249         idc->oic_lid.oii_ino = 0;
250         idc->oic_lid.oii_gen = 0;
251         idc->oic_remote = 0;
252
253         return idc;
254 }
255
256 /*
257  * lookup mapping for the given fid in the cache, initialize a
258  * new one if not found. the initialization checks whether the
259  * object is local or remote. for local objects, OI is used to
260  * learn ino/generation. the function is used when the caller
261  * has no information about the object, e.g. at dt_insert().
262  */
263 static struct osd_idmap_cache *
264 osd_idc_find_or_init(const struct lu_env *env, struct osd_device *osd,
265                      const struct lu_fid *fid)
266 {
267         struct osd_idmap_cache *idc;
268         int rc;
269
270         idc = osd_idc_find(env, osd, fid);
271         LASSERT(!IS_ERR(idc));
272         if (idc != NULL)
273                 return idc;
274
275         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
276                osd->od_svname, PFID(fid));
277
278         /* new mapping is needed */
279         idc = osd_idc_add(env, osd, fid);
280         if (IS_ERR(idc)) {
281                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
282                        osd->od_svname, PFID(fid), PTR_ERR(idc));
283                 return idc;
284         }
285
286         /* initialize it */
287         rc = osd_remote_fid(env, osd, fid);
288         if (unlikely(rc < 0))
289                 return ERR_PTR(rc);
290
291         if (rc == 0) {
292                 /* the object is local, lookup in OI */
293                 /* XXX: probably cheaper to lookup in LU first? */
294                 rc = osd_oi_lookup(osd_oti_get(env), osd, fid,
295                                    &idc->oic_lid, 0);
296                 if (unlikely(rc < 0)) {
297                         CERROR("can't lookup: rc = %d\n", rc);
298                         return ERR_PTR(rc);
299                 }
300         } else {
301                 /* the object is remote */
302                 idc->oic_remote = 1;
303         }
304
305         return idc;
306 }
307
308 static void osd_idc_dump_lma(const struct lu_env *env,
309                                 struct osd_device *osd,
310                                 unsigned long ino,
311                                 bool check_in_oi)
312 {
313         struct osd_thread_info *info = osd_oti_get(env);
314         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
315         const struct lu_fid *fid;
316         struct osd_inode_id lid;
317         struct inode *inode;
318         int rc;
319
320         inode = osd_ldiskfs_iget(osd_sb(osd), ino);
321         if (IS_ERR(inode)) {
322                 CERROR("%s: can't get inode %lu: rc = %d\n",
323                        osd->od_svname, ino, (int)PTR_ERR(inode));
324                 return;
325         }
326         if (is_bad_inode(inode)) {
327                 CERROR("%s: bad inode %lu\n", osd->od_svname, ino);
328                 goto put;
329         }
330         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
331         if (rc) {
332                 CERROR("%s: can't get LMA for %lu: rc = %d\n",
333                        osd->od_svname, ino, rc);
334                 goto put;
335         }
336         fid = &loa->loa_lma.lma_self_fid;
337         LCONSOLE(D_INFO, "%s: "DFID" in inode %lu/%u\n", osd->od_svname,
338                       PFID(fid), ino, (unsigned)inode->i_generation);
339         if (!check_in_oi)
340                 goto put;
341         rc = osd_oi_lookup(osd_oti_get(env), osd, fid, &lid, 0);
342         if (rc) {
343                 CERROR("%s: can't lookup "DFID": rc = %d\n",
344                        osd->od_svname, PFID(fid), rc);
345                 goto put;
346         }
347         LCONSOLE(D_INFO, "%s: "DFID" maps to %u/%u\n", osd->od_svname,
348                       PFID(fid), lid.oii_ino, lid.oii_gen);
349 put:
350         iput(inode);
351 }
352
353 static void osd_idc_dump_debug(const struct lu_env *env,
354                                 struct osd_device *osd,
355                                 const struct lu_fid *fid,
356                                 unsigned long ino1,
357                                 unsigned long ino2)
358 {
359         struct osd_inode_id lid;
360
361         int rc;
362
363         rc = osd_oi_lookup(osd_oti_get(env), osd, fid, &lid, 0);
364         if (!rc) {
365                 LCONSOLE(D_INFO, "%s: "DFID" maps to %u/%u\n",
366                         osd->od_svname, PFID(fid), lid.oii_ino, lid.oii_gen);
367                 osd_idc_dump_lma(env, osd, lid.oii_ino, false);
368         } else {
369                 CERROR("%s: can't lookup "DFID": rc = %d\n",
370                        osd->od_svname, PFID(fid), rc);
371         }
372         if (ino1)
373                 osd_idc_dump_lma(env, osd, ino1, true);
374         if (ino2)
375                 osd_idc_dump_lma(env, osd, ino2, true);
376 }
377
378 /*
379  * lookup mapping for given FID and fill it from the given object.
380  * the object is lolcal by definition.
381  */
382 static int osd_idc_find_and_init(const struct lu_env *env,
383                                  struct osd_device *osd,
384                                  struct osd_object *obj)
385 {
386         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
387         struct osd_idmap_cache *idc;
388
389         idc = osd_idc_find(env, osd, fid);
390         LASSERT(!IS_ERR(idc));
391         if (idc != NULL) {
392                 if (obj->oo_inode == NULL)
393                         return 0;
394                 if (idc->oic_lid.oii_ino != obj->oo_inode->i_ino) {
395                         if (idc->oic_lid.oii_ino) {
396                                 osd_idc_dump_debug(env, osd, fid,
397                                                    idc->oic_lid.oii_ino,
398                                                    obj->oo_inode->i_ino);
399                                 return -EINVAL;
400                         }
401                         idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
402                         idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
403                 }
404                 return 0;
405         }
406
407         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
408                osd->od_svname, PFID(fid));
409
410         /* new mapping is needed */
411         idc = osd_idc_add(env, osd, fid);
412         if (IS_ERR(idc)) {
413                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
414                        osd->od_svname, PFID(fid), PTR_ERR(idc));
415                 return PTR_ERR(idc);
416         }
417
418         if (obj->oo_inode != NULL) {
419                 idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
420                 idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
421         }
422         return 0;
423 }
424
425 /*
426  * OSD object methods.
427  */
428
429 /*
430  * Concurrency: no concurrent access is possible that early in object
431  * life-cycle.
432  */
433 static struct lu_object *osd_object_alloc(const struct lu_env *env,
434                                           const struct lu_object_header *hdr,
435                                           struct lu_device *d)
436 {
437         struct osd_object *mo;
438
439         OBD_ALLOC_PTR(mo);
440         if (mo != NULL) {
441                 struct lu_object *l;
442                 struct lu_object_header *h;
443                 struct osd_device *o = osd_dev(d);
444
445                 l = &mo->oo_dt.do_lu;
446                 if (unlikely(o->od_in_init)) {
447                         OBD_ALLOC_PTR(h);
448                         if (!h) {
449                                 OBD_FREE_PTR(mo);
450                                 return NULL;
451                         }
452
453                         lu_object_header_init(h);
454                         lu_object_init(l, h, d);
455                         lu_object_add_top(h, l);
456                         mo->oo_header = h;
457                 } else {
458                         dt_object_init(&mo->oo_dt, NULL, d);
459                         mo->oo_header = NULL;
460                 }
461
462                 mo->oo_dt.do_ops = &osd_obj_ops;
463                 l->lo_ops = &osd_lu_obj_ops;
464                 init_rwsem(&mo->oo_sem);
465                 init_rwsem(&mo->oo_ext_idx_sem);
466                 spin_lock_init(&mo->oo_guard);
467                 INIT_LIST_HEAD(&mo->oo_xattr_list);
468                 return l;
469         }
470         return NULL;
471 }
472
473 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
474                 struct dentry *dentry, struct lustre_ost_attrs *loa)
475 {
476         int rc;
477
478         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
479                              (void *)loa, sizeof(*loa));
480         if (rc > 0) {
481                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
482
483                 if (rc < sizeof(*lma))
484                         return -EINVAL;
485
486                 rc = 0;
487                 lustre_loa_swab(loa, true);
488                 /* Check LMA compatibility */
489                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
490                         rc = -EOPNOTSUPP;
491                         CWARN("%s: unsupported incompat LMA feature(s) %#x for fid = "DFID", ino = %lu: rc = %d\n",
492                               osd_ino2name(inode),
493                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
494                               PFID(&lma->lma_self_fid), inode->i_ino, rc);
495                 }
496         } else if (rc == 0) {
497                 rc = -ENODATA;
498         }
499
500         return rc;
501 }
502
503 /*
504  * retrieve object from backend ext fs.
505  **/
506 static struct inode *osd_iget2(struct osd_thread_info *info,
507                                struct osd_device *dev, struct osd_inode_id *id,
508                                int *err)
509 {
510         int rc = 0;
511         struct inode *inode = NULL;
512
513         /*
514          * if we look for an inode withing a running
515          * transaction, then we risk to deadlock
516          * osd_dirent_check_repair() breaks this
517          */
518          /* LASSERT(current->journal_info == NULL); */
519
520         inode = osd_ldiskfs_iget(osd_sb(dev), id->oii_ino);
521         if (IS_ERR(inode)) {
522                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
523                        id->oii_ino, PTR_ERR(inode));
524         } else if (id->oii_gen != OSD_OII_NOGEN &&
525                    inode->i_generation != id->oii_gen) {
526                 CDEBUG(D_INODE, "unmatched inode: ino = %u, oii_gen = %u, "
527                        "i_generation = %u\n",
528                        id->oii_ino, id->oii_gen, inode->i_generation);
529                 rc = -ESTALE;
530         } else if (inode->i_nlink == 0) {
531                 /*
532                  * due to parallel readdir and unlink,
533                  * we can have dead inode here.
534                  */
535                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
536                 rc = -ESTALE;
537         } else if (is_bad_inode(inode)) {
538                 CWARN("%s: bad inode: ino = %u: rc = %d\n",
539                       osd_dev2name(dev), id->oii_ino, -ENOENT);
540                 rc = -ENOENT;
541         } else  if (osd_is_ea_inode(inode)) {
542                 /*
543                  * EA inode is internal ldiskfs object, should don't visible
544                  * on osd
545                  */
546                 CDEBUG(D_INODE, "EA inode: ino = %u\n", id->oii_ino);
547                 rc = -ENOENT;
548         } else if ((rc = osd_attach_jinode(inode))) {
549                 CDEBUG(D_INODE, "jbd: ino = %u rc = %d\n", id->oii_ino, rc);
550         } else {
551                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
552                 if (id->oii_gen == OSD_OII_NOGEN)
553                         osd_id_gen(id, inode->i_ino, inode->i_generation);
554
555                 /*
556                  * Do not update file c/mtime in ldiskfs.
557                  * NB: we don't have any lock to protect this because we don't
558                  * have reference on osd_object now, but contention with
559                  * another lookup + attr_set can't happen in the tiny window
560                  * between if (...) and set S_NOCMTIME.
561                  */
562                 if (!(inode->i_flags & S_NOCMTIME))
563                         inode->i_flags |= S_NOCMTIME;
564         }
565
566         *err = rc;
567
568         return inode;
569 }
570
571 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
572                        struct osd_inode_id *id)
573 {
574         struct inode *inode;
575         int rc = 0;
576
577         inode = osd_iget2(info, dev, id, &rc);
578
579         if (rc) {
580                 iput(inode);
581                 inode = ERR_PTR(rc);
582         }
583
584         return inode;
585 }
586
587 int osd_ldiskfs_add_entry(struct osd_thread_info *info, struct osd_device *osd,
588                           handle_t *handle, struct dentry *child,
589                           struct inode *inode, struct htree_lock *hlock)
590 {
591         int rc, rc2;
592
593         rc = __ldiskfs_add_entry(handle, child, inode, hlock);
594         if (rc == -ENOBUFS || rc == -ENOSPC) {
595                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
596                 struct inode *parent = child->d_parent->d_inode;
597                 struct lu_fid *fid = NULL;
598                 char fidstr[FID_LEN + 1] = "unknown";
599
600                 rc2 = osd_get_lma(info, parent, child->d_parent, loa);
601                 if (!rc2) {
602                         fid = &loa->loa_lma.lma_self_fid;
603                 } else if (rc2 == -ENODATA) {
604                         if (unlikely(is_root_inode(parent))) {
605                                 fid = &info->oti_fid3;
606                                 lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
607                         } else if (!osd->od_is_ost && osd->od_index == 0) {
608                                 fid = &info->oti_fid3;
609                                 lu_igif_build(fid, parent->i_ino,
610                                               parent->i_generation);
611                         }
612                 }
613
614                 if (fid != NULL)
615                         snprintf(fidstr, sizeof(fidstr), DFID, PFID(fid));
616
617                 /* below message is checked in sanity.sh test_129 */
618                 if (rc == -ENOSPC) {
619                         CWARN("%s: directory (inode: %lu, FID: %s) has reached max size limit\n",
620                               osd_name(osd), parent->i_ino, fidstr);
621                 } else {
622                         rc = 0; /* ignore such error now */
623                         CWARN("%s: directory (inode: %lu, FID: %s) is approaching max size limit\n",
624                               osd_name(osd), parent->i_ino, fidstr);
625                 }
626
627         }
628
629         return rc;
630 }
631
632
633 struct inode *
634 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
635              struct osd_inode_id *id, struct lu_fid *fid)
636 {
637         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
638         struct inode *inode;
639         int rc;
640
641         inode = osd_iget(info, dev, id);
642         if (IS_ERR(inode))
643                 return inode;
644
645         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
646         if (!rc) {
647                 *fid = loa->loa_lma.lma_self_fid;
648         } else if (rc == -ENODATA) {
649                 if (unlikely(is_root_inode(inode)))
650                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
651                 else
652                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
653         } else {
654                 iput(inode);
655                 inode = ERR_PTR(rc);
656         }
657         return inode;
658 }
659
660 static struct inode *osd_iget_check(struct osd_thread_info *info,
661                                     struct osd_device *dev,
662                                     const struct lu_fid *fid,
663                                     struct osd_inode_id *id,
664                                     bool trusted)
665 {
666         struct inode *inode;
667         int rc = 0;
668
669         ENTRY;
670
671         /*
672          * The cached OI mapping is trustable. If we cannot locate the inode
673          * via the cached OI mapping, then return the failure to the caller
674          * directly without further OI checking.
675          */
676
677 again:
678         inode = osd_iget2(info, dev, id, &rc);
679         if (rc) {
680                 if (!trusted && (rc == -ENOENT || rc == -ESTALE))
681                         goto check_oi;
682
683                 CDEBUG(D_INODE, "no inode for FID: "DFID", ino = %u, rc = %d\n",
684                        PFID(fid), id->oii_ino, rc);
685                 GOTO(put, rc);
686         }
687
688 check_oi:
689         if (rc != 0) {
690                 __u32 saved_ino = id->oii_ino;
691                 __u32 saved_gen = id->oii_gen;
692
693                 LASSERT(!trusted);
694                 LASSERTF(rc == -ESTALE || rc == -ENOENT, "rc = %d\n", rc);
695
696                 rc = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
697                 /*
698                  * XXX: There are four possible cases:
699                  *      1. rc = 0.
700                  *         Backup/restore caused the OI invalid.
701                  *      2. rc = 0.
702                  *         Someone unlinked the object but NOT removed
703                  *         the OI mapping, such as mount target device
704                  *         as ldiskfs, and modify something directly.
705                  *      3. rc = -ENOENT.
706                  *         Someone just removed the object between the
707                  *         former oi_lookup and the iget. It is normal.
708                  *      4. Other failure cases.
709                  *
710                  *      Generally, when the device is mounted, it will
711                  *      auto check whether the system is restored from
712                  *      file-level backup or not. We trust such detect
713                  *      to distinguish the 1st case from the 2nd case:
714                  *      if the OI files are consistent but may contain
715                  *      stale OI mappings because of case 2, if iget()
716                  *      returns -ENOENT or -ESTALE, then it should be
717                  *      the case 2.
718                  */
719                 if (rc != 0)
720                         /*
721                          * If the OI mapping was in OI file before the
722                          * osd_iget_check(), but now, it is disappear,
723                          * then it must be removed by race. That is a
724                          * normal race case.
725                          */
726                         GOTO(put, rc);
727
728                 /*
729                  * It is the OI scrub updated the OI mapping by race.
730                  * The new OI mapping must be valid.
731                  */
732                 if (saved_ino != id->oii_ino ||
733                     (saved_gen != id->oii_gen && saved_gen != OSD_OII_NOGEN)) {
734                         if (!IS_ERR(inode))
735                                 iput(inode);
736
737                         trusted = true;
738                         goto again;
739                 }
740
741                 if (IS_ERR(inode)) {
742                         if (dev->od_scrub.os_scrub.os_file.sf_flags &
743                             SF_INCONSISTENT)
744                                 /*
745                                  * It still can be the case 2, but we cannot
746                                  * distinguish it from the case 1. So return
747                                  * -EREMCHG to block current operation until
748                                  *  OI scrub rebuilt the OI mappings.
749                                  */
750                                 rc = -EREMCHG;
751                         else
752                                 rc = -ENOENT;
753
754                         GOTO(put, rc);
755                 }
756
757                 if (inode->i_generation == id->oii_gen)
758                         rc = -ENOENT;
759                 else
760                         rc = -EREMCHG;
761         }
762
763         GOTO(put, rc);
764
765 put:
766         if (rc != 0) {
767                 if (!IS_ERR(inode))
768                         iput(inode);
769
770                 inode = ERR_PTR(rc);
771         }
772
773         return inode;
774 }
775
776 /**
777  * \retval +v: new filter_fid does not contain self-fid
778  * \retval 0:  filter_fid_18_23, contains self-fid
779  * \retval -v: other failure cases
780  */
781 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
782                  struct dentry *dentry, struct lu_fid *fid)
783 {
784         struct filter_fid *ff = &info->oti_ff;
785         struct ost_id *ostid = &info->oti_ostid;
786         int rc;
787
788         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
789         if (rc == sizeof(struct filter_fid_18_23)) {
790                 struct filter_fid_18_23 *ff_old = (void *)ff;
791
792                 ostid_set_seq(ostid, le64_to_cpu(ff_old->ff_seq));
793                 rc = ostid_set_id(ostid, le64_to_cpu(ff_old->ff_objid));
794                 /*
795                  * XXX: use 0 as the index for compatibility, the caller will
796                  * handle index related issues when necessary.
797                  */
798                 if (!rc)
799                         ostid_to_fid(fid, ostid, 0);
800         } else if (rc >= (int)sizeof(struct filter_fid_24_29)) {
801                 rc = 1;
802         } else if (rc >= 0) {
803                 rc = -EINVAL;
804         }
805
806         return rc;
807 }
808
809 static int osd_lma_self_repair(struct osd_thread_info *info,
810                                struct osd_device *osd, struct inode *inode,
811                                const struct lu_fid *fid, __u32 compat)
812 {
813         handle_t *jh;
814         int rc;
815
816         LASSERT(current->journal_info == NULL);
817
818         jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC,
819                                   osd_dto_credits_noquota[DTO_XATTR_SET]);
820         if (IS_ERR(jh)) {
821                 rc = PTR_ERR(jh);
822                 CWARN("%s: cannot start journal for lma_self_repair: rc = %d\n",
823                       osd_name(osd), rc);
824                 return rc;
825         }
826
827         rc = osd_ea_fid_set(info, inode, fid, compat, 0);
828         if (rc != 0)
829                 CWARN("%s: cannot self repair the LMA: rc = %d\n",
830                       osd_name(osd), rc);
831         ldiskfs_journal_stop(jh);
832         return rc;
833 }
834
835 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
836 {
837         struct osd_thread_info *info = osd_oti_get(env);
838         struct osd_device *osd = osd_obj2dev(obj);
839         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
840         struct lustre_mdt_attrs *lma = &loa->loa_lma;
841         struct inode *inode = obj->oo_inode;
842         struct dentry *dentry = &info->oti_obj_dentry;
843         struct lu_fid *fid = NULL;
844         const struct lu_fid *rfid = lu_object_fid(&obj->oo_dt.do_lu);
845         int rc;
846
847         ENTRY;
848
849         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
850                              (void *)loa, sizeof(*loa));
851         if (rc == -ENODATA && !fid_is_igif(rfid) && osd->od_check_ff) {
852                 fid = &lma->lma_self_fid;
853                 rc = osd_get_idif(info, inode, dentry, fid);
854                 if (rc > 0 || (rc == -ENODATA && osd->od_index_in_idif)) {
855                         /*
856                          * For the given OST-object, if it has neither LMA nor
857                          * FID in XATTR_NAME_FID, then the given FID (which is
858                          * contained in the @obj, from client RPC for locating
859                          * the OST-object) is trusted. We use it to generate
860                          * the LMA.
861                          */
862                         osd_lma_self_repair(info, osd, inode, rfid,
863                                             LMAC_FID_ON_OST);
864                         RETURN(0);
865                 }
866         }
867
868         if (rc < 0)
869                 RETURN(rc);
870
871         if (rc > 0) {
872                 rc = 0;
873                 lustre_lma_swab(lma);
874                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
875                              (CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT) &&
876                               S_ISREG(inode->i_mode)))) {
877                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
878                               "fid = "DFID", ino = %lu\n", osd_name(osd),
879                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
880                               PFID(rfid), inode->i_ino);
881                         rc = -EOPNOTSUPP;
882                 } else {
883                         fid = &lma->lma_self_fid;
884                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
885                             osd->od_is_ost)
886                                 obj->oo_pfid_in_lma = 1;
887                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
888                             !osd->od_is_ost)
889                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
890                 }
891         }
892
893         if (fid != NULL && unlikely(!lu_fid_eq(rfid, fid))) {
894                 if (fid_is_idif(rfid) && fid_is_idif(fid)) {
895                         struct ost_id   *oi   = &info->oti_ostid;
896                         struct lu_fid   *fid1 = &info->oti_fid3;
897                         __u32            idx  = fid_idif_ost_idx(rfid);
898
899                         /*
900                          * For old IDIF, the OST index is not part of the IDIF,
901                          * Means that different OSTs may have the same IDIFs.
902                          * Under such case, we need to make some compatible
903                          * check to make sure to trigger OI scrub properly.
904                          */
905                         if (idx != 0 && fid_idif_ost_idx(fid) == 0) {
906                                 /* Given @rfid is new, LMA is old. */
907                                 fid_to_ostid(fid, oi);
908                                 ostid_to_fid(fid1, oi, idx);
909                                 if (lu_fid_eq(fid1, rfid)) {
910                                         if (osd->od_index_in_idif)
911                                                 osd_lma_self_repair(info, osd,
912                                                         inode, rfid,
913                                                         LMAC_FID_ON_OST);
914                                         RETURN(0);
915                                 }
916                         }
917                 }
918
919                 rc = -EREMCHG;
920         }
921
922         RETURN(rc);
923 }
924
925 struct osd_check_lmv_buf {
926         /* please keep it as first member */
927         struct dir_context ctx;
928         struct osd_thread_info *oclb_info;
929         struct osd_device *oclb_dev;
930         int oclb_items;
931         bool oclb_found;
932 };
933
934 /**
935  * It is called internally by ->iterate*() to filter out the
936  * local slave object's FID of the striped directory.
937  *
938  * \retval      1 found the local slave's FID
939  * \retval      0 continue to check next item
940  * \retval      -ve for failure
941  */
942 #ifdef HAVE_FILLDIR_USE_CTX
943 static FILLDIR_TYPE do_osd_stripe_dir_filldir(struct dir_context *buf,
944 #else
945 static int osd_stripe_dir_filldir(void *buf,
946 #endif
947                                   const char *name, int namelen,
948                                   loff_t offset, __u64 ino, unsigned int d_type)
949 {
950         struct osd_check_lmv_buf *oclb = (struct osd_check_lmv_buf *)buf;
951         struct osd_thread_info *oti = oclb->oclb_info;
952         struct lu_fid *fid = &oti->oti_fid3;
953         struct osd_inode_id *id = &oti->oti_id3;
954         struct osd_inode_id id2;
955         struct osd_device *dev = oclb->oclb_dev;
956         struct inode *inode;
957
958         oclb->oclb_items++;
959
960         if (name[0] == '.')
961                 return 0;
962
963         fid_zero(fid);
964         sscanf(name + 1, SFID, RFID(fid));
965         if (!fid_is_sane(fid))
966                 return 0;
967
968         if (osd_remote_fid(oti->oti_env, dev, fid))
969                 return 0;
970
971         osd_id_gen(id, ino, OSD_OII_NOGEN);
972         inode = osd_iget(oti, dev, id);
973         if (IS_ERR(inode))
974                 return PTR_ERR(inode);
975
976         iput(inode);
977         osd_add_oi_cache(oti, dev, id, fid);
978         /* Check shard by scrub only if it has a problem with OI */
979         if (osd_oi_lookup(oti, dev, fid, &id2, 0) || !osd_id_eq(id, &id2))
980                 osd_scrub_oi_insert(dev, fid, id, true);
981         oclb->oclb_found = true;
982
983         return 1;
984 }
985
986 WRAP_FILLDIR_FN(do_, osd_stripe_dir_filldir)
987
988 /*
989  * When lookup item under striped directory, we need to locate the master
990  * MDT-object of the striped directory firstly, then the client will send
991  * lookup (getattr_by_name) RPC to the MDT with some slave MDT-object's FID
992  * and the item's name. If the system is restored from MDT file level backup,
993  * then before the OI scrub completely built the OI files, the OI mappings of
994  * the master MDT-object and slave MDT-object may be invalid. Usually, it is
995  * not a problem for the master MDT-object. Because when locate the master
996  * MDT-object, we will do name based lookup (for the striped directory itself)
997  * firstly, during such process we can setup the correct OI mapping for the
998  * master MDT-object. But it will be trouble for the slave MDT-object. Because
999  * the client will not trigger name based lookup on the MDT to locate the slave
1000  * MDT-object before locating item under the striped directory, then when
1001  * osd_fid_lookup(), it will find that the OI mapping for the slave MDT-object
1002  * is invalid and does not know what the right OI mapping is, then the MDT has
1003  * to return -EINPROGRESS to the client to notify that the OI scrub is rebuiding
1004  * the OI file, related OI mapping is unknown yet, please try again later. And
1005  * then client will re-try the RPC again and again until related OI mapping has
1006  * been updated. That is quite inefficient.
1007  *
1008  * To resolve above trouble, we will handle it as the following two cases:
1009  *
1010  * 1) The slave MDT-object and the master MDT-object are on different MDTs.
1011  *    It is relative easy. Be as one of remote MDT-objects, the slave MDT-object
1012  *    is linked under /REMOTE_PARENT_DIR with the name of its FID string.
1013  *    We can locate the slave MDT-object via lookup the /REMOTE_PARENT_DIR
1014  *    directly. Please check osd_fid_lookup().
1015  *
1016  * 2) The slave MDT-object and the master MDT-object reside on the same MDT.
1017  *    Under such case, during lookup the master MDT-object, we will lookup the
1018  *    slave MDT-object via readdir against the master MDT-object, because the
1019  *    slave MDT-objects information are stored as sub-directories with the name
1020  *    "${FID}:${index}". Then when find the local slave MDT-object, its OI
1021  *    mapping will be recorded. Then subsequent osd_fid_lookup() will know
1022  *    the correct OI mapping for the slave MDT-object.
1023  */
1024 static int osd_check_lmv(struct osd_thread_info *oti, struct osd_device *dev,
1025                          struct inode *inode)
1026 {
1027         struct lu_buf *buf = &oti->oti_big_buf;
1028         struct file *filp;
1029         struct lmv_mds_md_v1 *lmv1;
1030         struct osd_check_lmv_buf oclb = {
1031                 .ctx.actor = osd_stripe_dir_filldir,
1032                 .oclb_info = oti,
1033                 .oclb_dev = dev,
1034                 .oclb_found = false,
1035         };
1036         int rc = 0;
1037
1038         ENTRY;
1039         /* We should use the VFS layer to create a real dentry. */
1040         oti->oti_obj_dentry.d_inode = inode;
1041         oti->oti_obj_dentry.d_sb = inode->i_sb;
1042
1043         filp = alloc_file_pseudo(inode, dev->od_mnt, "/", O_NOATIME,
1044                                  inode->i_fop);
1045         if (IS_ERR(filp))
1046                 RETURN(-ENOMEM);
1047
1048         filp->f_mode |= FMODE_64BITHASH;
1049         filp->f_pos = 0;
1050         ihold(inode);
1051 again:
1052         rc = __osd_xattr_get(inode, filp->f_path.dentry, XATTR_NAME_LMV,
1053                              buf->lb_buf, buf->lb_len);
1054         if (rc == -ERANGE) {
1055                 rc = __osd_xattr_get(inode, filp->f_path.dentry,
1056                                      XATTR_NAME_LMV, NULL, 0);
1057                 if (rc > 0) {
1058                         lu_buf_realloc(buf, rc);
1059                         if (buf->lb_buf == NULL)
1060                                 GOTO(out, rc = -ENOMEM);
1061
1062                         goto again;
1063                 }
1064         }
1065
1066         if (unlikely(rc == 0 || rc == -ENODATA))
1067                 GOTO(out, rc = 0);
1068
1069         if (rc < 0)
1070                 GOTO(out, rc);
1071
1072         if (unlikely(buf->lb_buf == NULL)) {
1073                 lu_buf_realloc(buf, rc);
1074                 if (buf->lb_buf == NULL)
1075                         GOTO(out, rc = -ENOMEM);
1076
1077                 goto again;
1078         }
1079
1080         lmv1 = buf->lb_buf;
1081         if (le32_to_cpu(lmv1->lmv_magic) != LMV_MAGIC_V1)
1082                 GOTO(out, rc = 0);
1083
1084         do {
1085                 oclb.oclb_items = 0;
1086                 rc = iterate_dir(filp, &oclb.ctx);
1087         } while (rc >= 0 && oclb.oclb_items > 0 && !oclb.oclb_found &&
1088                  filp->f_pos != LDISKFS_HTREE_EOF_64BIT);
1089 out:
1090         fput(filp);
1091         if (rc < 0)
1092                 CDEBUG(D_LFSCK,
1093                        "%s: cannot check LMV, ino = %lu/%u: rc = %d\n",
1094                        osd_ino2name(inode), inode->i_ino, inode->i_generation,
1095                        rc);
1096         else
1097                 rc = 0;
1098
1099         RETURN(rc);
1100 }
1101
1102 /**
1103  * Is object in scrub inconsistent/stale list.
1104  *
1105  * \a scrub has two lists, os_inconsistent_items contains mappings to fix, while
1106  * os_stale_items contains mappings failed to fix.
1107  */
1108 static bool fid_in_scrub_list(struct lustre_scrub *scrub,
1109                               const struct list_head *list,
1110                               const struct lu_fid *fid)
1111 {
1112         struct osd_inconsistent_item *oii;
1113
1114         if (list_empty(list))
1115                 return false;
1116
1117         spin_lock(&scrub->os_lock);
1118         list_for_each_entry(oii, list, oii_list) {
1119                 if (lu_fid_eq(fid, &oii->oii_cache.oic_fid)) {
1120                         spin_unlock(&scrub->os_lock);
1121                         return true;
1122                 }
1123         }
1124         spin_unlock(&scrub->os_lock);
1125
1126         return false;
1127 }
1128
1129 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
1130                           const struct lu_fid *fid,
1131                           const struct lu_object_conf *conf)
1132 {
1133         struct osd_thread_info *info;
1134         struct lu_device *ldev = obj->oo_dt.do_lu.lo_dev;
1135         struct osd_device *dev;
1136         struct osd_idmap_cache *oic;
1137         struct osd_inode_id *id;
1138         struct inode *inode = NULL;
1139         struct lustre_scrub *scrub;
1140         struct scrub_file *sf;
1141         __u32 flags = SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT | SS_AUTO_FULL;
1142         __u32 saved_ino;
1143         __u32 saved_gen;
1144         int result = 0;
1145         int rc1 = 0;
1146         bool remote = false;
1147         bool trusted = true;
1148         bool updated = false;
1149         bool checked = false;
1150         bool stale = false;
1151
1152         ENTRY;
1153
1154         LINVRNT(osd_invariant(obj));
1155         LASSERT(obj->oo_inode == NULL);
1156
1157         if (fid_is_sane(fid) == 0) {
1158                 CERROR("%s: invalid FID "DFID"\n", ldev->ld_obd->obd_name,
1159                        PFID(fid));
1160                 dump_stack();
1161                 RETURN(-EINVAL);
1162         }
1163
1164         dev = osd_dev(ldev);
1165         scrub = &dev->od_scrub.os_scrub;
1166         sf = &scrub->os_file;
1167         info = osd_oti_get(env);
1168         LASSERT(info);
1169         oic = &info->oti_cache;
1170
1171         if (CFS_FAIL_CHECK(OBD_FAIL_SRV_ENOENT))
1172                 RETURN(-ENOENT);
1173
1174         /*
1175          * For the object is created as locking anchor, or for the object to
1176          * be created on disk. No need to osd_oi_lookup() at here because FID
1177          * shouldn't never be re-used, if it's really a duplicate FID from
1178          * unexpected reason, we should be able to detect it later by calling
1179          * do_create->osd_oi_insert().
1180          */
1181         if (conf && conf->loc_flags & LOC_F_NEW)
1182                 RETURN(0);
1183
1184         /* Search order: 1. per-thread cache. */
1185         if (lu_fid_eq(fid, &oic->oic_fid) && likely(oic->oic_dev == dev)) {
1186                 id = &oic->oic_lid;
1187                 goto iget;
1188         }
1189
1190         /* Search order: 2. OI scrub pending list. */
1191         id = &info->oti_id;
1192         memset(id, 0, sizeof(struct osd_inode_id));
1193         if (fid_in_scrub_list(scrub, &scrub->os_inconsistent_items, fid) &&
1194             scrub->os_running)
1195                 RETURN(-EINPROGRESS);
1196
1197         stale = fid_in_scrub_list(scrub, &scrub->os_stale_items, fid);
1198         if (stale && CFS_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_STALE))
1199                 RETURN(-ESTALE);
1200
1201         /*
1202          * The OI mapping in the OI file can be updated by the OI scrub
1203          * when we locate the inode via FID. So it may be not trustable.
1204          */
1205         trusted = false;
1206
1207         /* Search order: 3. OI files. */
1208         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1209         if (result == -ENOENT) {
1210                 if (!fid_is_norm(fid) ||
1211                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
1212                     !ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
1213                                       sf->sf_oi_bitmap))
1214                         GOTO(out, result = 0);
1215
1216                 goto trigger;
1217         }
1218
1219         /* -ESTALE is returned if inode of OST object doesn't exist */
1220         if (result == -ESTALE &&
1221             fid_is_on_ost(info, dev, fid, OI_CHECK_FLD)) {
1222                 GOTO(out, result = 0);
1223         }
1224
1225         if (result)
1226                 GOTO(out, result);
1227
1228 iget:
1229         obj->oo_inode = NULL;
1230         /* for later passes through checks, not true on first pass */
1231         if (!IS_ERR_OR_NULL(inode))
1232                 iput(inode);
1233
1234         inode = osd_iget_check(info, dev, fid, id, trusted);
1235         if (!IS_ERR(inode)) {
1236                 obj->oo_inode = inode;
1237                 result = 0;
1238                 if (remote)
1239                         goto trigger;
1240
1241                 goto check_lma;
1242         }
1243
1244         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_STALE))
1245                 goto trigger;
1246
1247         result = PTR_ERR(inode);
1248         if (result == -ENOENT || result == -ESTALE)
1249                 GOTO(out, result = 0);
1250
1251         if (result != -EREMCHG)
1252                 GOTO(out, result);
1253
1254 trigger:
1255         /* don't trigger repeatedly for stale mapping */
1256         if (stale)
1257                 GOTO(out, result = -ESTALE);
1258
1259         /*
1260          * We still have chance to get the valid inode: for the
1261          * object which is referenced by remote name entry, the
1262          * object on the local MDT will be linked under the dir
1263          * of "/REMOTE_PARENT_DIR" with its FID string as name.
1264          *
1265          * We do not know whether the object for the given FID
1266          * is referenced by some remote name entry or not, and
1267          * especially for DNE II, a multiple-linked object may
1268          * have many name entries reside on many MDTs.
1269          *
1270          * To simplify the operation, OSD will not distinguish
1271          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
1272          * only happened for the RPC from other MDT during the
1273          * OI scrub, or for the client side RPC with FID only,
1274          * such as FID to path, or from old connected client.
1275          */
1276         if (!remote) {
1277                 rc1 = osd_lookup_in_remote_parent(info, dev, fid, id);
1278                 if (!rc1) {
1279                         remote = true;
1280                         trusted = true;
1281                         flags |= SS_AUTO_PARTIAL;
1282                         flags &= ~SS_AUTO_FULL;
1283                         goto iget;
1284                 }
1285         }
1286
1287         if (scrub->os_running) {
1288                 if (scrub->os_partial_scan && !scrub->os_in_join)
1289                         goto join;
1290
1291                 if (IS_ERR_OR_NULL(inode) || result) {
1292                         osd_scrub_oi_insert(dev, fid, id, result == -ENOENT);
1293                         GOTO(out, result = -EINPROGRESS);
1294                 }
1295
1296                 LASSERT(remote);
1297                 LASSERT(obj->oo_inode == inode);
1298
1299                 osd_scrub_oi_insert(dev, fid, id, true);
1300                 goto found;
1301         }
1302
1303         if (dev->od_scrub.os_scrub.os_auto_scrub_interval == AS_NEVER) {
1304                 if (!remote)
1305                         GOTO(out, result = -EREMCHG);
1306
1307                 LASSERT(!result);
1308                 LASSERT(obj->oo_inode == inode);
1309
1310                 osd_add_oi_cache(info, dev, id, fid);
1311                 goto found;
1312         }
1313
1314 join:
1315         if (IS_ERR_OR_NULL(inode) || result)
1316                 osd_scrub_oi_insert(dev, fid, id, result == -ENOENT);
1317
1318         rc1 = osd_scrub_start(env, dev, flags);
1319         CDEBUG_LIMIT(D_LFSCK | D_CONSOLE | D_WARNING,
1320                      "%s: trigger OI scrub by RPC for "DFID"/%u with flags %#x: rc = %d\n",
1321                      osd_name(dev), PFID(fid), id->oii_ino, flags, rc1);
1322         if (rc1 && rc1 != -EALREADY)
1323                 GOTO(out, result = -EREMCHG);
1324
1325         if (IS_ERR_OR_NULL(inode) || result)
1326                 GOTO(out, result = -EINPROGRESS);
1327
1328         LASSERT(remote);
1329         LASSERT(obj->oo_inode == inode);
1330         goto found;
1331
1332 check_lma:
1333         checked = true;
1334         if (unlikely(obj->oo_header))
1335                 goto found;
1336
1337         result = osd_check_lma(env, obj);
1338         if (!result)
1339                 goto found;
1340
1341         LASSERTF(id->oii_ino == inode->i_ino &&
1342                  id->oii_gen == inode->i_generation,
1343                  "locate wrong inode for FID: "DFID", %u/%u => %ld/%u\n",
1344                  PFID(fid), id->oii_ino, id->oii_gen,
1345                  inode->i_ino, inode->i_generation);
1346
1347         saved_ino = inode->i_ino;
1348         saved_gen = inode->i_generation;
1349
1350         if (unlikely(result == -ENODATA)) {
1351                 /*
1352                  * If the OI scrub updated the OI mapping by race, it
1353                  * must be valid. Trust the inode that has no LMA EA.
1354                  */
1355                 if (updated)
1356                         goto found;
1357
1358                 result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1359                 if (!result) {
1360                         /*
1361                          * The OI mapping is still there, the inode is still
1362                          * valid. It is just becaues the inode has no LMA EA.
1363                          */
1364                         if (saved_ino == id->oii_ino &&
1365                             saved_gen == id->oii_gen)
1366                                 goto found;
1367
1368                         /*
1369                          * It is the OI scrub updated the OI mapping by race.
1370                          * The new OI mapping must be valid.
1371                          */
1372                         trusted = true;
1373                         updated = true;
1374                         goto iget;
1375                 }
1376
1377                 /*
1378                  * "result == -ENOENT" means that the OI mappinghas been
1379                  * removed by race, so the inode belongs to other object.
1380                  *
1381                  * Others error can be returned  directly.
1382                  */
1383                 if (result == -ENOENT) {
1384                         obj->oo_inode = NULL;
1385                         result = 0;
1386                 }
1387         }
1388
1389         if (result != -EREMCHG)
1390                 GOTO(out, result);
1391
1392         LASSERT(!updated);
1393
1394         /*
1395          * if two OST objects map to the same inode, and inode mode is
1396          * (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666), which means it's
1397          * reserved by precreate, and not written yet, in this case, don't
1398          * set inode for the object whose FID mismatch, so that it can create
1399          * inode and not block precreate.
1400          */
1401         if (fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) &&
1402             inode->i_mode == (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666)) {
1403                 obj->oo_inode = NULL;
1404                 GOTO(out, result = 0);
1405         }
1406
1407         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1408         /*
1409          * "result == -ENOENT" means the cached OI mapping has been removed
1410          * from the OI file by race, above inode belongs to other object.
1411          */
1412         if (result == -ENOENT) {
1413                 obj->oo_inode = NULL;
1414                 GOTO(out, result = 0);
1415         }
1416
1417         if (result)
1418                 GOTO(out, result);
1419
1420         if (saved_ino == id->oii_ino && saved_gen == id->oii_gen) {
1421                 result = -EREMCHG;
1422                 osd_scrub_refresh_mapping(info, dev, fid, id, DTO_INDEX_DELETE,
1423                                           true, 0, NULL);
1424                 goto trigger;
1425         }
1426
1427         /*
1428          * It is the OI scrub updated the OI mapping by race.
1429          * The new OI mapping must be valid.
1430          */
1431         trusted = true;
1432         updated = true;
1433         goto iget;
1434
1435 found:
1436         if (!checked) {
1437                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
1438                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
1439
1440                 result = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
1441                 if (!result) {
1442                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
1443                             dev->od_is_ost)
1444                                 obj->oo_pfid_in_lma = 1;
1445                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
1446                             !dev->od_is_ost)
1447                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
1448                 } else if (result != -ENODATA) {
1449                         GOTO(out, result);
1450                 }
1451         }
1452
1453         obj->oo_compat_dot_created = 1;
1454         obj->oo_compat_dotdot_created = 1;
1455
1456         if (S_ISDIR(inode->i_mode) &&
1457             (flags & SS_AUTO_PARTIAL || sf->sf_status == SS_SCANNING))
1458                 osd_check_lmv(info, dev, inode);
1459
1460         result = osd_attach_jinode(inode);
1461         if (result)
1462                 GOTO(out, result);
1463
1464         if (!ldiskfs_pdo)
1465                 GOTO(out, result = 0);
1466
1467         LASSERT(!obj->oo_hl_head);
1468         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1469
1470         GOTO(out, result = (!obj->oo_hl_head ? -ENOMEM : 0));
1471
1472 out:
1473         if (!result && stale)
1474                 osd_scrub_oi_resurrect(scrub, fid);
1475
1476         if (result || !obj->oo_inode) {
1477                 if (!IS_ERR_OR_NULL(inode))
1478                         iput(inode);
1479
1480                 obj->oo_inode = NULL;
1481                 if (trusted)
1482                         fid_zero(&oic->oic_fid);
1483         }
1484
1485         LINVRNT(osd_invariant(obj));
1486         return result;
1487 }
1488
1489 /*
1490  * Concurrency: shouldn't matter.
1491  */
1492 static void osd_object_init0(struct osd_object *obj)
1493 {
1494         LASSERT(obj->oo_inode != NULL);
1495         obj->oo_dt.do_body_ops = &osd_body_ops;
1496         obj->oo_dt.do_lu.lo_header->loh_attr |=
1497                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
1498 }
1499
1500 /*
1501  * Concurrency: no concurrent access is possible that early in object
1502  * life-cycle.
1503  */
1504 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
1505                            const struct lu_object_conf *conf)
1506 {
1507         struct osd_object *obj = osd_obj(l);
1508         int result;
1509
1510         LINVRNT(osd_invariant(obj));
1511
1512         if (CFS_FAIL_PRECHECK(OBD_FAIL_MDS_LLOG_UMOUNT_RACE) &&
1513             cfs_fail_val == 2) {
1514                 struct osd_thread_info *info = osd_oti_get(env);
1515                 struct osd_idmap_cache *oic = &info->oti_cache;
1516                 /* invalidate thread cache */
1517                 memset(&oic->oic_fid, 0, sizeof(oic->oic_fid));
1518         }
1519         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
1520                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
1521                 l->lo_header->loh_attr |= LOHA_EXISTS;
1522                 return 0;
1523         }
1524
1525         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
1526         obj->oo_dt.do_body_ops = &osd_body_ops_new;
1527         if (result == 0 && obj->oo_inode != NULL) {
1528                 struct osd_thread_info *oti = osd_oti_get(env);
1529                 struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
1530
1531                 osd_object_init0(obj);
1532                 if (unlikely(obj->oo_header))
1533                         return 0;
1534
1535                 result = osd_get_lma(oti, obj->oo_inode,
1536                                      &oti->oti_obj_dentry, loa);
1537                 if (!result) {
1538                         /*
1539                          * Convert LMAI flags to lustre LMA flags
1540                          * and cache it to oo_lma_flags
1541                          */
1542                         obj->oo_lma_flags =
1543                                 lma_to_lustre_flags(loa->loa_lma.lma_incompat);
1544                 } else if (result == -ENODATA) {
1545                         result = 0;
1546                 }
1547         }
1548         atomic_set(&obj->oo_dirent_count, LU_DIRENT_COUNT_UNSET);
1549
1550         LINVRNT(osd_invariant(obj));
1551         return result;
1552 }
1553
1554 /*
1555  * The first part of oxe_buf is xattr name, and is '\0' terminated.
1556  * The left part is for value, binary mode.
1557  */
1558 struct osd_xattr_entry {
1559         struct list_head        oxe_list;
1560         size_t                  oxe_len;
1561         size_t                  oxe_namelen;
1562         bool                    oxe_exist;
1563         struct rcu_head         oxe_rcu;
1564         char                    oxe_buf[0];
1565 };
1566
1567 static int osd_oxc_get(struct osd_object *obj, const char *name,
1568                        struct lu_buf *buf)
1569 {
1570         struct osd_xattr_entry *tmp;
1571         struct osd_xattr_entry *oxe = NULL;
1572         size_t namelen = strlen(name);
1573         int rc;
1574
1575         rcu_read_lock();
1576         list_for_each_entry_rcu(tmp, &obj->oo_xattr_list, oxe_list) {
1577                 if (namelen == tmp->oxe_namelen &&
1578                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1579                         oxe = tmp;
1580                         break;
1581                 }
1582         }
1583
1584         if (oxe == NULL)
1585                 GOTO(out, rc = -ENOENT);
1586
1587         if (!oxe->oxe_exist)
1588                 GOTO(out, rc = -ENODATA);
1589
1590         /* vallen */
1591         rc = oxe->oxe_len - sizeof(*oxe) - oxe->oxe_namelen - 1;
1592         LASSERT(rc > 0);
1593
1594         if (buf->lb_buf == NULL)
1595                 GOTO(out, rc);
1596
1597         if (buf->lb_len < rc)
1598                 GOTO(out, rc = -ERANGE);
1599
1600         memcpy(buf->lb_buf, &oxe->oxe_buf[namelen + 1], rc);
1601 out:
1602         rcu_read_unlock();
1603
1604         return rc;
1605 }
1606
1607 static void osd_oxc_free(struct rcu_head *head)
1608 {
1609         struct osd_xattr_entry *oxe;
1610
1611         oxe = container_of(head, struct osd_xattr_entry, oxe_rcu);
1612         OBD_FREE(oxe, oxe->oxe_len);
1613 }
1614
1615 static void osd_oxc_add(struct osd_object *obj, const char *name,
1616                         const char *buf, int buflen)
1617 {
1618         struct osd_xattr_entry *oxe;
1619         struct osd_xattr_entry *old = NULL;
1620         struct osd_xattr_entry *tmp;
1621         size_t namelen = strlen(name);
1622         size_t len = sizeof(*oxe) + namelen + 1 + buflen;
1623
1624         OBD_ALLOC(oxe, len);
1625         if (oxe == NULL)
1626                 return;
1627
1628         INIT_LIST_HEAD(&oxe->oxe_list);
1629         oxe->oxe_len = len;
1630         oxe->oxe_namelen = namelen;
1631         memcpy(oxe->oxe_buf, name, namelen);
1632         if (buflen > 0) {
1633                 LASSERT(buf != NULL);
1634                 memcpy(oxe->oxe_buf + namelen + 1, buf, buflen);
1635                 oxe->oxe_exist = true;
1636         } else {
1637                 oxe->oxe_exist = false;
1638         }
1639
1640         /* this should be rarely called, just remove old and add new */
1641         spin_lock(&obj->oo_guard);
1642         list_for_each_entry(tmp, &obj->oo_xattr_list, oxe_list) {
1643                 if (namelen == tmp->oxe_namelen &&
1644                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1645                         old = tmp;
1646                         break;
1647                 }
1648         }
1649         if (old != NULL) {
1650                 list_replace_rcu(&old->oxe_list, &oxe->oxe_list);
1651                 call_rcu(&old->oxe_rcu, osd_oxc_free);
1652         } else {
1653                 list_add_tail_rcu(&oxe->oxe_list, &obj->oo_xattr_list);
1654         }
1655         spin_unlock(&obj->oo_guard);
1656 }
1657
1658 static void osd_oxc_del(struct osd_object *obj, const char *name)
1659 {
1660         struct osd_xattr_entry *oxe;
1661         size_t namelen = strlen(name);
1662
1663         spin_lock(&obj->oo_guard);
1664         list_for_each_entry(oxe, &obj->oo_xattr_list, oxe_list) {
1665                 if (namelen == oxe->oxe_namelen &&
1666                     strncmp(name, oxe->oxe_buf, namelen) == 0) {
1667                         list_del_rcu(&oxe->oxe_list);
1668                         call_rcu(&oxe->oxe_rcu, osd_oxc_free);
1669                         break;
1670                 }
1671         }
1672         spin_unlock(&obj->oo_guard);
1673 }
1674
1675 static void osd_oxc_fini(struct osd_object *obj)
1676 {
1677         struct osd_xattr_entry *oxe, *next;
1678
1679         list_for_each_entry_safe(oxe, next, &obj->oo_xattr_list, oxe_list) {
1680                 list_del(&oxe->oxe_list);
1681                 OBD_FREE(oxe, oxe->oxe_len);
1682         }
1683 }
1684
1685 /*
1686  * Concurrency: no concurrent access is possible that late in object
1687  * life-cycle.
1688  */
1689 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
1690 {
1691         struct osd_object *obj = osd_obj(l);
1692         struct lu_object_header *h = obj->oo_header;
1693
1694         LINVRNT(osd_invariant(obj));
1695
1696         osd_oxc_fini(obj);
1697         dt_object_fini(&obj->oo_dt);
1698         if (obj->oo_hl_head != NULL)
1699                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1700         /* obj doesn't contain an lu_object_header, so we don't need call_rcu */
1701         OBD_FREE_PTR(obj);
1702         if (unlikely(h))
1703                 lu_object_header_free(h);
1704 }
1705
1706 /*
1707  * Concurrency: no concurrent access is possible that late in object
1708  * life-cycle.
1709  */
1710 static void osd_index_fini(struct osd_object *o)
1711 {
1712         struct iam_container *bag;
1713
1714         if (o->oo_dir != NULL) {
1715                 bag = &o->oo_dir->od_container;
1716                 if (o->oo_inode != NULL) {
1717                         if (bag->ic_object == o->oo_inode)
1718                                 iam_container_fini(bag);
1719                 }
1720                 OBD_FREE_PTR(o->oo_dir);
1721                 o->oo_dir = NULL;
1722         }
1723 }
1724
1725 enum {
1726         OSD_TXN_OI_DELETE_CREDITS    = 20,
1727         OSD_TXN_INODE_DELETE_CREDITS = 20
1728 };
1729
1730 /*
1731  * Journal
1732  */
1733
1734 #if OSD_THANDLE_STATS
1735 /**
1736  * Set time when the handle is allocated
1737  */
1738 static void osd_th_alloced(struct osd_thandle *oth)
1739 {
1740         oth->oth_alloced = ktime_get();
1741 }
1742
1743 /**
1744  * Set time when the handle started
1745  */
1746 static void osd_th_started(struct osd_thandle *oth)
1747 {
1748         oth->oth_started = ktime_get();
1749 }
1750
1751 /**
1752  * Check whether the we deal with this handle for too long.
1753  */
1754 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
1755                                 ktime_t alloced, ktime_t started,
1756                                 ktime_t closed)
1757 {
1758         ktime_t now = ktime_get();
1759
1760         LASSERT(dev != NULL);
1761
1762         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
1763                             ktime_us_delta(started, alloced));
1764         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
1765                             ktime_us_delta(closed, started));
1766         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
1767                             ktime_us_delta(now, closed));
1768
1769         if (ktime_before(ktime_add_ns(alloced, 30 * NSEC_PER_SEC), now)) {
1770                 CWARN("transaction handle %p was open for too long: now %lld, alloced %lld, started %lld, closed %lld\n",
1771                                 oth, now, alloced, started, closed);
1772                 dump_stack();
1773         }
1774 }
1775
1776 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
1777 {                                                                       \
1778         ktime_t __closed = ktime_get();                                 \
1779         ktime_t __alloced = oth->oth_alloced;                           \
1780         ktime_t __started = oth->oth_started;                           \
1781                                                                         \
1782         expr;                                                           \
1783         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
1784 }
1785
1786 #else /* OSD_THANDLE_STATS */
1787
1788 #define osd_th_alloced(h)                  do {} while(0)
1789 #define osd_th_started(h)                  do {} while(0)
1790 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
1791
1792 #endif /* OSD_THANDLE_STATS */
1793
1794 /*
1795  * in some cases (like overstriped files) the same operations on the same
1796  * objects are declared many times and this may lead to huge number of
1797  * credits which can be a problem and/or cause performance degradation.
1798  * this function is to remember what declarations have been made within
1799  * a given thandle and then skip duplications.
1800  * limit it's scope so that regular small transactions don't need all
1801  * this overhead with allocations, lists.
1802  * also, limit scope to the specific objects like llogs, etc.
1803  */
1804 static inline bool osd_check_special_fid(const struct lu_fid *f)
1805 {
1806         if (fid_seq_is_llog(f->f_seq))
1807                 return true;
1808         if (f->f_seq == FID_SEQ_LOCAL_FILE &&
1809             f->f_oid == MDD_LOV_OBJ_OID)
1810                 return true;
1811         return false;
1812 }
1813
1814 bool osd_tx_was_declared(const struct lu_env *env, struct osd_thandle *oth,
1815                          struct dt_object *dt, enum dt_txn_op op, loff_t pos)
1816 {
1817         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
1818         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
1819         struct osd_thread_info *oti = osd_oti_get(env);
1820         struct osd_obj_declare *old;
1821
1822         if (osd->od_is_ost)
1823                 return false;
1824
1825         /* small transactions don't need this overhead */
1826         if (oti->oti_declare_ops[DTO_OBJECT_CREATE] < 10 &&
1827             oti->oti_declare_ops[DTO_WRITE_BASE] < 10)
1828                 return false;
1829
1830         if (osd_check_special_fid(fid) == 0)
1831                 return false;
1832
1833         list_for_each_entry(old, &oth->ot_declare_list, old_list) {
1834                 if (old->old_op == op && old->old_pos == pos &&
1835                     lu_fid_eq(&old->old_fid, fid))
1836                         return true;
1837         }
1838         OBD_ALLOC_PTR(old);
1839         if (unlikely(old == NULL))
1840                 return false;
1841         old->old_fid = *lu_object_fid(&dt->do_lu);
1842         old->old_op = op;
1843         old->old_pos = pos;
1844         list_add(&old->old_list, &oth->ot_declare_list);
1845         return false;
1846 }
1847
1848 void osd_tx_declaration_free(struct osd_thandle *oth)
1849 {
1850         struct osd_obj_declare *old, *tmp;
1851
1852         list_for_each_entry_safe(old, tmp, &oth->ot_declare_list, old_list) {
1853                 list_del_init(&old->old_list);
1854                 OBD_FREE_PTR(old);
1855         }
1856 }
1857
1858 /*
1859  * Concurrency: doesn't access mutable data.
1860  */
1861 static int osd_param_is_not_sane(const struct osd_device *dev,
1862                                  const struct thandle *th)
1863 {
1864         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
1865
1866         return oh->ot_credits > osd_transaction_size(dev);
1867 }
1868
1869 /*
1870  * Concurrency: shouldn't matter.
1871  */
1872 static void osd_trans_commit_cb(struct super_block *sb,
1873                                 struct ldiskfs_journal_cb_entry *jcb, int error)
1874 {
1875         struct osd_thandle *oh = container_of(jcb, struct osd_thandle, ot_jcb);
1876         struct thandle *th = &oh->ot_super;
1877         struct lu_device *lud = &th->th_dev->dd_lu_dev;
1878         struct osd_device *osd = osd_dev(lud);
1879         struct dt_txn_commit_cb *dcb, *tmp;
1880
1881         LASSERT(oh->ot_handle == NULL);
1882
1883         if (error)
1884                 CERROR("transaction @0x%p commit error: %d\n", th, error);
1885
1886         /* call per-transaction callbacks if any */
1887         list_for_each_entry_safe(dcb, tmp, &oh->ot_commit_dcb_list,
1888                                  dcb_linkage) {
1889                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
1890                          "commit callback entry: magic=%x name='%s'\n",
1891                          dcb->dcb_magic, dcb->dcb_name);
1892                 list_del_init(&dcb->dcb_linkage);
1893                 dcb->dcb_func(NULL, th, dcb, error);
1894         }
1895
1896         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
1897         if (atomic_dec_and_test(&osd->od_commit_cb_in_flight))
1898                 wake_up(&osd->od_commit_cb_done);
1899         th->th_dev = NULL;
1900
1901         OBD_FREE_PTR(oh);
1902 }
1903
1904 static struct thandle *osd_trans_create(const struct lu_env *env,
1905                                         struct dt_device *d)
1906 {
1907         struct osd_thread_info *oti = osd_oti_get(env);
1908         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1909         struct osd_thandle *oh;
1910         struct thandle *th;
1911
1912         ENTRY;
1913
1914         if (d->dd_rdonly) {
1915                 CERROR("%s: someone try to start transaction under "
1916                        "readonly mode, should be disabled.\n",
1917                        osd_name(osd_dt_dev(d)));
1918                 dump_stack();
1919                 RETURN(ERR_PTR(-EROFS));
1920         }
1921
1922         /* on pending IO in this thread should left from prev. request */
1923         LASSERT(atomic_read(&iobuf->dr_numreqs) == 0);
1924
1925         sb_start_write(osd_sb(osd_dt_dev(d)));
1926
1927         OBD_ALLOC_GFP(oh, sizeof(*oh), GFP_NOFS);
1928         if (!oh) {
1929                 sb_end_write(osd_sb(osd_dt_dev(d)));
1930                 RETURN(ERR_PTR(-ENOMEM));
1931         }
1932
1933         oh->ot_quota_trans = &oti->oti_quota_trans;
1934         memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
1935         th = &oh->ot_super;
1936         th->th_dev = d;
1937         th->th_result = 0;
1938         oh->ot_credits = 0;
1939         oh->oh_declared_ext = 0;
1940         INIT_LIST_HEAD(&oh->ot_commit_dcb_list);
1941         INIT_LIST_HEAD(&oh->ot_stop_dcb_list);
1942         INIT_LIST_HEAD(&oh->ot_trunc_locks);
1943         INIT_LIST_HEAD(&oh->ot_declare_list);
1944         osd_th_alloced(oh);
1945
1946         memset(oti->oti_declare_ops, 0,
1947                sizeof(oti->oti_declare_ops));
1948         memset(oti->oti_declare_ops_cred, 0,
1949                sizeof(oti->oti_declare_ops_cred));
1950         memset(oti->oti_declare_ops_used, 0,
1951                sizeof(oti->oti_declare_ops_used));
1952
1953         oti->oti_ins_cache_depth++;
1954
1955         RETURN(th);
1956 }
1957
1958 void osd_trans_dump_creds(const struct lu_env *env, struct thandle *th)
1959 {
1960         struct osd_thread_info *oti = osd_oti_get(env);
1961         struct osd_thandle *oh;
1962
1963         oh = container_of(th, struct osd_thandle, ot_super);
1964         LASSERT(oh != NULL);
1965
1966         CWARN("  create: %u/%u/%u, destroy: %u/%u/%u\n",
1967               oti->oti_declare_ops[OSD_OT_CREATE],
1968               oti->oti_declare_ops_cred[OSD_OT_CREATE],
1969               oti->oti_declare_ops_used[OSD_OT_CREATE],
1970               oti->oti_declare_ops[OSD_OT_DESTROY],
1971               oti->oti_declare_ops_cred[OSD_OT_DESTROY],
1972               oti->oti_declare_ops_used[OSD_OT_DESTROY]);
1973         CWARN("  attr_set: %u/%u/%u, xattr_set: %u/%u/%u\n",
1974               oti->oti_declare_ops[OSD_OT_ATTR_SET],
1975               oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
1976               oti->oti_declare_ops_used[OSD_OT_ATTR_SET],
1977               oti->oti_declare_ops[OSD_OT_XATTR_SET],
1978               oti->oti_declare_ops_cred[OSD_OT_XATTR_SET],
1979               oti->oti_declare_ops_used[OSD_OT_XATTR_SET]);
1980         CWARN("  write: %u/%u/%u, punch: %u/%u/%u, quota %u/%u/%u\n",
1981               oti->oti_declare_ops[OSD_OT_WRITE],
1982               oti->oti_declare_ops_cred[OSD_OT_WRITE],
1983               oti->oti_declare_ops_used[OSD_OT_WRITE],
1984               oti->oti_declare_ops[OSD_OT_PUNCH],
1985               oti->oti_declare_ops_cred[OSD_OT_PUNCH],
1986               oti->oti_declare_ops_used[OSD_OT_PUNCH],
1987               oti->oti_declare_ops[OSD_OT_QUOTA],
1988               oti->oti_declare_ops_cred[OSD_OT_QUOTA],
1989               oti->oti_declare_ops_used[OSD_OT_QUOTA]);
1990         CWARN("  insert: %u/%u/%u, delete: %u/%u/%u\n",
1991               oti->oti_declare_ops[OSD_OT_INSERT],
1992               oti->oti_declare_ops_cred[OSD_OT_INSERT],
1993               oti->oti_declare_ops_used[OSD_OT_INSERT],
1994               oti->oti_declare_ops[OSD_OT_DELETE],
1995               oti->oti_declare_ops_cred[OSD_OT_DELETE],
1996               oti->oti_declare_ops_used[OSD_OT_DELETE]);
1997         CWARN("  ref_add: %u/%u/%u, ref_del: %u/%u/%u\n",
1998               oti->oti_declare_ops[OSD_OT_REF_ADD],
1999               oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
2000               oti->oti_declare_ops_used[OSD_OT_REF_ADD],
2001               oti->oti_declare_ops[OSD_OT_REF_DEL],
2002               oti->oti_declare_ops_cred[OSD_OT_REF_DEL],
2003               oti->oti_declare_ops_used[OSD_OT_REF_DEL]);
2004 }
2005
2006 #ifdef HAVE_LDISKFS_JOURNAL_ENSURE_CREDITS
2007 void osd_ldiskfs_credits_for_revoke(struct osd_device *osd,
2008                                     struct osd_thandle *oh,
2009                                     int *credits, int *revoke)
2010 {
2011         int blocks = LDISKFS_MAX_EXTENT_DEPTH * oh->oh_declared_ext;
2012         *revoke += ldiskfs_trans_default_revoke_credits(osd_sb(osd)) + blocks;
2013 }
2014 #else
2015 void osd_ldiskfs_credits_for_revoke(struct osd_device *osd,
2016                                     struct osd_thandle *oh,
2017                                     int *credits, int *revoke)
2018 {
2019         struct journal_s *journal = LDISKFS_SB(osd_sb(osd))->s_journal;
2020         int blocks, jbsize, records_per_block;
2021
2022         blocks = LDISKFS_MAX_EXTENT_DEPTH * oh->oh_declared_ext;
2023         jbsize = journal->j_blocksize;
2024         jbsize -= sizeof(struct jbd2_journal_block_tail) +
2025                   sizeof(jbd2_journal_revoke_header_t);
2026         records_per_block = jbsize / 8;
2027         *credits += (blocks + records_per_block - 1) / records_per_block;
2028 }
2029 #endif
2030
2031 /*
2032  * Concurrency: shouldn't matter.
2033  */
2034 static int osd_trans_start(const struct lu_env *env, struct dt_device *d,
2035                            struct thandle *th)
2036 {
2037         struct osd_thread_info *oti = osd_oti_get(env);
2038         struct osd_device *dev = osd_dt_dev(d);
2039         handle_t *jh;
2040         struct osd_thandle *oh;
2041         int rc, revoke = 0;
2042
2043         ENTRY;
2044
2045         LASSERT(current->journal_info == NULL);
2046
2047         oh = container_of(th, struct osd_thandle, ot_super);
2048         LASSERT(oh != NULL);
2049         LASSERT(oh->ot_handle == NULL);
2050         if (unlikely(ldiskfs_track_declares_assert != 0)) {
2051                 LASSERT(oti->oti_r_locks == 0);
2052                 LASSERT(oti->oti_w_locks == 0);
2053         }
2054
2055         rc = dt_txn_hook_start(env, d, th);
2056         if (rc != 0)
2057                 GOTO(out, rc);
2058
2059         if (unlikely(osd_param_is_not_sane(dev, th))) {
2060                 static unsigned long last_printed;
2061                 static int last_credits;
2062
2063                 lprocfs_counter_add(dev->od_stats,
2064                                     LPROC_OSD_TOO_MANY_CREDITS, 1);
2065
2066                 /*
2067                  * don't make noise on a tiny testing systems
2068                  * actual credits misuse will be caught anyway
2069                  */
2070                 if (last_credits != oh->ot_credits &&
2071                     time_after(jiffies, last_printed +
2072                                cfs_time_seconds(60)) &&
2073                     osd_transaction_size(dev) > 512) {
2074                         CWARN("%s: credits %u > trans_max %u\n", osd_name(dev),
2075                               oh->ot_credits, osd_transaction_size(dev));
2076                         osd_trans_dump_creds(env, th);
2077                         dump_stack();
2078                         last_credits = oh->ot_credits;
2079                         last_printed = jiffies;
2080                 }
2081                 /*
2082                  * XXX Limit the credits to 'max_transaction_buffers', and
2083                  *     let the underlying filesystem to catch the error if
2084                  *     we really need so many credits.
2085                  *
2086                  *     This should be removed when we can calculate the
2087                  *     credits precisely.
2088                  */
2089                 oh->ot_credits = osd_transaction_size(dev);
2090         } else if (ldiskfs_track_declares_assert != 0) {
2091                 /*
2092                  * reserve few credits to prevent an assertion in JBD
2093                  * our debugging mechanism will be able to detected
2094                  * overuse. this can help to debug single-update
2095                  * transactions
2096                  */
2097                 oh->ot_credits += 10;
2098                 if (unlikely(osd_param_is_not_sane(dev, th)))
2099                         oh->ot_credits = osd_transaction_size(dev);
2100         }
2101
2102         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_TXN_START))
2103                 GOTO(out, rc = -EIO);
2104
2105          /*
2106           * we ignore quota checks for system-owned files, but still
2107           * need to count blocks for uid/gid/projid
2108           */
2109         osd_trans_declare_op(env, oh, OSD_OT_QUOTA, 3);
2110
2111         /*
2112          * XXX temporary stuff. Some abstraction layer should
2113          * be used.
2114          */
2115         osd_ldiskfs_credits_for_revoke(dev, oh, &oh->ot_credits, &revoke);
2116         jh = osd_journal_start_with_revoke(osd_sb(dev), LDISKFS_HT_MISC,
2117                                            oh->ot_credits, revoke);
2118         osd_th_started(oh);
2119         if (!IS_ERR(jh)) {
2120                 oh->ot_handle = jh;
2121                 LASSERT(oti->oti_txns == 0);
2122
2123                 atomic_inc(&dev->od_commit_cb_in_flight);
2124                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
2125                               "osd-tx", th);
2126                 oti->oti_txns++;
2127                 rc = 0;
2128         } else {
2129                 rc = PTR_ERR(jh);
2130         }
2131 out:
2132         RETURN(rc);
2133 }
2134
2135 static int osd_seq_exists(const struct lu_env *env,
2136                           struct osd_device *osd, u64 seq)
2137 {
2138         struct lu_seq_range *range = &osd_oti_get(env)->oti_seq_range;
2139         struct seq_server_site *ss = osd_seq_site(osd);
2140         int rc;
2141
2142         ENTRY;
2143
2144         LASSERT(ss != NULL);
2145         LASSERT(ss->ss_server_fld != NULL);
2146
2147         rc = osd_fld_lookup(env, osd, seq, range);
2148         if (rc != 0) {
2149                 if (rc != -ENOENT)
2150                         CERROR("%s: can't lookup FLD sequence %#llx: rc = %d\n",
2151                                osd_name(osd), seq, rc);
2152                 RETURN(0);
2153         }
2154
2155         RETURN(ss->ss_node_id == range->lsr_index);
2156 }
2157
2158 static void osd_trans_stop_cb(struct osd_thandle *oth, int result)
2159 {
2160         struct dt_txn_commit_cb *dcb;
2161         struct dt_txn_commit_cb *tmp;
2162
2163         /* call per-transaction stop callbacks if any */
2164         list_for_each_entry_safe(dcb, tmp, &oth->ot_stop_dcb_list,
2165                                  dcb_linkage) {
2166                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
2167                          "commit callback entry: magic=%x name='%s'\n",
2168                          dcb->dcb_magic, dcb->dcb_name);
2169                 list_del_init(&dcb->dcb_linkage);
2170                 dcb->dcb_func(NULL, &oth->ot_super, dcb, result);
2171         }
2172 }
2173
2174 /*
2175  * Concurrency: shouldn't matter.
2176  */
2177 static int osd_trans_stop(const struct lu_env *env, struct dt_device *dt,
2178                           struct thandle *th)
2179 {
2180         struct osd_thread_info *oti = osd_oti_get(env);
2181         struct osd_thandle *oh;
2182         struct osd_iobuf *iobuf = &oti->oti_iobuf;
2183         struct osd_device *osd = osd_dt_dev(th->th_dev);
2184         struct qsd_instance *qsd = osd_def_qsd(osd);
2185         struct lquota_trans *qtrans;
2186         LIST_HEAD(truncates);
2187         int rc = 0, remove_agents = 0;
2188
2189         ENTRY;
2190
2191         oh = container_of(th, struct osd_thandle, ot_super);
2192
2193         remove_agents = oh->ot_remove_agents;
2194
2195         qtrans = oh->ot_quota_trans;
2196         oh->ot_quota_trans = NULL;
2197
2198         osd_tx_declaration_free(oh);
2199
2200         /* move locks to local list, stop tx, execute truncates */
2201         list_splice(&oh->ot_trunc_locks, &truncates);
2202
2203         if (oh->ot_handle != NULL) {
2204                 int rc2;
2205
2206                 handle_t *hdl = oh->ot_handle;
2207
2208                 /*
2209                  * add commit callback
2210                  * notice we don't do this in osd_trans_start()
2211                  * as underlying transaction can change during truncate
2212                  */
2213                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
2214                                              &oh->ot_jcb);
2215
2216                 LASSERT(oti->oti_txns == 1);
2217                 oti->oti_txns--;
2218
2219                 rc = dt_txn_hook_stop(env, th);
2220                 if (rc != 0)
2221                         CERROR("%s: failed in transaction hook: rc = %d\n",
2222                                osd_name(osd), rc);
2223
2224                 osd_trans_stop_cb(oh, rc);
2225                 /* hook functions might modify th_sync */
2226                 hdl->h_sync = th->th_sync;
2227
2228                 oh->ot_handle = NULL;
2229                 OSD_CHECK_SLOW_TH(oh, osd, rc2 = ldiskfs_journal_stop(hdl));
2230                 if (rc2 != 0)
2231                         CERROR("%s: failed to stop transaction: rc = %d\n",
2232                                osd_name(osd), rc2);
2233                 if (!rc)
2234                         rc = rc2;
2235
2236                 /* We preserve the origin behavior of ignoring any
2237                  * failures with the underlying punch / truncate
2238                  * operation. We do record for debugging if an error
2239                  * does occur in the lctl dk logs.
2240                  */
2241                 rc2 = osd_process_truncates(env, &truncates);
2242                 if (rc2 != 0)
2243                         CERROR("%s: failed truncate process: rc = %d\n",
2244                                osd_name(osd), rc2);
2245         } else {
2246                 osd_trans_stop_cb(oh, th->th_result);
2247                 OBD_FREE_PTR(oh);
2248         }
2249
2250         osd_trunc_unlock_all(env, &truncates);
2251
2252         /* inform the quota slave device that the transaction is stopping */
2253         qsd_op_end(env, qsd, qtrans);
2254
2255         /*
2256          * as we want IO to journal and data IO be concurrent, we don't block
2257          * awaiting data IO completion in osd_do_bio(), instead we wait here
2258          * once transaction is submitted to the journal. all reqular requests
2259          * don't do direct IO (except read/write), thus this wait_event becomes
2260          * no-op for them.
2261          *
2262          * IMPORTANT: we have to wait till any IO submited by the thread is
2263          * completed otherwise iobuf may be corrupted by different request
2264          */
2265         wait_event(iobuf->dr_wait,
2266                        atomic_read(&iobuf->dr_numreqs) == 0);
2267
2268         if (!rc)
2269                 rc = iobuf->dr_error;
2270
2271         osd_fini_iobuf(osd, iobuf);
2272
2273         if (unlikely(remove_agents != 0))
2274                 osd_process_scheduled_agent_removals(env, osd);
2275
2276         LASSERT(oti->oti_ins_cache_depth > 0);
2277         oti->oti_ins_cache_depth--;
2278         /* reset OI cache for safety */
2279         if (oti->oti_ins_cache_depth == 0)
2280                 oti->oti_ins_cache_used = 0;
2281
2282         sb_end_write(osd_sb(osd));
2283
2284         RETURN(rc);
2285 }
2286
2287 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
2288 {
2289         struct osd_thandle *oh = container_of(th, struct osd_thandle,
2290                                               ot_super);
2291
2292         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
2293         LASSERT(&dcb->dcb_func != NULL);
2294         if (dcb->dcb_flags & DCB_TRANS_STOP)
2295                 list_add(&dcb->dcb_linkage, &oh->ot_stop_dcb_list);
2296         else
2297                 list_add(&dcb->dcb_linkage, &oh->ot_commit_dcb_list);
2298
2299         return 0;
2300 }
2301
2302 struct osd_delayed_iput_work {
2303         struct work_struct diw_work;
2304         struct inode      *diw_inode;
2305 };
2306
2307 static void osd_delayed_iput_fn(struct work_struct *work)
2308 {
2309         struct osd_delayed_iput_work *diwork;
2310         struct inode *inode;
2311
2312         diwork = container_of(work, struct osd_delayed_iput_work, diw_work);
2313         inode = diwork->diw_inode;
2314         CDEBUG(D_INODE, "%s: delayed iput (ino=%lu)\n",
2315                inode->i_sb->s_id, inode->i_ino);
2316         iput(inode);
2317         OBD_FREE_PTR(diwork);
2318 }
2319
2320 noinline void osd_delayed_iput(struct inode *inode,
2321                                struct osd_delayed_iput_work *diwork)
2322 {
2323         if (!diwork) {
2324                 iput(inode);
2325         } else {
2326                 INIT_WORK(&diwork->diw_work, osd_delayed_iput_fn);
2327                 diwork->diw_inode = inode;
2328                 queue_work(LDISKFS_SB(inode->i_sb)->s_misc_wq,
2329                            &diwork->diw_work);
2330         }
2331 }
2332
2333 /*
2334  * Called just before object is freed. Releases all resources except for
2335  * object itself (that is released by osd_object_free()).
2336  *
2337  * Concurrency: no concurrent access is possible that late in object
2338  * life-cycle.
2339  */
2340 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
2341 {
2342         struct osd_object *obj = osd_obj(l);
2343         struct qsd_instance *qsd = osd_def_qsd(osd_obj2dev(obj));
2344         struct inode *inode = obj->oo_inode;
2345         struct osd_delayed_iput_work *diwork = NULL;
2346         __u64 projid;
2347         qid_t uid;
2348         qid_t gid;
2349
2350         LINVRNT(osd_invariant(obj));
2351
2352         /*
2353          * If object is unlinked remove fid->ino mapping from object index.
2354          */
2355
2356         osd_index_fini(obj);
2357
2358         if (!inode)
2359                 return;
2360
2361         if (inode->i_blocks > ldiskfs_delayed_unlink_blocks)
2362                 OBD_ALLOC(diwork, sizeof(*diwork));
2363
2364         if (osd_has_index(obj) &&  obj->oo_dt.do_index_ops == &osd_index_iam_ops)
2365                 ldiskfs_set_inode_flag(inode, LDISKFS_INODE_JOURNAL_DATA);
2366
2367         uid = i_uid_read(inode);
2368         gid = i_gid_read(inode);
2369         projid = i_projid_read(inode);
2370
2371         obj->oo_inode = NULL;
2372         osd_delayed_iput(inode, diwork);
2373
2374         /* do not rebalance quota if the caller needs to release memory
2375          * otherwise qsd_refresh_usage() may went into a new ldiskfs
2376          * transaction and risk to deadlock - LU-12178 */
2377         if (current->flags & (PF_MEMALLOC | PF_KSWAPD))
2378                 return;
2379
2380         if (!obj->oo_header && qsd) {
2381                 struct osd_thread_info *info = osd_oti_get(env);
2382                 struct lquota_id_info *qi = &info->oti_qi;
2383
2384                 /* Release granted quota to master if necessary */
2385                 qi->lqi_id.qid_uid = uid;
2386                 qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
2387
2388                 qi->lqi_id.qid_uid = gid;
2389                 qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
2390
2391                 qi->lqi_id.qid_uid = projid;
2392                 qsd_op_adjust(env, qsd, &qi->lqi_id, PRJQUOTA);
2393         }
2394 }
2395
2396 /*
2397  * Concurrency: ->loo_object_release() is called under site spin-lock.
2398  */
2399 static void osd_object_release(const struct lu_env *env,
2400                                struct lu_object *l)
2401 {
2402         struct osd_object *o = osd_obj(l);
2403
2404         /*
2405          * nobody should be releasing a non-destroyed object with nlink=0
2406          * the API allows this, but ldiskfs doesn't like and then report
2407          * this inode as deleted
2408          */
2409         LASSERT(!(o->oo_destroyed == 0 && o->oo_inode &&
2410                   o->oo_inode->i_nlink == 0));
2411 }
2412
2413 /*
2414  * Concurrency: shouldn't matter.
2415  */
2416 static int osd_object_print(const struct lu_env *env, void *cookie,
2417                             lu_printer_t p, const struct lu_object *l)
2418 {
2419         struct osd_object *o = osd_obj(l);
2420         struct iam_descr *d;
2421
2422         if (o->oo_dir != NULL)
2423                 d = o->oo_dir->od_container.ic_descr;
2424         else
2425                 d = NULL;
2426         return (*p)(env, cookie,
2427                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
2428                     o, o->oo_inode,
2429                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
2430                     o->oo_inode ? o->oo_inode->i_generation : 0,
2431                     d ? d->id_ops->id_name : "plain");
2432 }
2433
2434 /*
2435  * Concurrency: shouldn't matter.
2436  */
2437 int osd_statfs(const struct lu_env *env, struct dt_device *d,
2438                 struct obd_statfs *sfs, struct obd_statfs_info *info)
2439 {
2440         struct osd_device *osd = osd_dt_dev(d);
2441         struct super_block *sb = osd_sb(osd);
2442         struct kstatfs *ksfs;
2443         __u64 reserved;
2444         int result = 0;
2445
2446         if (unlikely(osd->od_mnt == NULL))
2447                 return -EINPROGRESS;
2448
2449         /* osd_lproc.c call this without env, allocate ksfs for that case */
2450         if (unlikely(env == NULL)) {
2451                 OBD_ALLOC_PTR(ksfs);
2452                 if (ksfs == NULL)
2453                         return -ENOMEM;
2454         } else {
2455                 ksfs = &osd_oti_get(env)->oti_ksfs;
2456         }
2457
2458         result = sb->s_op->statfs(sb->s_root, ksfs);
2459         if (result)
2460                 goto out;
2461
2462         statfs_pack(sfs, ksfs);
2463         if (unlikely(sb->s_flags & SB_RDONLY))
2464                 sfs->os_state |= OS_STATFS_READONLY;
2465
2466         sfs->os_state |= osd->od_nonrotational ? OS_STATFS_NONROT : 0;
2467
2468         if (ldiskfs_has_feature_extents(sb))
2469                 sfs->os_maxbytes = sb->s_maxbytes;
2470         else
2471                 sfs->os_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2472
2473         /*
2474          * Reserve some space so to avoid fragmenting the filesystem too much.
2475          * Fragmentation not only impacts performance, but can also increase
2476          * metadata overhead significantly, causing grant calculation to be
2477          * wrong.
2478          *
2479          * Reserve 0.78% of total space, at least 8MB for small filesystems.
2480          */
2481         BUILD_BUG_ON(OSD_STATFS_RESERVED <= LDISKFS_MAX_BLOCK_SIZE);
2482         reserved = OSD_STATFS_RESERVED >> sb->s_blocksize_bits;
2483         if (likely(sfs->os_blocks >= reserved << OSD_STATFS_RESERVED_SHIFT))
2484                 reserved = sfs->os_blocks >> OSD_STATFS_RESERVED_SHIFT;
2485
2486         sfs->os_blocks -= reserved;
2487         sfs->os_bfree  -= min(reserved, sfs->os_bfree);
2488         sfs->os_bavail -= min(reserved, sfs->os_bavail);
2489
2490 out:
2491         if (unlikely(env == NULL))
2492                 OBD_FREE_PTR(ksfs);
2493         return result;
2494 }
2495
2496 /**
2497  * Estimate space needed for file creations. We assume the largest filename
2498  * which is 2^64 - 1, hence a filename of 20 chars.
2499  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
2500  */
2501 #ifdef __LDISKFS_DIR_REC_LEN
2502 # define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
2503 #elif defined  LDISKFS_DIR_REC_LEN_WITH_DIR
2504 # define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20, NULL)
2505 #else
2506 # define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
2507 #endif
2508
2509 /*
2510  * Concurrency: doesn't access mutable data.
2511  */
2512 static void osd_conf_get(const struct lu_env *env,
2513                          const struct dt_device *dev,
2514                          struct dt_device_param *param)
2515 {
2516         struct osd_device *d = osd_dt_dev(dev);
2517         struct super_block *sb = osd_sb(d);
2518         struct blk_integrity *bi = bdev_get_integrity(sb->s_bdev);
2519         const char *name;
2520         int ea_overhead;
2521
2522         /*
2523          * XXX should be taken from not-yet-existing fs abstraction layer.
2524          */
2525         param->ddp_max_name_len = LDISKFS_NAME_LEN;
2526         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
2527         param->ddp_symlink_max  = sb->s_blocksize;
2528         param->ddp_mount_type   = LDD_MT_LDISKFS;
2529         if (ldiskfs_has_feature_extents(sb))
2530                 param->ddp_maxbytes = sb->s_maxbytes;
2531         else
2532                 param->ddp_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2533         /*
2534          * inode are statically allocated, so per-inode space consumption
2535          * is the space consumed by the directory entry
2536          */
2537         param->ddp_inodespace     = PER_OBJ_USAGE;
2538         /*
2539          * EXT_INIT_MAX_LEN is the theoretical maximum extent size (32k blocks
2540          * is 128MB) which is unlikely to be hit in real life. Report a smaller
2541          * maximum length to not under-count the actual number of extents
2542          * needed for writing a file if there are sub-optimal block allocations.
2543          */
2544         param->ddp_max_extent_blks = EXT_INIT_MAX_LEN >> 1;
2545         /* worst-case extent insertion metadata overhead */
2546         param->ddp_extent_tax = 6 * LDISKFS_BLOCK_SIZE(sb);
2547         param->ddp_mntopts = 0;
2548         if (test_opt(sb, XATTR_USER))
2549                 param->ddp_mntopts |= MNTOPT_USERXATTR;
2550         if (test_opt(sb, POSIX_ACL))
2551                 param->ddp_mntopts |= MNTOPT_ACL;
2552
2553         /*
2554          * LOD might calculate the max stripe count based on max_ea_size,
2555          * so we need take account in the overhead as well,
2556          * xattr_header + magic + xattr_entry_head
2557          */
2558         ea_overhead = sizeof(struct ldiskfs_xattr_header) + sizeof(__u32) +
2559                       LDISKFS_XATTR_LEN(XATTR_NAME_MAX_LEN);
2560
2561 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
2562         if (ldiskfs_has_feature_ea_inode(sb))
2563                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE -
2564                                                                 ea_overhead;
2565         else
2566 #endif
2567                 param->ddp_max_ea_size = sb->s_blocksize - ea_overhead;
2568
2569         if (param->ddp_max_ea_size > OBD_MAX_EA_SIZE)
2570                 param->ddp_max_ea_size = OBD_MAX_EA_SIZE;
2571
2572         /*
2573          * Preferred RPC size for efficient disk IO.  4MB shows good
2574          * all-around performance for ldiskfs, but use bigalloc chunk size
2575          * by default if larger.
2576          */
2577 #if defined(LDISKFS_CLUSTER_SIZE)
2578         if (LDISKFS_CLUSTER_SIZE(sb) > DT_DEF_BRW_SIZE)
2579                 param->ddp_brw_size = LDISKFS_CLUSTER_SIZE(sb);
2580         else
2581 #endif
2582                 param->ddp_brw_size = DT_DEF_BRW_SIZE;
2583
2584         param->ddp_t10_cksum_type = 0;
2585         if (bi) {
2586                 unsigned short interval = blk_integrity_interval(bi);
2587                 name = blk_integrity_name(bi);
2588                 /*
2589                  * Expected values:
2590                  * T10-DIF-TYPE1-CRC
2591                  * T10-DIF-TYPE2-CRC
2592                  * T10-DIF-TYPE3-CRC
2593                  * T10-DIF-TYPE1-IP
2594                  * T10-DIF-TYPE2-IP
2595                  * T10-DIF-TYPE3-IP
2596                  */
2597                 if (strncmp(name, "T10-DIF-TYPE",
2598                             sizeof("T10-DIF-TYPE") - 1) == 0) {
2599                         /* also skip "1/2/3-" at end */
2600                         const int type_off = sizeof("T10-DIF-TYPE.");
2601                         char type_number = name[type_off - 2];
2602
2603                         if (interval != 512 && interval != 4096) {
2604                                 CERROR("%s: unsupported T10PI sector size %u\n",
2605                                        d->od_svname, interval);
2606                                 goto out;
2607                         }
2608                         switch (type_number) {
2609                         case '1':
2610                                 d->od_t10_type = OSD_T10_TYPE1;
2611                                 break;
2612                         case '2':
2613                                 d->od_t10_type = OSD_T10_TYPE2;
2614                                 break;
2615                         case '3':
2616                                 d->od_t10_type = OSD_T10_TYPE3;
2617                                 break;
2618                         default:
2619                                 CERROR("%s: unsupported T10PI type %s\n",
2620                                        d->od_svname, name);
2621                                 goto out;
2622                         }
2623                         if (strcmp(name + type_off, "CRC") == 0) {
2624                                 d->od_t10_type |= OSD_T10_TYPE_CRC;
2625                                 param->ddp_t10_cksum_type = interval == 512 ?
2626                                         OBD_CKSUM_T10CRC512 :
2627                                         OBD_CKSUM_T10CRC4K;
2628                         } else if (strcmp(name + type_off, "IP") == 0) {
2629                                 d->od_t10_type |= OSD_T10_TYPE_IP;
2630                                 param->ddp_t10_cksum_type = interval == 512 ?
2631                                         OBD_CKSUM_T10IP512 :
2632                                         OBD_CKSUM_T10IP4K;
2633                         } else {
2634                                 CERROR("%s: unsupported checksum type of T10PI type '%s'\n",
2635                                        d->od_svname, name);
2636                                 d->od_t10_type = 0;
2637                         }
2638
2639                 } else {
2640                         CERROR("%s: unsupported T10PI type '%s'\n",
2641                                d->od_svname, name);
2642                 }
2643         }
2644
2645 out:
2646         param->ddp_has_lseek_data_hole = true;
2647 }
2648
2649 static struct vfsmount *osd_mnt_get(const struct dt_device *d)
2650 {
2651         return osd_dt_dev(d)->od_mnt;
2652 }
2653
2654 /*
2655  * Concurrency: shouldn't matter.
2656  */
2657 static int osd_sync(const struct lu_env *env, struct dt_device *d)
2658 {
2659         int rc;
2660         struct super_block *s = osd_sb(osd_dt_dev(d));
2661         ENTRY;
2662
2663         down_read(&s->s_umount);
2664         rc = s->s_op->sync_fs(s, 1);
2665         up_read(&s->s_umount);
2666
2667         CDEBUG(D_CACHE, "%s: synced OSD: rc = %d\n", osd_dt_dev(d)->od_svname,
2668                rc);
2669
2670         return rc;
2671 }
2672
2673 /**
2674  * Start commit for OSD device.
2675  *
2676  * An implementation of dt_commit_async method for OSD device.
2677  * Asychronously starts underlayng fs sync and thereby a transaction
2678  * commit.
2679  *
2680  * \param env environment
2681  * \param d dt device
2682  *
2683  * \see dt_device_operations
2684  */
2685 static int osd_commit_async(const struct lu_env *env,
2686                             struct dt_device *d)
2687 {
2688         struct super_block *s = osd_sb(osd_dt_dev(d));
2689         int rc;
2690
2691         ENTRY;
2692
2693         CDEBUG(D_HA, "%s: async commit OSD\n", osd_dt_dev(d)->od_svname);
2694         down_read(&s->s_umount);
2695         rc = s->s_op->sync_fs(s, 0);
2696         up_read(&s->s_umount);
2697
2698         RETURN(rc);
2699 }
2700
2701 /*
2702  * Concurrency: shouldn't matter.
2703  */
2704 static int osd_ro(const struct lu_env *env, struct dt_device *d)
2705 {
2706         struct super_block *sb = osd_sb(osd_dt_dev(d));
2707         struct block_device *dev = sb->s_bdev;
2708         int rc = -EOPNOTSUPP;
2709
2710         ENTRY;
2711
2712         CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
2713                osd_dt_dev(d)->od_svname, (long)dev, rc);
2714
2715         RETURN(rc);
2716 }
2717
2718 /**
2719  * Note: we do not count into QUOTA here.
2720  * If we mount with --data_journal we may need more.
2721  */
2722 const int osd_dto_credits_noquota[DTO_NR] = {
2723         /**
2724          * Insert.
2725          * INDEX_EXTRA_TRANS_BLOCKS(8) +
2726          * SINGLEDATA_TRANS_BLOCKS(8)
2727          * XXX Note: maybe iam need more, since iam have more level than
2728          *           EXT3 htree.
2729          */
2730         [DTO_INDEX_INSERT]  = 16,
2731         /**
2732          * Delete
2733          * just modify a single entry, probably merge few within a block
2734          */
2735         [DTO_INDEX_DELETE]  = 1,
2736         /**
2737          * Used for OI scrub
2738          */
2739         [DTO_INDEX_UPDATE]  = 16,
2740         /**
2741          * 4(inode, inode bits, groups, GDT)
2742          *   notice: OI updates are counted separately with DTO_INDEX_INSERT
2743          */
2744         [DTO_OBJECT_CREATE] = 4,
2745         /**
2746          * 4(inode, inode bits, groups, GDT)
2747          *   notice: OI updates are counted separately with DTO_INDEX_DELETE
2748          */
2749         [DTO_OBJECT_DELETE] = 4,
2750         /**
2751          * Attr set credits (inode)
2752          */
2753         [DTO_ATTR_SET_BASE] = 1,
2754         /**
2755          * Xattr set. The same as xattr of EXT3.
2756          * DATA_TRANS_BLOCKS(14)
2757          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
2758          * are also counted in. Do not know why?
2759          */
2760         [DTO_XATTR_SET]     = 14,
2761         /**
2762          * credits for inode change during write.
2763          */
2764         [DTO_WRITE_BASE]    = 3,
2765         /**
2766          * credits for single block write.
2767          */
2768         [DTO_WRITE_BLOCK]   = 14,
2769         /**
2770          * Attr set credits for chown.
2771          * This is extra credits for setattr, and it is null without quota
2772          */
2773         [DTO_ATTR_SET_CHOWN] = 0
2774 };
2775
2776 /* reserve or free quota for some operation */
2777 static int osd_reserve_or_free_quota(const struct lu_env *env,
2778                                      struct dt_device *dev,
2779                                      struct lquota_id_info *qi)
2780 {
2781         struct osd_device       *osd = osd_dt_dev(dev);
2782         struct qsd_instance     *qsd = NULL;
2783         int rc;
2784
2785         ENTRY;
2786
2787         if (qi->lqi_is_blk)
2788                 qsd = osd->od_quota_slave_dt;
2789         else
2790                 qsd = osd->od_quota_slave_md;
2791
2792         rc = qsd_reserve_or_free_quota(env, qsd, qi);
2793         RETURN(rc);
2794 }
2795
2796 static const struct dt_device_operations osd_dt_ops = {
2797         .dt_root_get              = osd_root_get,
2798         .dt_statfs                = osd_statfs,
2799         .dt_trans_create          = osd_trans_create,
2800         .dt_trans_start           = osd_trans_start,
2801         .dt_trans_stop            = osd_trans_stop,
2802         .dt_trans_cb_add          = osd_trans_cb_add,
2803         .dt_conf_get              = osd_conf_get,
2804         .dt_mnt_get               = osd_mnt_get,
2805         .dt_sync                  = osd_sync,
2806         .dt_ro                    = osd_ro,
2807         .dt_commit_async          = osd_commit_async,
2808         .dt_reserve_or_free_quota = osd_reserve_or_free_quota,
2809 };
2810
2811 static void osd_read_lock(const struct lu_env *env, struct dt_object *dt,
2812                           unsigned int role)
2813 {
2814         struct osd_object *obj = osd_dt_obj(dt);
2815         struct osd_thread_info *oti = osd_oti_get(env);
2816
2817         LINVRNT(osd_invariant(obj));
2818
2819         LASSERT(obj->oo_owner != env);
2820         down_read_nested(&obj->oo_sem, role);
2821
2822         LASSERT(obj->oo_owner == NULL);
2823         oti->oti_r_locks++;
2824 }
2825
2826 static void osd_write_lock(const struct lu_env *env, struct dt_object *dt,
2827                            unsigned int role)
2828 {
2829         struct osd_object *obj = osd_dt_obj(dt);
2830         struct osd_thread_info *oti = osd_oti_get(env);
2831
2832         LINVRNT(osd_invariant(obj));
2833
2834         LASSERT(obj->oo_owner != env);
2835         down_write_nested(&obj->oo_sem, role);
2836
2837         LASSERT(obj->oo_owner == NULL);
2838         obj->oo_owner = env;
2839         oti->oti_w_locks++;
2840 }
2841
2842 static void osd_read_unlock(const struct lu_env *env, struct dt_object *dt)
2843 {
2844         struct osd_object *obj = osd_dt_obj(dt);
2845         struct osd_thread_info *oti = osd_oti_get(env);
2846
2847         LINVRNT(osd_invariant(obj));
2848
2849         LASSERT(oti->oti_r_locks > 0);
2850         oti->oti_r_locks--;
2851         up_read(&obj->oo_sem);
2852 }
2853
2854 static void osd_write_unlock(const struct lu_env *env, struct dt_object *dt)
2855 {
2856         struct osd_object *obj = osd_dt_obj(dt);
2857         struct osd_thread_info *oti = osd_oti_get(env);
2858
2859         LINVRNT(osd_invariant(obj));
2860
2861         LASSERT(obj->oo_owner == env);
2862         LASSERT(oti->oti_w_locks > 0);
2863         oti->oti_w_locks--;
2864         obj->oo_owner = NULL;
2865         up_write(&obj->oo_sem);
2866 }
2867
2868 static int osd_write_locked(const struct lu_env *env, struct dt_object *dt)
2869 {
2870         struct osd_object *obj = osd_dt_obj(dt);
2871
2872         LINVRNT(osd_invariant(obj));
2873
2874         return obj->oo_owner == env;
2875 }
2876
2877 static void osd_inode_getattr(const struct lu_env *env,
2878                               struct inode *inode, struct lu_attr *attr)
2879 {
2880         attr->la_valid  |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
2881                            LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
2882                            LA_PROJID | LA_FLAGS | LA_NLINK | LA_RDEV |
2883                            LA_BLKSIZE | LA_TYPE | LA_BTIME;
2884
2885         attr->la_atime = inode->i_atime.tv_sec;
2886         attr->la_mtime = inode->i_mtime.tv_sec;
2887         attr->la_ctime = inode->i_ctime.tv_sec;
2888         attr->la_btime = LDISKFS_I(inode)->i_crtime.tv_sec;
2889         attr->la_mode    = inode->i_mode;
2890         attr->la_size    = i_size_read(inode);
2891         attr->la_blocks  = inode->i_blocks;
2892         attr->la_uid     = i_uid_read(inode);
2893         attr->la_gid     = i_gid_read(inode);
2894         attr->la_projid  = i_projid_read(inode);
2895         attr->la_flags   = ll_inode_to_ext_flags(inode->i_flags);
2896         attr->la_nlink   = inode->i_nlink;
2897         attr->la_rdev    = inode->i_rdev;
2898         attr->la_blksize = 1 << inode->i_blkbits;
2899         attr->la_blkbits = inode->i_blkbits;
2900         /*
2901          * Ext4 did not transfer inherit flags from raw inode
2902          * to inode flags, and ext4 internally test raw inode
2903          * @i_flags directly. Instead of patching ext4, we do it here.
2904          */
2905         if (LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL)
2906                 attr->la_flags |= LUSTRE_PROJINHERIT_FL;
2907 }
2908
2909 static int osd_dirent_count(const struct lu_env *env, struct dt_object *dt,
2910                             u64 *count)
2911 {
2912         struct osd_object *obj = osd_dt_obj(dt);
2913         const struct dt_it_ops *iops;
2914         struct dt_it *it;
2915         int rc;
2916
2917         ENTRY;
2918
2919         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
2920         LASSERT(fid_is_namespace_visible(lu_object_fid(&obj->oo_dt.do_lu)));
2921
2922         /* directory not initialized yet */
2923         if (!dt->do_index_ops) {
2924                 *count = 0;
2925                 RETURN(0);
2926         }
2927
2928         spin_lock(&obj->oo_guard);
2929         *count = atomic_read(&obj->oo_dirent_count);
2930         if (*count == LU_DIRENT_COUNT_UNSET)
2931                 atomic_set(&obj->oo_dirent_count, 0);
2932         spin_unlock(&obj->oo_guard);
2933         if (*count != LU_DIRENT_COUNT_UNSET)
2934                 RETURN(0);
2935
2936         *count = 0;
2937         iops = &dt->do_index_ops->dio_it;
2938         it = iops->init(env, dt, LUDA_64BITHASH);
2939         if (IS_ERR(it))
2940                 GOTO(out, rc = PTR_ERR(it));
2941
2942         rc = iops->load(env, it, 0);
2943         if (rc < 0) {
2944                 if (rc == -ENODATA)
2945                         rc = 0;
2946                 GOTO(put, rc);
2947         }
2948         if (rc > 0)
2949                 rc = iops->next(env, it);
2950
2951         for (; rc == 0 || rc == -ESTALE; rc = iops->next(env, it)) {
2952                 if (rc == -ESTALE)
2953                         continue;
2954
2955                 if (iops->key_size(env, it) == 0)
2956                         continue;
2957
2958                 (*count)++;
2959         }
2960         if (rc == 1 || rc == -ESTALE)
2961                 rc = 0;
2962 put:
2963         iops->put(env, it);
2964         iops->fini(env, it);
2965 out:
2966         /* If counting dirents failed, use the current count (if any).
2967          *
2968          * At worst this means the directory will not be split until the
2969          * count can be completed successfully (remount or oo_dirent_count
2970          * incremented by adding new entries).  This avoids re-walking
2971          * the whole directory on each access and hitting the same error.
2972          */
2973         if (rc && *count == 0)
2974                 *count = LU_DIRENT_COUNT_UNSET;
2975         atomic_set(&obj->oo_dirent_count, *count);
2976         RETURN(rc);
2977 }
2978
2979 static int osd_attr_get(const struct lu_env *env, struct dt_object *dt,
2980                         struct lu_attr *attr)
2981 {
2982         struct osd_object *obj = osd_dt_obj(dt);
2983         int rc = 0;
2984
2985         if (unlikely(!dt_object_exists(dt)))
2986                 return -ENOENT;
2987         if (unlikely(obj->oo_destroyed))
2988                 return -ENOENT;
2989
2990         LASSERT(!dt_object_remote(dt));
2991         LINVRNT(osd_invariant(obj));
2992
2993         spin_lock(&obj->oo_guard);
2994         osd_inode_getattr(env, obj->oo_inode, attr);
2995         if (obj->oo_lma_flags & LUSTRE_ORPHAN_FL) {
2996                 attr->la_valid |= LA_FLAGS;
2997                 attr->la_flags |= LUSTRE_ORPHAN_FL;
2998         }
2999         if (obj->oo_lma_flags & LUSTRE_ENCRYPT_FL) {
3000                 attr->la_valid |= LA_FLAGS;
3001                 attr->la_flags |= LUSTRE_ENCRYPT_FL;
3002         }
3003         spin_unlock(&obj->oo_guard);
3004
3005         if (S_ISDIR(obj->oo_inode->i_mode) &&
3006             (attr->la_valid & LA_DIRENT_CNT) &&
3007             fid_is_namespace_visible(lu_object_fid(&dt->do_lu)))
3008                 rc = osd_dirent_count(env, dt, &attr->la_dirent_count);
3009         else
3010                 attr->la_valid &= ~LA_DIRENT_CNT;
3011
3012         return rc;
3013 }
3014
3015 static int osd_declare_attr_qid(const struct lu_env *env,
3016                                 struct osd_object *obj,
3017                                 struct osd_thandle *oh, long long bspace,
3018                                 qid_t old_id, qid_t new_id, bool enforce,
3019                                 unsigned int type)
3020 {
3021         int rc;
3022         struct osd_thread_info *info = osd_oti_get(env);
3023         struct lquota_id_info  *qi = &info->oti_qi;
3024
3025         qi->lqi_type = type;
3026         /* inode accounting */
3027         qi->lqi_is_blk = false;
3028
3029         /* one more inode for the new id ... */
3030         qi->lqi_id.qid_uid = new_id;
3031         qi->lqi_space      = 1;
3032         /* Reserve credits for the new id */
3033         rc = osd_declare_qid(env, oh, qi, NULL, enforce, NULL);
3034         if (rc == -EDQUOT || rc == -EINPROGRESS)
3035                 rc = 0;
3036         if (rc)
3037                 RETURN(rc);
3038
3039         /* and one less inode for the current id */
3040         qi->lqi_id.qid_uid = old_id;
3041         qi->lqi_space = -1;
3042         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
3043         if (rc == -EDQUOT || rc == -EINPROGRESS)
3044                 rc = 0;
3045         if (rc)
3046                 RETURN(rc);
3047
3048         /* block accounting */
3049         qi->lqi_is_blk = true;
3050
3051         /* more blocks for the new id ... */
3052         qi->lqi_id.qid_uid = new_id;
3053         qi->lqi_space      = bspace;
3054         /*
3055          * Credits for the new uid has been reserved, re-use "obj"
3056          * to save credit reservation.
3057          */
3058         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
3059         if (rc == -EDQUOT || rc == -EINPROGRESS)
3060                 rc = 0;
3061         if (rc)
3062                 RETURN(rc);
3063
3064         /* and finally less blocks for the current uid */
3065         qi->lqi_id.qid_uid = old_id;
3066         qi->lqi_space      = -bspace;
3067         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
3068         if (rc == -EDQUOT || rc == -EINPROGRESS)
3069                 rc = 0;
3070
3071         RETURN(rc);
3072 }
3073
3074 static int osd_declare_attr_set(const struct lu_env *env,
3075                                 struct dt_object *dt,
3076                                 const struct lu_attr *attr,
3077                                 struct thandle *handle)
3078 {
3079         struct osd_thandle *oh;
3080         struct osd_object *obj;
3081         qid_t uid;
3082         qid_t gid;
3083         long long bspace;
3084         int rc = 0;
3085         bool enforce;
3086
3087         ENTRY;
3088
3089         LASSERT(dt != NULL);
3090         LASSERT(handle != NULL);
3091
3092         obj = osd_dt_obj(dt);
3093         LASSERT(osd_invariant(obj));
3094
3095         oh = container_of(handle, struct osd_thandle, ot_super);
3096         LASSERT(oh->ot_handle == NULL);
3097
3098         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
3099                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
3100
3101         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
3102                              osd_dto_credits_noquota[DTO_XATTR_SET]);
3103
3104         if (attr == NULL || obj->oo_inode == NULL)
3105                 RETURN(rc);
3106
3107         bspace   = obj->oo_inode->i_blocks << 9;
3108         bspace   = toqb(bspace);
3109
3110         /*
3111          * Changing ownership is always preformed by super user, it should not
3112          * fail with EDQUOT unless required explicitly.
3113          *
3114          * We still need to call the osd_declare_qid() to calculate the journal
3115          * credits for updating quota accounting files and to trigger quota
3116          * space adjustment once the operation is completed.
3117          */
3118         if (attr->la_valid & LA_UID || attr->la_valid & LA_GID) {
3119                 /* USERQUOTA */
3120                 uid = i_uid_read(obj->oo_inode);
3121                 enforce = (attr->la_valid & LA_UID) && (attr->la_uid != uid);
3122                 rc = osd_declare_attr_qid(env, obj, oh, bspace, uid,
3123                                           attr->la_uid, enforce, USRQUOTA);
3124                 if (rc)
3125                         RETURN(rc);
3126
3127                 gid = i_gid_read(obj->oo_inode);
3128                 CDEBUG(D_QUOTA, "declare uid %d -> %d gid %d -> %d\n", uid,
3129                        attr->la_uid, gid, attr->la_gid);
3130                 enforce = (attr->la_valid & LA_GID) && (attr->la_gid != gid);
3131                 rc = osd_declare_attr_qid(env, obj, oh, bspace, gid,
3132                                           attr->la_gid, enforce, GRPQUOTA);
3133                 if (rc)
3134                         RETURN(rc);
3135
3136         }
3137 #ifdef HAVE_PROJECT_QUOTA
3138         if (attr->la_valid & LA_PROJID) {
3139                 __u32 projid = i_projid_read(obj->oo_inode);
3140
3141                 enforce = (attr->la_valid & LA_PROJID) &&
3142                                         (attr->la_projid != projid);
3143                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
3144                                           (qid_t)projid, (qid_t)attr->la_projid,
3145                                           enforce, PRJQUOTA);
3146                 if (rc)
3147                         RETURN(rc);
3148         }
3149 #endif
3150         /* punch must be aware we are dealing with an encrypted file */
3151         if (attr->la_valid & LA_FLAGS && attr->la_flags & LUSTRE_ENCRYPT_FL)
3152                 obj->oo_lma_flags |= LUSTRE_ENCRYPT_FL;
3153
3154         RETURN(rc);
3155 }
3156
3157 static int osd_inode_setattr(const struct lu_env *env,
3158                              struct inode *inode, const struct lu_attr *attr)
3159 {
3160         __u64 bits = attr->la_valid;
3161
3162         /* Only allow set size for regular file */
3163         if (!S_ISREG(inode->i_mode))
3164                 bits &= ~(LA_SIZE | LA_BLOCKS);
3165
3166         if (bits == 0)
3167                 return 0;
3168
3169         if (bits & LA_ATIME)
3170                 inode->i_atime = osd_inode_time(inode, attr->la_atime);
3171         if (bits & LA_CTIME)
3172                 inode->i_ctime = osd_inode_time(inode, attr->la_ctime);
3173         if (bits & LA_MTIME)
3174                 inode->i_mtime = osd_inode_time(inode, attr->la_mtime);
3175         if (bits & LA_SIZE) {
3176                 spin_lock(&inode->i_lock);
3177                 LDISKFS_I(inode)->i_disksize = attr->la_size;
3178                 i_size_write(inode, attr->la_size);
3179                 spin_unlock(&inode->i_lock);
3180         }
3181
3182         /*
3183          * OSD should not change "i_blocks" which is used by quota.
3184          * "i_blocks" should be changed by ldiskfs only.
3185          */
3186         if (bits & LA_MODE)
3187                 inode->i_mode = (inode->i_mode & S_IFMT) |
3188                                 (attr->la_mode & ~S_IFMT);
3189         if (bits & LA_UID)
3190                 i_uid_write(inode, attr->la_uid);
3191         if (bits & LA_GID)
3192                 i_gid_write(inode, attr->la_gid);
3193         if (bits & LA_PROJID)
3194                 i_projid_write(inode, attr->la_projid);
3195         if (bits & LA_NLINK)
3196                 set_nlink(inode, attr->la_nlink);
3197         if (bits & LA_RDEV)
3198                 inode->i_rdev = attr->la_rdev;
3199
3200         if (bits & LA_FLAGS) {
3201                 /* always keep S_NOCMTIME */
3202                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
3203                                  S_NOCMTIME;
3204 #if defined(S_ENCRYPTED)
3205                 /* Always remove S_ENCRYPTED, because ldiskfs must not be
3206                  * aware of encryption status. It is just stored into LMA
3207                  * so that it can be forwared to client side.
3208                  */
3209                 inode->i_flags &= ~S_ENCRYPTED;
3210 #endif
3211                 /*
3212                  * Ext4 did not transfer inherit flags from
3213                  * @inode->i_flags to raw inode i_flags when writing
3214                  * flags, we do it explictly here.
3215                  */
3216                 if (attr->la_flags & LUSTRE_PROJINHERIT_FL)
3217                         LDISKFS_I(inode)->i_flags |= LUSTRE_PROJINHERIT_FL;
3218                 else
3219                         LDISKFS_I(inode)->i_flags &= ~LUSTRE_PROJINHERIT_FL;
3220         }
3221         return 0;
3222 }
3223
3224 #ifdef HAVE_PROJECT_QUOTA
3225 static int osd_transfer_project(struct inode *inode, __u32 projid,
3226                                 struct thandle *handle)
3227 {
3228         struct super_block *sb = inode->i_sb;
3229         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
3230         int err;
3231         kprojid_t kprojid;
3232         struct ldiskfs_iloc iloc;
3233         struct ldiskfs_inode *raw_inode;
3234         struct dquot *transfer_to[LDISKFS_MAXQUOTAS] = { };
3235
3236         if (!ldiskfs_has_feature_project(sb)) {
3237                 LASSERT(__kprojid_val(LDISKFS_I(inode)->i_projid)
3238                         == LDISKFS_DEF_PROJID);
3239                 if (projid != LDISKFS_DEF_PROJID)
3240                         return -EOPNOTSUPP;
3241                 else
3242                         return 0;
3243         }
3244
3245         if (LDISKFS_INODE_SIZE(sb) <= LDISKFS_GOOD_OLD_INODE_SIZE)
3246                 return -EOPNOTSUPP;
3247
3248         kprojid = make_kprojid(&init_user_ns, (projid_t)projid);
3249         if (projid_eq(kprojid, LDISKFS_I(inode)->i_projid))
3250                 return 0;
3251
3252         err = ldiskfs_get_inode_loc(inode, &iloc);
3253         if (err)
3254                 return err;
3255
3256         raw_inode = ldiskfs_raw_inode(&iloc);
3257         if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3258                 struct osd_thandle *oh = container_of(handle,
3259                                                       struct osd_thandle,
3260                                                       ot_super);
3261                 /**
3262                  * try to expand inode size automatically.
3263                  */
3264                 ldiskfs_mark_inode_dirty(oh->ot_handle, inode);
3265                 if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3266                         err = -EOVERFLOW;
3267                         brelse(iloc.bh);
3268                         return err;
3269                 }
3270         }
3271         brelse(iloc.bh);
3272
3273         dquot_initialize(inode);
3274         transfer_to[PRJQUOTA] = dqget(sb, make_kqid_projid(kprojid));
3275         if (transfer_to[PRJQUOTA]) {
3276                 lock_dquot_transfer(inode);
3277                 err = __dquot_transfer(inode, transfer_to);
3278                 unlock_dquot_transfer(inode);
3279                 dqput(transfer_to[PRJQUOTA]);
3280                 if (err)
3281                         return err;
3282         }
3283
3284         return err;
3285 }
3286 #endif
3287
3288 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr,
3289                               struct thandle *handle)
3290 {
3291         int rc;
3292
3293         if ((attr->la_valid & LA_UID && attr->la_uid != i_uid_read(inode)) ||
3294             (attr->la_valid & LA_GID && attr->la_gid != i_gid_read(inode))) {
3295                 struct iattr iattr;
3296
3297                 CDEBUG(D_QUOTA,
3298                        "executing dquot_transfer inode %ld uid %d -> %d gid %d -> %d\n",
3299                        inode->i_ino, i_uid_read(inode), attr->la_uid,
3300                        i_gid_read(inode), attr->la_gid);
3301
3302                 dquot_initialize(inode);
3303                 iattr.ia_valid = 0;
3304                 if (attr->la_valid & LA_UID)
3305                         iattr.ia_valid |= ATTR_UID;
3306                 if (attr->la_valid & LA_GID)
3307                         iattr.ia_valid |= ATTR_GID;
3308                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
3309                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
3310
3311                 lock_dquot_transfer(inode);
3312                 rc = osd_dquot_transfer(&nop_mnt_idmap, inode, &iattr);
3313                 unlock_dquot_transfer(inode);
3314                 if (rc) {
3315                         CERROR("%s: quota transfer failed. Is quota enforcement enabled on the ldiskfs filesystem? rc = %d\n",
3316                                osd_ino2name(inode), rc);
3317                         return rc;
3318                 }
3319         }
3320
3321         /* Handle project id transfer here properly */
3322         if (attr->la_valid & LA_PROJID &&
3323             attr->la_projid != i_projid_read(inode)) {
3324                 if (!projid_valid(make_kprojid(&init_user_ns, attr->la_projid)))
3325                         return -EINVAL;
3326 #ifdef HAVE_PROJECT_QUOTA
3327                 rc = osd_transfer_project(inode, attr->la_projid, handle);
3328 #else
3329                 rc = -ENOTSUPP;
3330 #endif
3331                 if (rc) {
3332                         CERROR("%s: quota transfer failed. Is project enforcement enabled on the ldiskfs filesystem? rc = %d\n",
3333                                osd_ino2name(inode), rc);
3334                         return rc;
3335                 }
3336         }
3337         return 0;
3338 }
3339
3340 static int osd_attr_set(const struct lu_env *env,
3341                         struct dt_object *dt,
3342                         const struct lu_attr *attr,
3343                         struct thandle *handle)
3344 {
3345         struct osd_thread_info *info = osd_oti_get(env);
3346         struct osd_object *obj = osd_dt_obj(dt);
3347         struct osd_device *osd = osd_obj2dev(obj);
3348         struct inode *inode;
3349         int rc;
3350
3351         if (!dt_object_exists(dt))
3352                 return -ENOENT;
3353
3354         LASSERT(handle != NULL);
3355         LASSERT(!dt_object_remote(dt));
3356         LASSERT(osd_invariant(obj));
3357
3358         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
3359
3360         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING) &&
3361             !osd_obj2dev(obj)->od_is_ost) {
3362                 struct osd_thread_info *oti = osd_oti_get(env);
3363                 const struct lu_fid *fid0 = lu_object_fid(&dt->do_lu);
3364                 struct lu_fid *fid1 = &oti->oti_fid;
3365                 struct osd_inode_id *id = &oti->oti_id;
3366                 struct iam_path_descr *ipd;
3367                 struct iam_container *bag;
3368                 struct osd_thandle *oh;
3369                 int rc;
3370
3371                 fid_cpu_to_be(fid1, fid0);
3372                 memset(id, 1, sizeof(*id));
3373                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
3374                                   fid0)->oi_dir.od_container;
3375                 ipd = osd_idx_ipd_get(env, bag);
3376                 if (unlikely(ipd == NULL))
3377                         RETURN(-ENOMEM);
3378
3379                 oh = container_of(handle, struct osd_thandle, ot_super);
3380                 rc = iam_update(oh->ot_handle, bag,
3381                                 (const struct iam_key *)fid1,
3382                                 (const struct iam_rec *)id, ipd);
3383                 osd_ipd_put(env, bag, ipd);
3384                 return(rc > 0 ? 0 : rc);
3385         }
3386
3387         inode = obj->oo_inode;
3388
3389         rc = osd_quota_transfer(inode, attr, handle);
3390         if (rc)
3391                 return rc;
3392
3393         spin_lock(&obj->oo_guard);
3394         rc = osd_inode_setattr(env, inode, attr);
3395         spin_unlock(&obj->oo_guard);
3396         if (rc != 0)
3397                 GOTO(out, rc);
3398
3399         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3400
3401         osd_trans_exec_check(env, handle, OSD_OT_ATTR_SET);
3402
3403         if (!(attr->la_valid & LA_FLAGS))
3404                 GOTO(out, rc);
3405
3406         /* If setting LUSTRE_ENCRYPT_FL on an OST object, also set a dummy
3407          * enc ctx xattr, with 2 benefits:
3408          * - setting the LL_XATTR_NAME_ENCRYPTION_CONTEXT xattr internally sets
3409          *   the LDISKFS_ENCRYPT_FL flag on the on-disk inode;
3410          * - it makes e2fsprogs happy to see an enc ctx for an inode that has
3411          *   the LDISKFS_ENCRYPT_FL flag
3412          * We do not need the actual encryption context on OST objects, it is
3413          * only stored on MDT inodes, at file creation time.
3414          */
3415         if (!(LDISKFS_I(obj->oo_inode)->i_flags & LDISKFS_ENCRYPT_FL) &&
3416             attr->la_flags & LUSTRE_ENCRYPT_FL && osd->od_is_ost &&
3417             !CFS_FAIL_CHECK(OBD_FAIL_LFSCK_NO_ENCFLAG)) {
3418                 struct lu_buf buf;
3419
3420                 /* use a dummy enc ctx, fine with e2fsprogs */
3421                 buf.lb_buf = "\xFF";
3422                 buf.lb_len = 1;
3423                 rc = osd_xattr_set(env, dt, &buf,
3424                                    LL_XATTR_NAME_ENCRYPTION_CONTEXT,
3425                                    0, handle);
3426                 if (rc)
3427                         CWARN("%s: set "DFID" enc ctx failed: rc = %d\n",
3428                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
3429                               rc);
3430         }
3431
3432         /* Let's check if there are extra flags need to be set into LMA */
3433         if (attr->la_flags & LUSTRE_LMA_FL_MASKS) {
3434                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
3435
3436                 LASSERT(!obj->oo_pfid_in_lma);
3437
3438                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
3439                                  &info->oti_ost_attrs);
3440                 if (rc)
3441                         GOTO(out, rc);
3442
3443                 if ((lma->lma_incompat & lustre_to_lma_flags(attr->la_flags)) ==
3444                     lustre_to_lma_flags(attr->la_flags))
3445                         /* if lma incompat already has the flags,
3446                          * save a useless call to xattr_set
3447                          */
3448                         GOTO(out, rc = 0);
3449
3450                 lma->lma_incompat |=
3451                         lustre_to_lma_flags(attr->la_flags);
3452                 lustre_lma_swab(lma);
3453
3454                 osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3455
3456                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA,
3457                                      lma, sizeof(*lma), XATTR_REPLACE);
3458                 if (rc != 0)
3459                         CWARN("%s: set "DFID" lma flags %u failed: rc = %d\n",
3460                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
3461                               lma->lma_incompat, rc);
3462                 else
3463                         obj->oo_lma_flags =
3464                                 attr->la_flags & LUSTRE_LMA_FL_MASKS;
3465                 osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
3466         }
3467
3468 out:
3469         return rc;
3470 }
3471
3472 static struct dentry *osd_child_dentry_get(const struct lu_env *env,
3473                                            struct osd_object *obj,
3474                                            const char *name, const int namelen)
3475 {
3476         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
3477 }
3478
3479 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
3480                       umode_t mode, struct dt_allocation_hint *hint,
3481                       struct thandle *th, struct lu_attr *attr)
3482 {
3483         int result;
3484         struct osd_device *osd = osd_obj2dev(obj);
3485         struct osd_thandle *oth;
3486         struct dt_object *parent = NULL;
3487         struct inode *inode;
3488         struct iattr iattr = {
3489                 .ia_valid = ATTR_UID | ATTR_GID |
3490                             ATTR_CTIME | ATTR_MTIME | ATTR_ATIME,
3491                 .ia_ctime.tv_sec = attr->la_ctime,
3492                 .ia_mtime.tv_sec = attr->la_mtime,
3493                 .ia_atime.tv_sec = attr->la_atime,
3494                 .ia_uid = GLOBAL_ROOT_UID,
3495                 .ia_gid = GLOBAL_ROOT_GID,
3496         };
3497         const struct osd_timespec omit = { .tv_nsec = UTIME_OMIT };
3498
3499         if (attr->la_valid & LA_UID)
3500                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
3501         if (attr->la_valid & LA_GID)
3502                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
3503
3504         LINVRNT(osd_invariant(obj));
3505         LASSERT(obj->oo_inode == NULL);
3506         LASSERT(obj->oo_hl_head == NULL);
3507
3508         if (S_ISDIR(mode) && ldiskfs_pdo) {
3509                 obj->oo_hl_head =
3510                         ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
3511                 if (obj->oo_hl_head == NULL)
3512                         return -ENOMEM;
3513         }
3514
3515         oth = container_of(th, struct osd_thandle, ot_super);
3516         LASSERT(oth->ot_handle->h_transaction != NULL);
3517
3518         if (hint != NULL && hint->dah_parent != NULL &&
3519             !dt_object_remote(hint->dah_parent))
3520                 parent = hint->dah_parent;
3521
3522         /* if a time component is not valid set it to UTIME_OMIT */
3523         if (!(attr->la_valid & LA_CTIME))
3524                 iattr.ia_ctime = omit;
3525         if (!(attr->la_valid & LA_MTIME))
3526                 iattr.ia_mtime = omit;
3527         if (!(attr->la_valid & LA_ATIME))
3528                 iattr.ia_atime = omit;
3529
3530         inode = ldiskfs_create_inode(oth->ot_handle,
3531                                      parent ? osd_dt_obj(parent)->oo_inode :
3532                                               osd_sb(osd)->s_root->d_inode,
3533                                      mode, &iattr);
3534         if (!IS_ERR(inode)) {
3535                 /* Do not update file c/mtime in ldiskfs. */
3536                 inode->i_flags |= S_NOCMTIME;
3537
3538                 /*
3539                  * For new created object, it must be consistent,
3540                  * and it is unnecessary to scrub against it.
3541                  */
3542                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
3543
3544                 obj->oo_inode = inode;
3545                 result = 0;
3546         } else {
3547                 if (obj->oo_hl_head != NULL) {
3548                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
3549                         obj->oo_hl_head = NULL;
3550                 }
3551                 result = PTR_ERR(inode);
3552         }
3553         LINVRNT(osd_invariant(obj));
3554         return result;
3555 }
3556
3557 enum {
3558         OSD_NAME_LEN = 255
3559 };
3560
3561 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
3562                      struct lu_attr *attr,
3563                      struct dt_allocation_hint *hint,
3564                      struct dt_object_format *dof,
3565                      struct thandle *th)
3566 {
3567         int result;
3568         struct osd_thandle *oth;
3569         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX | S_ISGID));
3570
3571         LASSERT(S_ISDIR(attr->la_mode));
3572
3573         oth = container_of(th, struct osd_thandle, ot_super);
3574         LASSERT(oth->ot_handle->h_transaction != NULL);
3575         if (fid_is_namespace_visible(lu_object_fid(&obj->oo_dt.do_lu)))
3576                 atomic_set(&obj->oo_dirent_count, 0);
3577         result = osd_mkfile(info, obj, mode, hint, th, attr);
3578
3579         return result;
3580 }
3581
3582 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
3583                         struct lu_attr *attr,
3584                         struct dt_allocation_hint *hint,
3585                         struct dt_object_format *dof,
3586                         struct thandle *th)
3587 {
3588         int result;
3589         struct osd_thandle *oth;
3590         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
3591
3592         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
3593
3594         LASSERT(S_ISREG(attr->la_mode));
3595
3596         oth = container_of(th, struct osd_thandle, ot_super);
3597         LASSERT(oth->ot_handle->h_transaction != NULL);
3598
3599         result = osd_mkfile(info, obj, mode, hint, th, attr);
3600         if (result == 0) {
3601                 LASSERT(obj->oo_inode != NULL);
3602                 if (feat->dif_flags & DT_IND_VARKEY)
3603                         result = iam_lvar_create(obj->oo_inode,
3604                                                  feat->dif_keysize_max,
3605                                                  feat->dif_ptrsize,
3606                                                  feat->dif_recsize_max,
3607                                                  oth->ot_handle);
3608                 else
3609                         result = iam_lfix_create(obj->oo_inode,
3610                                                  feat->dif_keysize_max,
3611                                                  feat->dif_ptrsize,
3612                                                  feat->dif_recsize_max,
3613                                                  oth->ot_handle);
3614         }
3615         return result;
3616 }
3617
3618 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
3619                      struct lu_attr *attr,
3620                      struct dt_allocation_hint *hint,
3621                      struct dt_object_format *dof,
3622                      struct thandle *th)
3623 {
3624         LASSERT(S_ISREG(attr->la_mode));
3625         return osd_mkfile(info, obj, (attr->la_mode &
3626                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3627                           attr);
3628 }
3629
3630 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
3631                      struct lu_attr *attr,
3632                      struct dt_allocation_hint *hint,
3633                      struct dt_object_format *dof,
3634                      struct thandle *th)
3635 {
3636         LASSERT(S_ISLNK(attr->la_mode));
3637         return osd_mkfile(info, obj, (attr->la_mode &
3638                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3639                           attr);
3640 }
3641
3642 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
3643                      struct lu_attr *attr,
3644                      struct dt_allocation_hint *hint,
3645                      struct dt_object_format *dof,
3646                      struct thandle *th)
3647 {
3648         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
3649         int result;
3650
3651         LINVRNT(osd_invariant(obj));
3652         LASSERT(obj->oo_inode == NULL);
3653         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
3654                 S_ISFIFO(mode) || S_ISSOCK(mode));
3655
3656         result = osd_mkfile(info, obj, mode, hint, th, attr);
3657         if (result == 0) {
3658                 LASSERT(obj->oo_inode != NULL);
3659                 /*
3660                  * This inode should be marked dirty for i_rdev.  Currently
3661                  * that is done in the osd_attr_init().
3662                  */
3663                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
3664                                    attr->la_rdev);
3665         }
3666         LINVRNT(osd_invariant(obj));
3667         return result;
3668 }
3669
3670 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
3671                               struct lu_attr *,
3672                               struct dt_allocation_hint *hint,
3673                               struct dt_object_format *dof,
3674                               struct thandle *);
3675
3676 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
3677 {
3678         osd_obj_type_f result;
3679
3680         switch (type) {
3681         case DFT_DIR:
3682                 result = osd_mkdir;
3683                 break;
3684         case DFT_REGULAR:
3685                 result = osd_mkreg;
3686                 break;
3687         case DFT_SYM:
3688                 result = osd_mksym;
3689                 break;
3690         case DFT_NODE:
3691                 result = osd_mknod;
3692                 break;
3693         case DFT_INDEX:
3694                 result = osd_mk_index;
3695                 break;
3696
3697         default:
3698                 LBUG();
3699                 break;
3700         }
3701         return result;
3702 }
3703
3704 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
3705                         struct dt_object *parent, struct dt_object *child,
3706                         umode_t child_mode)
3707 {
3708         LASSERT(ah);
3709
3710         ah->dah_parent = parent;
3711
3712         if (parent != NULL && !dt_object_remote(parent)) {
3713                 /* will help to find FID->ino at dt_insert("..") */
3714                 struct osd_object *pobj = osd_dt_obj(parent);
3715
3716                 osd_idc_find_and_init(env, osd_obj2dev(pobj), pobj);
3717         }
3718 }
3719
3720 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
3721                           struct lu_attr *attr, struct dt_object_format *dof,
3722                           struct thandle *handle)
3723 {
3724         struct inode *inode = obj->oo_inode;
3725         __u64 valid = attr->la_valid;
3726         int result;
3727
3728         attr->la_valid &= ~(LA_TYPE | LA_MODE);
3729
3730         if (dof->dof_type != DFT_NODE)
3731                 attr->la_valid &= ~LA_RDEV;
3732         if ((valid & LA_ATIME) && (attr->la_atime == inode->i_atime.tv_sec))
3733                 attr->la_valid &= ~LA_ATIME;
3734         if ((valid & LA_CTIME) && (attr->la_ctime == inode->i_ctime.tv_sec))
3735                 attr->la_valid &= ~LA_CTIME;
3736         if ((valid & LA_MTIME) && (attr->la_mtime == inode->i_mtime.tv_sec))
3737                 attr->la_valid &= ~LA_MTIME;
3738
3739         result = osd_quota_transfer(inode, attr, handle);
3740         if (result)
3741                 return;
3742
3743         if (attr->la_valid != 0) {
3744                 result = osd_inode_setattr(info->oti_env, inode, attr);
3745                 /*
3746                  * The osd_inode_setattr() should always succeed here.  The
3747                  * only error that could be returned is EDQUOT when we are
3748                  * trying to change the UID or GID of the inode. However, this
3749                  * should not happen since quota enforcement is no longer
3750                  * enabled on ldiskfs (lquota takes care of it).
3751                  */
3752                 LASSERTF(result == 0, "%d\n", result);
3753                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
3754         }
3755
3756         attr->la_valid = valid;
3757 }
3758
3759 /**
3760  * Helper function for osd_create()
3761  *
3762  * \retval 0, on success
3763  */
3764 static int __osd_create(struct osd_thread_info *info, struct osd_object *obj,
3765                         struct lu_attr *attr, struct dt_allocation_hint *hint,
3766                         struct dt_object_format *dof, struct thandle *th)
3767 {
3768         int result;
3769         __u32 umask;
3770
3771         osd_trans_exec_op(info->oti_env, th, OSD_OT_CREATE);
3772
3773         /* we drop umask so that permissions we pass are not affected */
3774         umask = current->fs->umask;
3775         current->fs->umask = 0;
3776
3777         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
3778                                                   th);
3779         if (likely(obj->oo_inode != NULL)) {
3780                 LASSERT(obj->oo_inode->i_state & I_NEW);
3781
3782                 /*
3783                  * Unlock the inode before attr initialization to avoid
3784                  * unnecessary dqget operations. LU-6378
3785                  */
3786                 unlock_new_inode(obj->oo_inode);
3787         }
3788
3789         if (likely(result == 0)) {
3790                 osd_attr_init(info, obj, attr, dof, th);
3791                 osd_object_init0(obj);
3792         }
3793
3794         /* restore previous umask value */
3795         current->fs->umask = umask;
3796
3797         osd_trans_exec_check(info->oti_env, th, OSD_OT_CREATE);
3798
3799         return result;
3800 }
3801
3802 /**
3803  * Helper function for osd_create()
3804  *
3805  * \retval 0, on success
3806  */
3807 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
3808                            const struct lu_fid *fid, struct thandle *th)
3809 {
3810         struct osd_thread_info *info = osd_oti_get(env);
3811         struct osd_inode_id    *id   = &info->oti_id;
3812         struct osd_device      *osd  = osd_obj2dev(obj);
3813         struct osd_thandle     *oh;
3814         int rc;
3815
3816         LASSERT(obj->oo_inode != NULL);
3817
3818         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_OI_ENOSPC))
3819                 return -ENOSPC;
3820
3821         oh = container_of(th, struct osd_thandle, ot_super);
3822         LASSERT(oh->ot_handle);
3823         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3824
3825         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
3826         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_FID_REUSE) && osd->od_is_ost &&
3827             fid->f_oid) {
3828                 struct lu_fid tfid = *fid;
3829
3830                 tfid.f_oid--;
3831                 osd_oi_insert(info, osd, &tfid, id, oh->ot_handle,
3832                               OI_CHECK_FLD, NULL);
3833                 /* clear NOSCRUB flag so that it can be scrubbed immediately */
3834                 ldiskfs_clear_inode_state(obj->oo_inode,
3835                                           LDISKFS_STATE_LUSTRE_NOSCRUB);
3836                 rc = 0;
3837         } else {
3838                 rc = osd_oi_insert(info, osd, fid, id, oh->ot_handle,
3839                                    OI_CHECK_FLD, NULL);
3840         }
3841         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP) && osd->od_is_ost) {
3842                 struct lu_fid next_fid = *fid;
3843
3844                 /* insert next object in advance, and map to the same inode */
3845                 next_fid.f_oid++;
3846                 if (next_fid.f_oid != 0) {
3847                         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3848                         osd_oi_insert(info, osd, &next_fid, id, oh->ot_handle,
3849                                       OI_CHECK_FLD, NULL);
3850                         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3851                 }
3852         }
3853
3854         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3855
3856         return rc;
3857 }
3858
3859 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
3860                    u64 seq, struct lu_seq_range *range)
3861 {
3862         struct seq_server_site *ss = osd_seq_site(osd);
3863
3864         if (fid_seq_is_idif(seq)) {
3865                 fld_range_set_ost(range);
3866                 range->lsr_index = idif_ost_idx(seq);
3867                 return 0;
3868         }
3869
3870         if (!fid_seq_in_fldb(seq)) {
3871                 fld_range_set_mdt(range);
3872                 if (ss != NULL)
3873                         /*
3874                          * FIXME: If ss is NULL, it suppose not get lsr_index
3875                          * at all
3876                          */
3877                         range->lsr_index = ss->ss_node_id;
3878                 return 0;
3879         }
3880
3881         LASSERT(ss != NULL);
3882         fld_range_set_any(range);
3883         /* OSD will only do local fld lookup */
3884         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
3885 }
3886
3887 static int osd_declare_create(const struct lu_env *env, struct dt_object *dt,
3888                               struct lu_attr *attr,
3889                               struct dt_allocation_hint *hint,
3890                               struct dt_object_format *dof,
3891                               struct thandle *handle)
3892 {
3893         struct osd_thandle *oh;
3894         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
3895         int credits;
3896         int rc;
3897
3898         ENTRY;
3899
3900         LASSERT(handle != NULL);
3901
3902         oh = container_of(handle, struct osd_thandle, ot_super);
3903         LASSERT(oh->ot_handle == NULL);
3904
3905         if (osd_tx_was_declared(env, oh, dt, DTO_OBJECT_CREATE, 0))
3906                 RETURN(0);
3907
3908         /*
3909          * EA object consumes more credits than regular object: osd_mk_index
3910          * vs. osd_mkreg: osd_mk_index will create 2 blocks for root_node and
3911          * leaf_node, could involves the block, block bitmap, groups, GDT
3912          * change for each block, so add 4 * 2 credits in that case.
3913          *
3914          * The default ACL initialization may consume an additional 16 blocks
3915          */
3916         credits = osd_dto_credits_noquota[DTO_OBJECT_CREATE] +
3917                   ((dof->dof_type == DFT_INDEX) ? 4 * 2 : 0);
3918
3919         /**
3920          * While ldiskfs_new_inode() calls ldiskfs_init_acl() we have to add
3921          * credits for possible default ACL creation in new inode
3922          */
3923         if (hint && hint->dah_acl_len)
3924                 credits += osd_calc_bkmap_credits(sb, NULL, 0, -1,
3925                                 (hint->dah_acl_len + sb->s_blocksize - 1) >>
3926                                 sb->s_blocksize_bits);
3927
3928         osd_trans_declare_op(env, oh, OSD_OT_CREATE, credits);
3929
3930         /*
3931          * Reuse idle OI block may cause additional one OI block
3932          * to be changed.
3933          */
3934         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3935                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3936         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP))
3937                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3938                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3939
3940         /* will help to find FID->ino mapping at dt_insert() */
3941         rc = osd_idc_find_and_init(env, osd_obj2dev(osd_dt_obj(dt)),
3942                                    osd_dt_obj(dt));
3943         if (rc != 0)
3944                 RETURN(rc);
3945
3946         if (!attr)
3947                 RETURN(0);
3948
3949         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid,
3950                                    attr->la_projid, 1, oh, osd_dt_obj(dt),
3951                                    NULL, OSD_QID_INODE);
3952         if (rc != 0)
3953                 RETURN(rc);
3954
3955         RETURN(rc);
3956 }
3957
3958 /**
3959  * Called to destroy on-disk representation of the object
3960  *
3961  * Concurrency: must be locked
3962  */
3963 static int osd_declare_destroy(const struct lu_env *env, struct dt_object *dt,
3964                                struct thandle *th)
3965 {
3966         struct osd_object *obj = osd_dt_obj(dt);
3967         struct inode *inode = obj->oo_inode;
3968         struct osd_thandle *oh;
3969         int rc;
3970
3971         ENTRY;
3972
3973         if (inode == NULL)
3974                 RETURN(-ENOENT);
3975
3976         oh = container_of(th, struct osd_thandle, ot_super);
3977         LASSERT(oh->ot_handle == NULL);
3978
3979         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
3980                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
3981
3982         /* For removing agent entry */
3983         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu))
3984                 oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_DELETE];
3985
3986         /*
3987          * Recycle idle OI leaf may cause additional three OI blocks
3988          * to be changed.
3989          */
3990         if (!CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3991                 osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3992                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
3993         /* one less inode */
3994         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3995                                    i_projid_read(inode), -1, oh, obj, NULL,
3996                                    OSD_QID_INODE);
3997         if (rc)
3998                 RETURN(rc);
3999         /* data to be truncated */
4000         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
4001                                    i_projid_read(inode), 0, oh, obj, NULL,
4002                                    OSD_QID_BLK);
4003         if (rc)
4004                 RETURN(rc);
4005
4006         /*
4007          * will help to find FID->ino when this object is being
4008          * added to PENDING
4009          */
4010         rc = osd_idc_find_and_init(env, osd_obj2dev(obj), obj);
4011
4012         RETURN(rc);
4013 }
4014
4015 static int osd_destroy(const struct lu_env *env, struct dt_object *dt,
4016                        struct thandle *th)
4017 {
4018         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
4019         struct osd_object *obj = osd_dt_obj(dt);
4020         struct inode *inode = obj->oo_inode;
4021         struct osd_device *osd = osd_obj2dev(obj);
4022         struct osd_thandle *oh;
4023         int result;
4024
4025         ENTRY;
4026
4027         oh = container_of(th, struct osd_thandle, ot_super);
4028         LASSERT(oh->ot_handle);
4029         LASSERT(inode);
4030         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
4031
4032         if (unlikely(fid_is_acct(fid)))
4033                 RETURN(-EPERM);
4034
4035         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu)) {
4036                 result = osd_delete_from_remote_parent(env, osd, obj, oh, true);
4037                 if (result != 0)
4038                         CERROR("%s: remove agent entry "DFID": rc = %d\n",
4039                                osd_name(osd), PFID(fid), result);
4040         }
4041
4042         if (S_ISDIR(inode->i_mode)) {
4043                 if (inode->i_nlink > 2)
4044                         CERROR("%s: directory "DFID" ino %lu link count is %u at unlink. run e2fsck to repair\n",
4045                                osd_name(osd), PFID(fid), inode->i_ino,
4046                                inode->i_nlink);
4047
4048                 spin_lock(&obj->oo_guard);
4049                 clear_nlink(inode);
4050                 spin_unlock(&obj->oo_guard);
4051                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4052         }
4053
4054         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
4055
4056         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
4057
4058         if (!CFS_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
4059                 result = osd_oi_delete(osd_oti_get(env), osd, fid,
4060                                        oh->ot_handle, OI_CHECK_FLD);
4061
4062         osd_trans_exec_check(env, th, OSD_OT_DESTROY);
4063         /* XXX: add to ext3 orphan list */
4064         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
4065
4066         /* not needed in the cache anymore */
4067         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
4068         obj->oo_destroyed = 1;
4069
4070         RETURN(0);
4071 }
4072
4073 /**
4074  * Put the fid into lustre_mdt_attrs, and then place the structure
4075  * inode's ea. This fid should not be altered during the life time
4076  * of the inode.
4077  *
4078  * \retval +ve, on success
4079  * \retval -ve, on error
4080  *
4081  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
4082  */
4083 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
4084                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
4085 {
4086         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4087         struct lustre_mdt_attrs *lma = &loa->loa_lma;
4088         int rc;
4089
4090         ENTRY;
4091
4092         if (CFS_FAIL_CHECK(OBD_FAIL_FID_INLMA))
4093                 RETURN(0);
4094
4095         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_OST_EA_FID_SET))
4096                 rc = -ENOMEM;
4097
4098         lustre_loa_init(loa, fid, compat, incompat);
4099         lustre_loa_swab(loa, false);
4100
4101         /*
4102          * For the OST device with 256 bytes inode size by default,
4103          * the PFID EA will be stored together with LMA EA to avoid
4104          * performance trouble. Otherwise the PFID EA can be stored
4105          * independently. LU-8998
4106          */
4107         if ((compat & LMAC_FID_ON_OST) &&
4108             LDISKFS_INODE_SIZE(inode->i_sb) <= 256)
4109                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
4110                                      sizeof(*loa), XATTR_CREATE);
4111         else
4112                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4113                                      sizeof(*lma), XATTR_CREATE);
4114         /*
4115          * LMA may already exist, but we need to check that all the
4116          * desired compat/incompat flags have been added.
4117          */
4118         if (unlikely(rc == -EEXIST)) {
4119                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
4120                                      XATTR_NAME_LMA, (void *)loa, sizeof(*loa));
4121                 if (rc < 0)
4122                         RETURN(rc);
4123
4124                 if (rc < sizeof(*lma))
4125                         RETURN(-EINVAL);
4126
4127                 lustre_loa_swab(loa, true);
4128                 if (lu_fid_eq(fid, &lma->lma_self_fid) &&
4129                     ((compat == 0 && incompat == 0) ||
4130                      (!(~lma->lma_compat & compat) &&
4131                       !(~lma->lma_incompat & incompat))))
4132                         RETURN(0);
4133
4134                 lma->lma_self_fid = *fid;
4135                 lma->lma_compat |= compat;
4136                 lma->lma_incompat |= incompat;
4137                 if (rc == sizeof(*lma)) {
4138                         lustre_lma_swab(lma);
4139                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4140                                              sizeof(*lma), XATTR_REPLACE);
4141                 } else {
4142                         lustre_loa_swab(loa, false);
4143                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
4144                                              sizeof(*loa), XATTR_REPLACE);
4145                 }
4146         }
4147
4148         RETURN(rc);
4149 }
4150
4151 /**
4152  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
4153  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
4154  * To have compatilibility with 1.8 ldiskfs driver we need to have
4155  * magic number at start of fid data.
4156  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
4157  * its inmemory API.
4158  */
4159 static void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
4160                                          const struct lu_fid *fid)
4161 {
4162         if (!fid_is_namespace_visible(fid) ||
4163             CFS_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
4164                 param->edp_magic = 0;
4165                 return;
4166         }
4167
4168         param->edp_magic = LDISKFS_LUFID_MAGIC;
4169         param->edp_len =  sizeof(struct lu_fid) + 1;
4170         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
4171 }
4172
4173 /**
4174  * Try to read the fid from inode ea into dt_rec.
4175  *
4176  * \param fid object fid.
4177  *
4178  * \retval 0 on success
4179  */
4180 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
4181                           __u32 ino, struct lu_fid *fid,
4182                           struct osd_inode_id *id)
4183 {
4184         struct osd_thread_info *info  = osd_oti_get(env);
4185         struct inode *inode;
4186
4187         ENTRY;
4188
4189         osd_id_gen(id, ino, OSD_OII_NOGEN);
4190         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
4191         if (IS_ERR(inode))
4192                 RETURN(PTR_ERR(inode));
4193
4194         iput(inode);
4195         RETURN(0);
4196 }
4197
4198 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
4199                                         struct inode *dir,
4200                                         struct inode *parent_dir,
4201                                         const struct lu_fid *dot_fid,
4202                                         const struct lu_fid *dot_dot_fid,
4203                                         struct osd_thandle *oth)
4204 {
4205         struct ldiskfs_dentry_param *dot_ldp;
4206         struct ldiskfs_dentry_param *dot_dot_ldp;
4207         __u32 saved_nlink = dir->i_nlink;
4208         int rc;
4209
4210         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DOTDOT_ENOSPC))
4211                 return -ENOSPC;
4212
4213         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
4214         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
4215
4216         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
4217         dot_ldp->edp_magic = 0;
4218
4219         rc = ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
4220                                     dir, dot_ldp, dot_dot_ldp);
4221         /*
4222          * The ldiskfs_add_dot_dotdot() may dir->i_nlink as 2, then
4223          * the subseqent ref_add() will increase the dir->i_nlink
4224          * as 3. That is incorrect for new created directory.
4225          *
4226          * It looks like hack, because we want to make the OSD API
4227          * to be order-independent for new created directory object
4228          * between dt_insert(..) and ref_add() operations.
4229          *
4230          * Here, we only restore the in-RAM dir-inode's nlink attr,
4231          * becuase if the nlink attr is not 2, then there will be
4232          * ref_add() called following the dt_insert(..), such call
4233          * will make both the in-RAM and on-disk dir-inode's nlink
4234          * attr to be set as 2. LU-7447
4235          */
4236         set_nlink(dir, saved_nlink);
4237         return rc;
4238 }
4239
4240 /**
4241  * Create an local agent inode for remote entry
4242  */
4243 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
4244                                                   struct osd_device *osd,
4245                                                   struct osd_object *pobj,
4246                                                   const struct lu_fid *fid,
4247                                                   __u32 type,
4248                                                   struct thandle *th)
4249 {
4250         struct osd_thread_info *info = osd_oti_get(env);
4251         struct inode *local;
4252         struct osd_thandle *oh;
4253         struct iattr iattr = {
4254                 .ia_valid = ATTR_UID | ATTR_GID |
4255                             ATTR_CTIME | ATTR_MTIME | ATTR_ATIME,
4256                 .ia_ctime.tv_nsec = UTIME_OMIT,
4257                 .ia_mtime.tv_nsec = UTIME_OMIT,
4258                 .ia_atime.tv_nsec = UTIME_OMIT,
4259                 .ia_uid = GLOBAL_ROOT_UID,
4260                 .ia_gid = GLOBAL_ROOT_GID,
4261         };
4262         int rc;
4263
4264         ENTRY;
4265
4266         LASSERT(th);
4267         oh = container_of(th, struct osd_thandle, ot_super);
4268         LASSERT(oh->ot_handle->h_transaction != NULL);
4269
4270         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode,
4271                                      type, &iattr);
4272         if (IS_ERR(local)) {
4273                 CERROR("%s: create local error %d\n", osd_name(osd),
4274                        (int)PTR_ERR(local));
4275                 RETURN(local);
4276         }
4277
4278         /*
4279          * restore i_gid in case S_ISGID is set, we will inherit S_ISGID and set
4280          * correct gid on remote file, not agent here
4281          */
4282         local->i_gid = current_fsgid();
4283         ldiskfs_set_inode_state(local, LDISKFS_STATE_LUSTRE_NOSCRUB);
4284
4285         /* e2fsck doesn't like empty symlinks.  Store remote FID as symlink.
4286          * That gives e2fsck something to look at and be happy, and allows
4287          * debugging if we need to determine where this symlink came from.
4288          */
4289         if (S_ISLNK(type)) {
4290                 BUILD_BUG_ON(LDISKFS_N_BLOCKS * 4 < FID_LEN + 1);
4291                 ldiskfs_clear_inode_flag(local, LDISKFS_INODE_EXTENTS);
4292                 rc = scnprintf((char *)LDISKFS_I(local)->i_data,
4293                                LDISKFS_N_BLOCKS * 4, DFID, PFID(fid));
4294
4295                 i_size_write(local, rc);
4296                 LDISKFS_I(local)->i_disksize = rc;
4297         }
4298         unlock_new_inode(local);
4299
4300         /* Agent inode should not have project ID */
4301 #ifdef  HAVE_PROJECT_QUOTA
4302         if (LDISKFS_I(pobj->oo_inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
4303             i_projid_read(pobj->oo_inode) != 0) {
4304                 rc = osd_transfer_project(local, 0, th);
4305                 if (rc) {
4306                         CERROR("%s: quota transfer failed:. Is project quota enforcement enabled on the ldiskfs filesystem? rc = %d\n",
4307                                osd_ino2name(local), rc);
4308                         RETURN(ERR_PTR(rc));
4309                 }
4310         }
4311 #endif
4312         /* Set special LMA flag for local agent inode */
4313         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
4314         if (rc != 0) {
4315                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
4316                        osd_name(osd), PFID(fid), rc);
4317                 RETURN(ERR_PTR(rc));
4318         }
4319
4320         if (!S_ISDIR(type))
4321                 RETURN(local);
4322
4323         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode, fid,
4324                                          lu_object_fid(&pobj->oo_dt.do_lu),
4325                                          oh);
4326         if (rc != 0) {
4327                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
4328                         osd_name(osd), PFID(fid), rc);
4329                 RETURN(ERR_PTR(rc));
4330         }
4331
4332         RETURN(local);
4333 }
4334
4335 /**
4336  * when direntry is deleted, we have to take care of possible agent inode
4337  * referenced by that. unfortunately we can't do this at that point:
4338  * iget() within a running transaction leads to deadlock and we better do
4339  * not call that every delete declaration to save performance. so we put
4340  * a potention agent inode on a list and process that once the transaction
4341  * is over. Notice it's not any worse in terms of real orphans as regular
4342  * object destroy doesn't put inodes on the on-disk orphan list. this should
4343  * be addressed separately
4344  */
4345 static int osd_schedule_agent_inode_removal(const struct lu_env *env,
4346                                             struct osd_thandle *oh,
4347                                             __u32 ino)
4348 {
4349         struct osd_device *osd = osd_dt_dev(oh->ot_super.th_dev);
4350         struct osd_obj_orphan *oor;
4351
4352         OBD_ALLOC_PTR(oor);
4353         if (oor == NULL)
4354                 return -ENOMEM;
4355
4356         oor->oor_ino = ino;
4357         oor->oor_env = (struct lu_env *)env;
4358         spin_lock(&osd->od_osfs_lock);
4359         list_add(&oor->oor_list, &osd->od_orphan_list);
4360         spin_unlock(&osd->od_osfs_lock);
4361
4362         oh->ot_remove_agents = 1;
4363
4364         return 0;
4365
4366 }
4367
4368 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
4369                                                 struct osd_device *osd)
4370 {
4371         struct osd_thread_info *info = osd_oti_get(env);
4372         struct osd_obj_orphan *oor, *tmp;
4373         struct osd_inode_id id;
4374         LIST_HEAD(list);
4375         struct inode *inode;
4376         struct lu_fid fid;
4377         handle_t *jh;
4378         __u32 ino;
4379
4380         spin_lock(&osd->od_osfs_lock);
4381         list_for_each_entry_safe(oor, tmp, &osd->od_orphan_list, oor_list) {
4382                 if (oor->oor_env == env)
4383                         list_move(&oor->oor_list, &list);
4384         }
4385         spin_unlock(&osd->od_osfs_lock);
4386
4387         list_for_each_entry_safe(oor, tmp, &list, oor_list) {
4388
4389                 ino = oor->oor_ino;
4390
4391                 list_del(&oor->oor_list);
4392                 OBD_FREE_PTR(oor);
4393
4394                 osd_id_gen(&id, ino, OSD_OII_NOGEN);
4395                 inode = osd_iget_fid(info, osd, &id, &fid);
4396                 if (IS_ERR(inode))
4397                         continue;
4398
4399                 if (!osd_remote_fid(env, osd, &fid)) {
4400                         iput(inode);
4401                         continue;
4402                 }
4403
4404                 jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC, 1);
4405                 clear_nlink(inode);
4406                 mark_inode_dirty(inode);
4407                 ldiskfs_journal_stop(jh);
4408                 iput(inode);
4409         }
4410
4411         return 0;
4412 }
4413
4414 /**
4415  * OSD layer object create function for OST objects (b=11826).
4416  *
4417  * The FID is inserted into inode xattr here.
4418  *
4419  * \retval   0, on success
4420  * \retval -ve, on error
4421  */
4422 static int osd_create(const struct lu_env *env, struct dt_object *dt,
4423                       struct lu_attr *attr, struct dt_allocation_hint *hint,
4424                       struct dt_object_format *dof, struct thandle *th)
4425 {
4426         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
4427         struct osd_object *obj = osd_dt_obj(dt);
4428         struct osd_thread_info *info = osd_oti_get(env);
4429         int result, on_ost = 0;
4430
4431         ENTRY;
4432
4433         if (dt_object_exists(dt))
4434                 RETURN(-EEXIST);
4435
4436         LINVRNT(osd_invariant(obj));
4437         LASSERT(!dt_object_remote(dt));
4438         LASSERT(osd_is_write_locked(env, obj));
4439         LASSERT(th != NULL);
4440
4441         if (unlikely(fid_is_acct(fid)))
4442                 /*
4443                  * Quota files can't be created from the kernel any more,
4444                  * 'tune2fs -O quota' will take care of creating them
4445                  */
4446                 RETURN(-EPERM);
4447
4448         result = __osd_create(info, obj, attr, hint, dof, th);
4449         if (result == 0) {
4450                 if (fid_is_idif(fid) &&
4451                     !osd_dev(dt->do_lu.lo_dev)->od_index_in_idif) {
4452                         struct lu_fid *tfid = &info->oti_fid;
4453                         struct ost_id *oi   = &info->oti_ostid;
4454
4455                         fid_to_ostid(fid, oi);
4456                         ostid_to_fid(tfid, oi, 0);
4457                         on_ost = 1;
4458                         result = osd_ea_fid_set(info, obj->oo_inode, tfid,
4459                                                 LMAC_FID_ON_OST, 0);
4460                 } else {
4461                         on_ost = fid_is_on_ost(info, osd_obj2dev(obj),
4462                                                fid, OI_CHECK_FLD);
4463                         result = osd_ea_fid_set(info, obj->oo_inode, fid,
4464                                                 on_ost ? LMAC_FID_ON_OST : 0,
4465                                                 0);
4466                 }
4467                 if (obj->oo_dt.do_body_ops == &osd_body_ops_new)
4468                         obj->oo_dt.do_body_ops = &osd_body_ops;
4469         }
4470
4471         if (!result && !CFS_FAIL_CHECK(OBD_FAIL_OSD_NO_OI_ENTRY)) {
4472                 struct inode *inode = obj->oo_inode;
4473
4474                 result = __osd_oi_insert(env, obj, fid, th);
4475                 if (result && inode) {
4476                         spin_lock(&obj->oo_guard);
4477                         clear_nlink(inode);
4478                         spin_unlock(&obj->oo_guard);
4479                         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4480                         ldiskfs_set_inode_state(inode,
4481                                                 LDISKFS_STATE_LUSTRE_DESTROY);
4482                         iput(inode);
4483                         obj->oo_inode = NULL;
4484                 }
4485         }
4486
4487         /*
4488          * a small optimization - dt_insert() isn't usually applied
4489          * to OST objects, so we don't need to cache OI mapping for
4490          * OST objects
4491          */
4492         if (result == 0 && on_ost == 0) {
4493                 struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
4494
4495                 result = osd_idc_find_and_init(env, osd, obj);
4496                 LASSERT(result == 0);
4497         }
4498
4499         LASSERT(ergo(result == 0,
4500                      dt_object_exists(dt) && !dt_object_remote(dt)));
4501         LINVRNT(osd_invariant(obj));
4502         RETURN(result);
4503 }
4504
4505 static int osd_declare_ref_add(const struct lu_env *env, struct dt_object *dt,
4506                                struct thandle *handle)
4507 {
4508         struct osd_thandle *oh;
4509         int rc;
4510
4511         /* it's possible that object doesn't exist yet */
4512         LASSERT(handle != NULL);
4513
4514         oh = container_of(handle, struct osd_thandle, ot_super);
4515         LASSERT(oh->ot_handle == NULL);
4516
4517         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
4518                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
4519
4520         rc = osd_idc_find_and_init(env, osd_dev(dt->do_lu.lo_dev),
4521                                    osd_dt_obj(dt));
4522
4523         return rc;
4524 }
4525
4526 /*
4527  * Concurrency: @dt is write locked.
4528  */
4529 static int osd_ref_add(const struct lu_env *env, struct dt_object *dt,
4530                        struct thandle *th)
4531 {
4532         struct osd_object *obj = osd_dt_obj(dt);
4533         struct inode *inode = obj->oo_inode;
4534         struct osd_thandle *oh;
4535         int rc = 0;
4536
4537         if (!dt_object_exists(dt) || obj->oo_destroyed)
4538                 return -ENOENT;
4539
4540         LINVRNT(osd_invariant(obj));
4541         LASSERT(!dt_object_remote(dt));
4542         LASSERT(osd_is_write_locked(env, obj));
4543         LASSERT(th != NULL);
4544
4545         oh = container_of(th, struct osd_thandle, ot_super);
4546         LASSERT(oh->ot_handle != NULL);
4547
4548         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
4549
4550         CDEBUG(D_INODE, DFID" increase nlink %d\n",
4551                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
4552         /*
4553          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
4554          * (65000) subdirectories by storing "1" in i_nlink if the link count
4555          * would otherwise overflow. Directory tranversal tools understand
4556          * that (st_nlink == 1) indicates that the filesystem dose not track
4557          * hard links count on the directory, and will not abort subdirectory
4558          * scanning early once (st_nlink - 2) subdirs have been found.
4559          *
4560          * This also has to properly handle the case of inodes with nlink == 0
4561          * in case they are being linked into the PENDING directory
4562          */
4563         spin_lock(&obj->oo_guard);
4564         if (unlikely(inode->i_nlink == 0))
4565                 /* inc_nlink from 0 may cause WARN_ON */
4566                 set_nlink(inode, 1);
4567         else {
4568                 osd_ldiskfs_inc_count(oh->ot_handle, inode);
4569                 if (!S_ISDIR(inode->i_mode))
4570                         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
4571         }
4572         spin_unlock(&obj->oo_guard);
4573
4574         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4575         LINVRNT(osd_invariant(obj));
4576
4577         osd_trans_exec_check(env, th, OSD_OT_REF_ADD);
4578
4579         return rc;
4580 }
4581
4582 static int osd_declare_ref_del(const struct lu_env *env, struct dt_object *dt,
4583                                struct thandle *handle)
4584 {
4585         struct osd_thandle *oh;
4586
4587         if (!dt_object_exists(dt))
4588                 return -ENOENT;
4589
4590         LASSERT(!dt_object_remote(dt));
4591         LASSERT(handle != NULL);
4592
4593         oh = container_of(handle, struct osd_thandle, ot_super);
4594         LASSERT(oh->ot_handle == NULL);
4595
4596         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
4597                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
4598
4599         return 0;
4600 }
4601
4602 /*
4603  * Concurrency: @dt is write locked.
4604  */
4605 static int osd_ref_del(const struct lu_env *env, struct dt_object *dt,
4606                        struct thandle *th)
4607 {
4608         struct osd_object *obj = osd_dt_obj(dt);
4609         struct inode *inode = obj->oo_inode;
4610         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
4611         struct osd_thandle *oh;
4612
4613         if (!dt_object_exists(dt))
4614                 return -ENOENT;
4615
4616         LINVRNT(osd_invariant(obj));
4617         LASSERT(!dt_object_remote(dt));
4618         LASSERT(osd_is_write_locked(env, obj));
4619         LASSERT(th != NULL);
4620
4621         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_REF_DEL))
4622                 return -EIO;
4623
4624         oh = container_of(th, struct osd_thandle, ot_super);
4625         LASSERT(oh->ot_handle != NULL);
4626
4627         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
4628
4629         spin_lock(&obj->oo_guard);
4630         /*
4631          * That can be result of upgrade from old Lustre version and
4632          * applied only to local files.  Just skip this ref_del call.
4633          * ext4_unlink() only treats this as a warning, don't LASSERT here.
4634          */
4635         if (inode->i_nlink == 0) {
4636                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
4637                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
4638                              ", maybe an upgraded file? (LU-3915)\n",
4639                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
4640                 spin_unlock(&obj->oo_guard);
4641                 return 0;
4642         }
4643
4644         CDEBUG(D_INODE, DFID" decrease nlink %d\n",
4645                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
4646
4647         osd_ldiskfs_dec_count(oh->ot_handle, inode);
4648         spin_unlock(&obj->oo_guard);
4649
4650         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
4651         LINVRNT(osd_invariant(obj));
4652
4653         osd_trans_exec_check(env, th, OSD_OT_REF_DEL);
4654
4655         return 0;
4656 }
4657
4658 /*
4659  * Concurrency: @dt is read locked.
4660  */
4661 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
4662                          struct lu_buf *buf, const char *name)
4663 {
4664         struct osd_object      *obj    = osd_dt_obj(dt);
4665         struct inode           *inode  = obj->oo_inode;
4666         struct osd_thread_info *info   = osd_oti_get(env);
4667         struct dentry          *dentry = &info->oti_obj_dentry;
4668         bool cache_xattr = false;
4669         int rc;
4670
4671         LASSERT(buf);
4672
4673         /* version get is not real XATTR but uses xattr API */
4674         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4675                 dt_obj_version_t *ver = buf->lb_buf;
4676
4677                 /*
4678                  * for version we are just using xattr API but change inode
4679                  * field instead
4680                  */
4681                 if (buf->lb_len == 0)
4682                         return sizeof(dt_obj_version_t);
4683
4684                 if (buf->lb_len < sizeof(dt_obj_version_t))
4685                         return -ERANGE;
4686
4687                 CDEBUG(D_INODE, "Get version %#llx for inode %lu\n",
4688                        LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4689
4690                 *ver = LDISKFS_I(inode)->i_fs_version;
4691
4692                 return sizeof(dt_obj_version_t);
4693         }
4694
4695         if (!dt_object_exists(dt))
4696                 return -ENOENT;
4697
4698         LASSERT(!dt_object_remote(dt));
4699         LASSERT(inode->i_op != NULL);
4700 #ifdef HAVE_IOP_XATTR
4701         LASSERT(inode->i_op->getxattr != NULL);
4702 #endif
4703
4704         if (strcmp(name, XATTR_NAME_LOV) == 0 ||
4705             strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0)
4706                 cache_xattr = true;
4707
4708         if (cache_xattr) {
4709                 rc = osd_oxc_get(obj, name, buf);
4710                 if (rc != -ENOENT)
4711                         return rc;
4712         }
4713
4714         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
4715                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4716                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4717                 struct filter_fid *ff;
4718                 struct ost_layout *ol;
4719
4720                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4721                 if (rc)
4722                         return rc;
4723
4724                 LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
4725
4726                 rc = sizeof(*ff);
4727                 if (buf->lb_len == 0 || !buf->lb_buf)
4728                         return rc;
4729
4730                 if (buf->lb_len < rc)
4731                         return -ERANGE;
4732
4733                 ff = buf->lb_buf;
4734                 ol = &ff->ff_layout;
4735                 ol->ol_stripe_count = cpu_to_le32(loa->loa_parent_fid.f_ver >>
4736                                                   PFID_STRIPE_IDX_BITS);
4737                 ol->ol_stripe_size = cpu_to_le32(loa->loa_stripe_size);
4738                 loa->loa_parent_fid.f_ver &= PFID_STRIPE_COUNT_MASK;
4739                 fid_cpu_to_le(&ff->ff_parent, &loa->loa_parent_fid);
4740                 if (lma->lma_compat & LMAC_COMP_INFO) {
4741                         ol->ol_comp_start = cpu_to_le64(loa->loa_comp_start);
4742                         ol->ol_comp_end = cpu_to_le64(loa->loa_comp_end);
4743                         ol->ol_comp_id = cpu_to_le32(loa->loa_comp_id);
4744                 } else {
4745                         ol->ol_comp_start = 0;
4746                         ol->ol_comp_end = 0;
4747                         ol->ol_comp_id = 0;
4748                 }
4749         } else {
4750                 /* Get enc context xattr directly from ldiskfs instead of going
4751                  * through the VFS, as there is no xattr handler for
4752                  * "encryption.".
4753                  */
4754                 if (strcmp(name, LL_XATTR_NAME_ENCRYPTION_CONTEXT) == 0)
4755                         rc = ldiskfs_xattr_get(inode,
4756                                           LDISKFS_XATTR_INDEX_ENCRYPTION,
4757                                           LDISKFS_XATTR_NAME_ENCRYPTION_CONTEXT,
4758                                           buf->lb_buf, buf->lb_len);
4759                 else
4760                         rc = __osd_xattr_get(inode, dentry, name,
4761                                              buf->lb_buf, buf->lb_len);
4762         }
4763
4764         if (cache_xattr) {
4765                 if (rc == -ENOENT || rc == -ENODATA)
4766                         osd_oxc_add(obj, name, NULL, 0);
4767                 else if (rc > 0 && buf->lb_buf != NULL)
4768                         osd_oxc_add(obj, name, buf->lb_buf, rc);
4769         }
4770
4771         return rc;
4772 }
4773
4774 static int osd_declare_xattr_set(const struct lu_env *env,
4775                                  struct dt_object *dt,
4776                                  const struct lu_buf *buf, const char *name,
4777                                  int fl, struct thandle *handle)
4778 {
4779         struct osd_thandle *oh;
4780         int credits = 0;
4781         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
4782
4783         LASSERT(handle != NULL);
4784
4785         oh = container_of(handle, struct osd_thandle, ot_super);
4786         LASSERT(oh->ot_handle == NULL);
4787
4788         if (strcmp(name, XATTR_NAME_LMA) == 0) {
4789                 /*
4790                  * For non-upgrading case, the LMA is set first and
4791                  * usually fit inode. But for upgrade case, the LMA
4792                  * may be in another separated EA block.
4793                  */
4794                 if (dt_object_exists(dt)) {
4795                         if (fl == LU_XATTR_REPLACE)
4796                                 credits = 1;
4797                         else
4798                                 goto upgrade;
4799                 }
4800         } else if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4801                 credits = 1;
4802         } else if (strcmp(name, XATTR_NAME_FID) == 0) {
4803                 /* We may need to delete the old PFID EA. */
4804                 credits = LDISKFS_MAXQUOTAS_DEL_BLOCKS(sb);
4805                 if (fl == LU_XATTR_REPLACE)
4806                         credits += 1;
4807                 else
4808                         goto upgrade;
4809         } else {
4810                 /*
4811                  * If some name entry resides on remote MDT, then will create
4812                  * agent entry under remote parent. On the other hand, if the
4813                  * remote entry will be removed, then related agent entry may
4814                  * need to be removed from the remote parent. So there may be
4815                  * kinds of cases, let's declare enough credits. The credits
4816                  * for create agent entry is enough for remove case.
4817                  */
4818                 if (strcmp(name, XATTR_NAME_LINK) == 0) {
4819                         credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
4820                         if (dt_object_exists(dt))
4821                                 credits += 1; /* For updating LMA */
4822                 }
4823
4824 upgrade:
4825                 credits += osd_dto_credits_noquota[DTO_XATTR_SET];
4826
4827                 if (buf != NULL) {
4828                         ssize_t buflen;
4829
4830                         if (buf->lb_buf == NULL && dt_object_exists(dt)) {
4831                                 /*
4832                                  * learn xattr size from osd_xattr_get if
4833                                  * attribute has not been read yet
4834                                  */
4835                                 buflen = __osd_xattr_get(
4836                                     osd_dt_obj(dt)->oo_inode,
4837                                     &osd_oti_get(env)->oti_obj_dentry,
4838                                     name, NULL, 0);
4839                                 if (buflen < 0)
4840                                         buflen = 0;
4841                         } else {
4842                                 buflen = buf->lb_len;
4843                         }
4844
4845                         if (buflen > sb->s_blocksize) {
4846                                 credits += osd_calc_bkmap_credits(
4847                                     sb, NULL, 0, -1,
4848                                     (buflen + sb->s_blocksize - 1) >>
4849                                     sb->s_blocksize_bits);
4850                         }
4851                 }
4852                 /*
4853                  * xattr set may involve inode quota change, reserve credits for
4854                  * dquot_initialize()
4855                  */
4856                 credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4857         }
4858
4859         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET, credits);
4860
4861         return 0;
4862 }
4863
4864 static int osd_xattr_set_pfid(const struct lu_env *env, struct osd_object *obj,
4865                               const struct lu_buf *buf, int fl,
4866                               struct thandle *handle)
4867 {
4868         struct osd_thread_info *info = osd_oti_get(env);
4869         struct dentry *dentry = &info->oti_obj_dentry;
4870         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4871         struct lustre_mdt_attrs *lma = &loa->loa_lma;
4872         struct inode *inode = obj->oo_inode;
4873         struct filter_fid *ff = buf->lb_buf;
4874         struct ost_layout *ol = &ff->ff_layout;
4875         int flags = XATTR_REPLACE;
4876         int rc;
4877
4878         ENTRY;
4879
4880         if (buf->lb_len != sizeof(*ff) && buf->lb_len != sizeof(struct lu_fid))
4881                 RETURN(-EINVAL);
4882
4883         rc = osd_get_lma(info, inode, dentry, loa);
4884         if (rc == -ENODATA) {
4885                 /* Usually for upgarding from old device */
4886                 lustre_loa_init(loa, lu_object_fid(&obj->oo_dt.do_lu),
4887                                 LMAC_FID_ON_OST, 0);
4888                 flags = XATTR_CREATE;
4889         } else if (rc) {
4890                 RETURN(rc);
4891         }
4892
4893         if (!rc && lma->lma_compat & LMAC_STRIPE_INFO) {
4894                 if ((fl & LU_XATTR_CREATE) && !(fl & LU_XATTR_REPLACE))
4895                         RETURN(-EEXIST);
4896
4897                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256) {
4898                         /* Separate PFID EA from LMA */
4899                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4900                         lustre_lma_swab(lma);
4901                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4902                                              sizeof(*lma), XATTR_REPLACE);
4903                         if (!rc) {
4904                                 obj->oo_pfid_in_lma = 0;
4905                                 rc = LU_XATTR_CREATE;
4906                         }
4907
4908                         RETURN(rc);
4909                 }
4910         } else {
4911                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256)
4912                         RETURN(fl);
4913
4914                 /*
4915                  * Old client does not send stripe information,
4916                  * then store the PFID EA on disk separatedly.
4917                  */
4918                 if (unlikely(buf->lb_len == sizeof(struct lu_fid) ||
4919                              ol->ol_stripe_size == 0))
4920                         RETURN(fl);
4921
4922                 /* Remove old PFID EA entry firstly. */
4923                 dquot_initialize(inode);
4924                 rc = ll_vfs_removexattr(dentry, inode, XATTR_NAME_FID);
4925                 if (rc == -ENODATA) {
4926                         /* XATTR_NAME_FID is already absent */
4927                         rc = 0;
4928                 } else if (rc) {
4929                         RETURN(rc);
4930                 }
4931         }
4932
4933         fid_le_to_cpu(&loa->loa_parent_fid, &ff->ff_parent);
4934         if (likely(ol->ol_stripe_size != 0)) {
4935                 loa->loa_parent_fid.f_ver |= le32_to_cpu(ol->ol_stripe_count) <<
4936                                              PFID_STRIPE_IDX_BITS;
4937                 loa->loa_stripe_size = le32_to_cpu(ol->ol_stripe_size);
4938                 lma->lma_compat |= LMAC_STRIPE_INFO;
4939                 if (ol->ol_comp_id != 0) {
4940                         loa->loa_comp_id = le32_to_cpu(ol->ol_comp_id);
4941                         loa->loa_comp_start = le64_to_cpu(ol->ol_comp_start);
4942                         loa->loa_comp_end = le64_to_cpu(ol->ol_comp_end);
4943                         lma->lma_compat |= LMAC_COMP_INFO;
4944                 }
4945         }
4946
4947         lustre_loa_swab(loa, false);
4948
4949         /* Store the PFID EA inside LMA. */
4950         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa, sizeof(*loa),
4951                              flags);
4952         if (!rc)
4953                 obj->oo_pfid_in_lma = 1;
4954
4955         RETURN(rc);
4956 }
4957
4958 /*
4959  * In DNE environment, the object (in spite of regular file or directory)
4960  * and its name entry may reside on different MDTs. Under such case, we will
4961  * create an agent entry on the MDT where the object resides. The agent entry
4962  * references the object locally, that makes the object to be visible to the
4963  * userspace when mounted as 'ldiskfs' directly. Then the userspace tools,
4964  * such as 'tar' can handle the object properly.
4965  *
4966  * We handle the agent entry during set linkEA that is the common interface
4967  * for both regular file and directroy, can handle kinds of cases, such as
4968  * create/link/unlink/rename, and so on.
4969  *
4970  * NOTE: we can NOT do that when ea_{insert,delete} that is only for directory.
4971  *
4972  * XXX: There are two known issues:
4973  * 1. For one object, we will create at most one agent entry even if there
4974  *    may be more than one cross-MDTs hard links on the object. So the local
4975  *    e2fsck may claim that the object's nlink is larger than the name entries
4976  *    that reference such inode. And in further, the e2fsck will fix the nlink
4977  *    attribute to match the local references. Then it will cause the object's
4978  *    nlink attribute to be inconsistent with the global references. it is bad
4979  *    but not fatal. The ref_del() can handle the zero-referenced case. On the
4980  *    other hand, the global namespace LFSCK can repair the object's attribute
4981  *    according to the linkEA.
4982  * 2. There may be too many hard links on the object as to its linkEA overflow,
4983  *    then the linkEA entry for cross-MDTs reference may be discarded. If such
4984  *    case happened, then at this point, we do not know whether there are some
4985  *    cross-MDTs reference. But there are local references, it guarantees that
4986  *    object is visible to userspace when mounted as 'ldiskfs'. That is enough.
4987  */
4988 static int osd_xattr_handle_linkea(const struct lu_env *env,
4989                                    struct osd_device *osd,
4990                                    struct osd_object *obj,
4991                                    const struct lu_buf *buf,
4992                                    struct thandle *handle)
4993 {
4994         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
4995         struct lu_fid *tfid = &osd_oti_get(env)->oti_fid3;
4996         struct linkea_data ldata = { .ld_buf = (struct lu_buf *)buf };
4997         struct lu_name tmpname;
4998         struct osd_thandle *oh;
4999         int rc;
5000         bool remote = false;
5001
5002         ENTRY;
5003
5004         oh = container_of(handle, struct osd_thandle, ot_super);
5005         LASSERT(oh->ot_handle != NULL);
5006
5007         rc = linkea_init_with_rec(&ldata);
5008         if (!rc) {
5009                 linkea_first_entry(&ldata);
5010                 while (ldata.ld_lee != NULL && !remote) {
5011                         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen,
5012                                             &tmpname, tfid);
5013                         if (osd_remote_fid(env, osd, tfid) > 0)
5014                                 remote = true;
5015                         else
5016                                 linkea_next_entry(&ldata);
5017                 }
5018         } else if (rc == -ENODATA) {
5019                 rc = 0;
5020         } else {
5021                 RETURN(rc);
5022         }
5023
5024         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu) && !remote) {
5025                 rc = osd_delete_from_remote_parent(env, osd, obj, oh, false);
5026                 if (rc)
5027                         CERROR("%s: failed to remove agent entry for "DFID
5028                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
5029         } else if (!lu_object_has_agent_entry(&obj->oo_dt.do_lu) && remote) {
5030                 rc = osd_add_to_remote_parent(env, osd, obj, oh);
5031                 if (rc)
5032                         CERROR("%s: failed to create agent entry for "DFID
5033                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
5034         }
5035
5036         RETURN(rc);
5037 }
5038
5039 /*
5040  * Concurrency: @dt is write locked.
5041  */
5042 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
5043                          const struct lu_buf *buf, const char *name, int fl,
5044                          struct thandle *handle)
5045 {
5046         struct osd_object *obj = osd_dt_obj(dt);
5047         struct osd_device *osd = osd_obj2dev(obj);
5048         struct inode *inode = obj->oo_inode;
5049         struct osd_thread_info *info = osd_oti_get(env);
5050         int fs_flags = 0;
5051         int len;
5052         int rc;
5053
5054         ENTRY;
5055
5056         LASSERT(handle);
5057         LASSERT(buf);
5058
5059         /* version set is not real XATTR */
5060         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
5061                 dt_obj_version_t *version = buf->lb_buf;
5062
5063                 /*
5064                  * for version we are just using xattr API but change inode
5065                  * field instead
5066                  */
5067                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
5068
5069                 CDEBUG(D_INODE,
5070                        DFID" set version %#llx (old %#llx) for inode %lu\n",
5071                        PFID(lu_object_fid(&dt->do_lu)), *version,
5072                        LDISKFS_I(inode)->i_fs_version, inode->i_ino);
5073
5074                 LDISKFS_I(inode)->i_fs_version = *version;
5075                 /*
5076                  * Version is set after all inode operations are finished,
5077                  * so we should mark it dirty here
5078                  */
5079                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
5080
5081                 RETURN(0);
5082         }
5083
5084         CDEBUG(D_INODE, DFID" set xattr '%s' with size %zu\n",
5085                PFID(lu_object_fid(&dt->do_lu)), name, buf->lb_len);
5086
5087         len = buf->lb_len;
5088         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
5089
5090         /*
5091          * For the OST device with 256 bytes inode size by default,
5092          * the PFID EA will be stored together with LMA EA to avoid
5093          * performance trouble. Otherwise the PFID EA can be stored
5094          * independently. LU-8998
5095          */
5096         if (strcmp(name, XATTR_NAME_FID) == 0 && osd->od_is_ost &&
5097             (LDISKFS_INODE_SIZE(inode->i_sb) <= 256 || obj->oo_pfid_in_lma)) {
5098                 LASSERT(buf->lb_buf);
5099
5100                 fl = osd_xattr_set_pfid(env, obj, buf, fl, handle);
5101                 if (fl <= 0)
5102                         RETURN(fl);
5103         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
5104                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
5105                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
5106
5107                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
5108                 if (rc)
5109                         RETURN(rc);
5110
5111                 lma->lma_incompat |= LMAI_STRIPED;
5112                 lustre_lma_swab(lma);
5113                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
5114                                      sizeof(*lma), XATTR_REPLACE);
5115                 if (rc != 0)
5116                         RETURN(rc);
5117         } else if (strcmp(name, XATTR_NAME_LINK) == 0) {
5118                 LASSERT(!osd->od_is_ost);
5119
5120                 rc = osd_xattr_handle_linkea(env, osd, obj, buf, handle);
5121                 if (rc)
5122                         RETURN(rc);
5123         }
5124
5125         if (fl & LU_XATTR_REPLACE)
5126                 fs_flags |= XATTR_REPLACE;
5127
5128         if (fl & LU_XATTR_CREATE)
5129                 fs_flags |= XATTR_CREATE;
5130
5131         if (strcmp(name, LL_XATTR_NAME_ENCRYPTION_CONTEXT) == 0) {
5132                 /* Set enc context xattr directly in ldiskfs instead of going
5133                  * through the VFS, as there is no xattr handler for
5134                  * "encryption.".
5135                  */
5136                 struct osd_thandle *oth = container_of(handle,
5137                                                        struct osd_thandle,
5138                                                        ot_super);
5139
5140                 if (!oth->ot_handle)
5141                         /* this should be already part of a transaction */
5142                         RETURN(-EPROTO);
5143
5144                 rc = ldiskfs_xattr_set_handle(oth->ot_handle, inode,
5145                                           LDISKFS_XATTR_INDEX_ENCRYPTION,
5146                                           LDISKFS_XATTR_NAME_ENCRYPTION_CONTEXT,
5147                                           buf->lb_buf, len, fs_flags);
5148         } else {
5149                 rc = __osd_xattr_set(info, inode, name,
5150                                      buf->lb_buf, len, fs_flags);
5151         }
5152         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
5153
5154         if (rc == 0 &&
5155             (strcmp(name, XATTR_NAME_LOV) == 0 ||
5156              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
5157                 osd_oxc_add(obj, name, buf->lb_buf, buf->lb_len);
5158
5159         return rc;
5160 }
5161
5162 /*
5163  * Concurrency: @dt is read locked.
5164  */
5165 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
5166                           const struct lu_buf *buf)
5167 {
5168         struct osd_object *obj = osd_dt_obj(dt);
5169         struct osd_device *dev = osd_obj2dev(obj);
5170         struct inode *inode = obj->oo_inode;
5171         struct osd_thread_info *info = osd_oti_get(env);
5172         struct dentry *dentry = &info->oti_obj_dentry;
5173         int rc;
5174
5175         if (!dt_object_exists(dt))
5176                 return -ENOENT;
5177
5178         LASSERT(!dt_object_remote(dt));
5179         LASSERT(inode->i_op != NULL);
5180         LASSERT(inode->i_op->listxattr != NULL);
5181
5182         dentry->d_inode = inode;
5183         dentry->d_sb = inode->i_sb;
5184         rc = inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
5185
5186         if (rc < 0 || buf->lb_buf == NULL)
5187                 return rc;
5188
5189         /* Hide virtual project ID xattr from list if disabled */
5190         if (!dev->od_enable_projid_xattr) {
5191                 char *end = (char *)buf->lb_buf + rc;
5192                 char *p = buf->lb_buf;
5193
5194                 while (p < end) {
5195                         char *next = p + strlen(p) + 1;
5196
5197                         if (strcmp(p, XATTR_NAME_PROJID) == 0) {
5198                                 if (end - next > 0)
5199                                         memmove(p, next, end - next);
5200                                 rc -= next - p;
5201                                 break;
5202                         }
5203
5204                         p = next;
5205                 }
5206         }
5207
5208         return rc;
5209 }
5210
5211 static int osd_declare_xattr_del(const struct lu_env *env,
5212                                  struct dt_object *dt, const char *name,
5213                                  struct thandle *handle)
5214 {
5215         struct osd_thandle *oh;
5216         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
5217
5218         LASSERT(!dt_object_remote(dt));
5219         LASSERT(handle != NULL);
5220
5221         oh = container_of(handle, struct osd_thandle, ot_super);
5222         LASSERT(oh->ot_handle == NULL);
5223
5224         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
5225                              osd_dto_credits_noquota[DTO_XATTR_SET]);
5226         /*
5227          * xattr del may involve inode quota change, reserve credits for
5228          * dquot_initialize()
5229          */
5230         oh->ot_credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
5231
5232         return 0;
5233 }
5234
5235 /*
5236  * Concurrency: @dt is write locked.
5237  */
5238 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
5239                          const char *name, struct thandle *handle)
5240 {
5241         struct osd_object *obj = osd_dt_obj(dt);
5242         struct inode *inode = obj->oo_inode;
5243         struct osd_thread_info *info = osd_oti_get(env);
5244         struct dentry *dentry = &info->oti_obj_dentry;
5245         int rc;
5246
5247         if (!dt_object_exists(dt))
5248                 return -ENOENT;
5249
5250         LASSERT(!dt_object_remote(dt));
5251         LASSERT(inode->i_op != NULL);
5252         LASSERT(handle != NULL);
5253 #ifdef HAVE_IOP_XATTR
5254         LASSERT(inode->i_op->removexattr != NULL);
5255 #endif
5256
5257         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
5258
5259         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
5260                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
5261
5262                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
5263                                  &info->oti_ost_attrs);
5264                 if (!rc) {
5265                         LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
5266
5267                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
5268                         lustre_lma_swab(lma);
5269                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
5270                                              sizeof(*lma), XATTR_REPLACE);
5271                         if (!rc)
5272                                 obj->oo_pfid_in_lma = 0;
5273                 }
5274         } else {
5275                 dquot_initialize(inode);
5276                 dentry->d_inode = inode;
5277                 dentry->d_sb = inode->i_sb;
5278                 rc = ll_vfs_removexattr(dentry, inode, name);
5279         }
5280
5281         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
5282
5283         if (rc == 0 &&
5284             (strcmp(name, XATTR_NAME_LOV) == 0 ||
5285              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
5286                 osd_oxc_del(obj, name);
5287
5288         return rc;
5289 }
5290
5291 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt,
5292                            __u64 start, __u64 end)
5293 {
5294         struct osd_object *obj = osd_dt_obj(dt);
5295         struct osd_device *dev = osd_obj2dev(obj);
5296         struct inode *inode = obj->oo_inode;
5297         struct file *file;
5298         int rc;
5299
5300         ENTRY;
5301         file = alloc_file_pseudo(inode, dev->od_mnt, "/", O_NOATIME,
5302                                  inode->i_fop);
5303         if (IS_ERR(file))
5304                 RETURN(PTR_ERR(file));
5305
5306         file->f_mode |= FMODE_64BITHASH;
5307         rc = vfs_fsync_range(file, start, end, 0);
5308         ihold(inode);
5309         fput(file);
5310
5311         RETURN(rc);
5312 }
5313
5314 static int osd_invalidate(const struct lu_env *env, struct dt_object *dt)
5315 {
5316         return 0;
5317 }
5318
5319 static bool osd_check_stale(struct dt_object *dt)
5320 {
5321         return false;
5322 }
5323 /*
5324  * Index operations.
5325  */
5326
5327 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
5328                                const struct dt_index_features *feat)
5329 {
5330         struct iam_descr *descr;
5331
5332         if (osd_object_is_root(o))
5333                 return feat == &dt_directory_features;
5334
5335         LASSERT(o->oo_dir != NULL);
5336
5337         descr = o->oo_dir->od_container.ic_descr;
5338         if (feat == &dt_directory_features) {
5339                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
5340                         return 1;
5341                 else
5342                         return 0;
5343         } else {
5344                 return feat->dif_keysize_min <= descr->id_key_size &&
5345                        descr->id_key_size <= feat->dif_keysize_max &&
5346                        feat->dif_recsize_min <= descr->id_rec_size &&
5347                        descr->id_rec_size <= feat->dif_recsize_max &&
5348                        !(feat->dif_flags & (DT_IND_VARKEY |
5349                                             DT_IND_VARREC | DT_IND_NONUNQ)) &&
5350                        ergo(feat->dif_flags & DT_IND_UPDATE,
5351                             1 /* XXX check that object (and fs) is writable */);
5352         }
5353 }
5354
5355 static int osd_iam_container_init(const struct lu_env *env,
5356                                   struct osd_object *obj,
5357                                   struct osd_directory *dir)
5358 {
5359         struct iam_container *bag = &dir->od_container;
5360         int result;
5361
5362         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
5363         if (result != 0)
5364                 return result;
5365
5366         result = iam_container_setup(bag);
5367         if (result == 0)
5368                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
5369         else
5370                 iam_container_fini(bag);
5371
5372         return result;
5373 }
5374
5375
5376 /*
5377  * Concurrency: no external locking is necessary.
5378  */
5379 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
5380                          const struct dt_index_features *feat)
5381 {
5382         int result;
5383         int skip_iam = 0;
5384         struct osd_object *obj = osd_dt_obj(dt);
5385
5386         LINVRNT(osd_invariant(obj));
5387
5388         if (osd_object_is_root(obj)) {
5389                 dt->do_index_ops = &osd_index_ea_ops;
5390                 result = 0;
5391         } else if (feat == &dt_directory_features) {
5392                 dt->do_index_ops = &osd_index_ea_ops;
5393                 if (obj->oo_inode == NULL || S_ISDIR(obj->oo_inode->i_mode))
5394                         result = 0;
5395                 else
5396                         result = -ENOTDIR;
5397                 skip_iam = 1;
5398         } else if (unlikely(feat == &dt_otable_features)) {
5399                 dt->do_index_ops = &osd_otable_ops;
5400                 return 0;
5401         } else if (unlikely(feat == &dt_acct_features)) {
5402                 dt->do_index_ops = &osd_acct_index_ops;
5403                 result = 0;
5404                 skip_iam = 1;
5405         } else if (!osd_has_index(obj)) {
5406                 struct osd_directory *dir;
5407                 struct osd_device *osd = osd_obj2dev(obj);
5408                 const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
5409
5410                 OBD_ALLOC_PTR(dir);
5411                 if (dir) {
5412
5413                         spin_lock(&obj->oo_guard);
5414                         if (obj->oo_dir == NULL)
5415                                 obj->oo_dir = dir;
5416                         else
5417                                 /*
5418                                  * Concurrent thread allocated container data.
5419                                  */
5420                                 OBD_FREE_PTR(dir);
5421                         spin_unlock(&obj->oo_guard);
5422                         /*
5423                          * Now, that we have container data, serialize its
5424                          * initialization.
5425                          */
5426                         down_write(&obj->oo_ext_idx_sem);
5427                         /*
5428                          * recheck under lock.
5429                          */
5430
5431                         if (osd_has_index(obj)) {
5432                                 result = 0;
5433                                 goto unlock;
5434                         }
5435
5436                         result = osd_iam_container_init(env, obj, obj->oo_dir);
5437                         if (result || feat == &dt_lfsck_namespace_features ||
5438                             feat == &dt_lfsck_layout_orphan_features ||
5439                             feat == &dt_lfsck_layout_dangling_features)
5440                                 goto unlock;
5441
5442                         result = osd_index_register(osd, fid,
5443                                                     feat->dif_keysize_max,
5444                                                     feat->dif_recsize_max);
5445                         if (result < 0)
5446                                 CWARN("%s: failed to register index "
5447                                       DFID": rc = %d\n",
5448                                       osd_name(osd), PFID(fid), result);
5449                         else if (result > 0)
5450                                 result = 0;
5451                         else
5452                                 CDEBUG(D_LFSCK, "%s: index object "DFID
5453                                        " (%d/%d) registered\n",
5454                                        osd_name(osd), PFID(fid),
5455                                        (int)feat->dif_keysize_max,
5456                                        (int)feat->dif_recsize_max);
5457
5458 unlock:
5459                         up_write(&obj->oo_ext_idx_sem);
5460                 } else {
5461                         result = -ENOMEM;
5462                 }
5463         } else {
5464                 result = 0;
5465         }
5466
5467         if (result == 0 && skip_iam == 0) {
5468                 if (!osd_iam_index_probe(env, obj, feat))
5469                         result = -ENOTDIR;
5470         }
5471         LINVRNT(osd_invariant(obj));
5472
5473         return result;
5474 }
5475
5476 static int osd_otable_it_attr_get(const struct lu_env *env,
5477                                  struct dt_object *dt,
5478                                  struct lu_attr *attr)
5479 {
5480         attr->la_valid = 0;
5481         return 0;
5482 }
5483
5484 static const struct dt_object_operations osd_obj_ops = {
5485         .do_read_lock           = osd_read_lock,
5486         .do_write_lock          = osd_write_lock,
5487         .do_read_unlock         = osd_read_unlock,
5488         .do_write_unlock        = osd_write_unlock,
5489         .do_write_locked        = osd_write_locked,
5490         .do_attr_get            = osd_attr_get,
5491         .do_declare_attr_set    = osd_declare_attr_set,
5492         .do_attr_set            = osd_attr_set,
5493         .do_ah_init             = osd_ah_init,
5494         .do_declare_create      = osd_declare_create,
5495         .do_create              = osd_create,
5496         .do_declare_destroy     = osd_declare_destroy,
5497         .do_destroy             = osd_destroy,
5498         .do_index_try           = osd_index_try,
5499         .do_declare_ref_add     = osd_declare_ref_add,
5500         .do_ref_add             = osd_ref_add,
5501         .do_declare_ref_del     = osd_declare_ref_del,
5502         .do_ref_del             = osd_ref_del,
5503         .do_xattr_get           = osd_xattr_get,
5504         .do_declare_xattr_set   = osd_declare_xattr_set,
5505         .do_xattr_set           = osd_xattr_set,
5506         .do_declare_xattr_del   = osd_declare_xattr_del,
5507         .do_xattr_del           = osd_xattr_del,
5508         .do_xattr_list          = osd_xattr_list,
5509         .do_object_sync         = osd_object_sync,
5510         .do_invalidate          = osd_invalidate,
5511         .do_check_stale         = osd_check_stale,
5512 };
5513
5514 static const struct dt_object_operations osd_obj_otable_it_ops = {
5515         .do_attr_get    = osd_otable_it_attr_get,
5516         .do_index_try   = osd_index_try,
5517 };
5518
5519 static int osd_index_declare_iam_delete(const struct lu_env *env,
5520                                         struct dt_object *dt,
5521                                         const struct dt_key *key,
5522                                         struct thandle *handle)
5523 {
5524         struct osd_thandle *oh;
5525
5526         oh = container_of(handle, struct osd_thandle, ot_super);
5527         LASSERT(oh->ot_handle == NULL);
5528
5529         /* Recycle  may cause additional three blocks to be changed. */
5530         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
5531                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
5532
5533         return 0;
5534 }
5535
5536 /**
5537  *      delete a (key, value) pair from index \a dt specified by \a key
5538  *
5539  *      \param  dt      osd index object
5540  *      \param  key     key for index
5541  *      \param  rec     record reference
5542  *      \param  handle  transaction handler
5543  *
5544  *      \retval  0  success
5545  *      \retval -ve   failure
5546  */
5547 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
5548                                 const struct dt_key *key,
5549                                 struct thandle *handle)
5550 {
5551         struct osd_thread_info *oti = osd_oti_get(env);
5552         struct osd_object *obj = osd_dt_obj(dt);
5553         struct osd_thandle *oh;
5554         struct iam_path_descr *ipd;
5555         struct iam_container *bag = &obj->oo_dir->od_container;
5556         int rc;
5557
5558         ENTRY;
5559
5560         if (!dt_object_exists(dt))
5561                 RETURN(-ENOENT);
5562
5563         LINVRNT(osd_invariant(obj));
5564         LASSERT(!dt_object_remote(dt));
5565         LASSERT(bag->ic_object == obj->oo_inode);
5566         LASSERT(handle != NULL);
5567
5568         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
5569
5570         ipd = osd_idx_ipd_get(env, bag);
5571         if (unlikely(ipd == NULL))
5572                 RETURN(-ENOMEM);
5573
5574         oh = container_of(handle, struct osd_thandle, ot_super);
5575         LASSERT(oh->ot_handle != NULL);
5576         LASSERT(oh->ot_handle->h_transaction != NULL);
5577
5578         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5579                 /* swab quota uid/gid provided by caller */
5580                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5581                 key = (const struct dt_key *)&oti->oti_quota_id;
5582         }
5583
5584         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
5585         osd_ipd_put(env, bag, ipd);
5586         LINVRNT(osd_invariant(obj));
5587         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
5588         RETURN(rc);
5589 }
5590
5591 static int osd_index_declare_ea_delete(const struct lu_env *env,
5592                                        struct dt_object *dt,
5593                                        const struct dt_key *key,
5594                                        struct thandle *handle)
5595 {
5596         struct osd_thandle *oh;
5597         struct inode *inode;
5598         int rc, credits;
5599
5600         ENTRY;
5601
5602         LASSERT(!dt_object_remote(dt));
5603         LASSERT(handle != NULL);
5604
5605         oh = container_of(handle, struct osd_thandle, ot_super);
5606         LASSERT(oh->ot_handle == NULL);
5607
5608         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE];
5609         osd_trans_declare_op(env, oh, OSD_OT_DELETE, credits);
5610
5611         inode = osd_dt_obj(dt)->oo_inode;
5612         if (inode == NULL)
5613                 RETURN(-ENOENT);
5614
5615         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
5616                                    i_projid_read(inode), 0, oh, osd_dt_obj(dt),
5617                                    NULL, OSD_QID_BLK);
5618         RETURN(rc);
5619 }
5620
5621 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
5622                                           struct dt_rec *fid)
5623 {
5624         struct osd_fid_pack *rec;
5625         int rc = -ENODATA;
5626
5627         if (de->file_type & LDISKFS_DIRENT_LUFID) {
5628                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
5629                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
5630                 if (rc == 0 && unlikely(!fid_is_sane((struct lu_fid *)fid)))
5631                         rc = -EINVAL;
5632         }
5633         return rc;
5634 }
5635
5636 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
5637                           const struct lu_fid *fid)
5638 {
5639         struct seq_server_site *ss = osd_seq_site(osd);
5640
5641         ENTRY;
5642
5643         /* FID seqs not in FLDB, must be local seq */
5644         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
5645                 RETURN(0);
5646
5647         /*
5648          * If FLD is not being initialized yet, it only happens during the
5649          * initialization, likely during mgs initialization, and we assume
5650          * this is local FID.
5651          */
5652         if (ss == NULL || ss->ss_server_fld == NULL)
5653                 RETURN(0);
5654
5655         /* Only check the local FLDB here */
5656         if (osd_seq_exists(env, osd, fid_seq(fid)))
5657                 RETURN(0);
5658
5659         RETURN(1);
5660 }
5661
5662 static void osd_take_care_of_agent(const struct lu_env *env,
5663                                    struct osd_device *osd,
5664                                    struct osd_thandle *oh,
5665                                    struct ldiskfs_dir_entry_2 *de)
5666 {
5667         struct lu_fid *fid = &osd_oti_get(env)->oti_fid;
5668         struct osd_idmap_cache *idc;
5669         int rc, schedule = 0;
5670
5671         LASSERT(de != NULL);
5672
5673         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
5674         if (likely(rc == 0)) {
5675                 idc = osd_idc_find_or_init(env, osd, fid);
5676                 if (IS_ERR(idc) || idc->oic_remote)
5677                         schedule = 1;
5678         } else if (rc == -ENODATA) {
5679                 /*
5680                  * can't get FID, postpone to the end of the
5681                  * transaction when iget() is safe
5682                  */
5683                 schedule = 1;
5684         } else {
5685                 CERROR("%s: can't get FID: rc = %d\n", osd_name(osd), rc);
5686         }
5687         if (schedule)
5688                 osd_schedule_agent_inode_removal(env, oh,
5689                                                  le32_to_cpu(de->inode));
5690 }
5691
5692 /**
5693  * Utility function to get real name from object name
5694  *
5695  * \param[in] obj      pointer to the object to be handled
5696  * \param[in] name     object name
5697  * \param[in] len      object name len
5698  * \param[out]ln       pointer to the struct lu_name to hold the real name
5699  *
5700  * If file is not encrypted, real name is just the object name.
5701  * If file is encrypted, object name needs to be decoded. In
5702  * this case a new buffer is allocated, and ln->ln_name needs to be freed by
5703  * the caller.
5704  *
5705  * \retval   0, on success
5706  * \retval -ve, on error
5707  */
5708 static int obj_name2lu_name(struct osd_object *obj, const char *name,
5709                             int len, struct lu_name *ln)
5710 {
5711         if (!(obj->oo_lma_flags & LUSTRE_ENCRYPT_FL)) {
5712                 ln->ln_name = name;
5713                 ln->ln_namelen = len;
5714         } else {
5715                 char *buf = kmalloc(len, GFP_NOFS);
5716
5717                 if (!buf)
5718                         return -ENOMEM;
5719
5720                 len = critical_decode(name, len, buf);
5721                 ln->ln_name = buf;
5722                 ln->ln_namelen = len;
5723         }
5724
5725         return 0;
5726 }
5727
5728 /**
5729  * Index delete function for interoperability mode (b11826).
5730  * It will remove the directory entry added by osd_index_ea_insert().
5731  * This entry is needed to maintain name->fid mapping.
5732  *
5733  * \param key,  key i.e. file entry to be deleted
5734  *
5735  * \retval   0, on success
5736  * \retval -ve, on error
5737  */
5738 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
5739                                const struct dt_key *key, struct thandle *handle)
5740 {
5741         struct osd_object *obj = osd_dt_obj(dt);
5742         struct inode *dir = obj->oo_inode;
5743         struct dentry *dentry;
5744         struct osd_thandle *oh;
5745         struct ldiskfs_dir_entry_2 *de = NULL;
5746         struct buffer_head *bh;
5747         struct htree_lock *hlock = NULL;
5748         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
5749         struct lu_name ln;
5750         int rc;
5751
5752         ENTRY;
5753
5754         if (!dt_object_exists(dt))
5755                 RETURN(-ENOENT);
5756
5757         LINVRNT(osd_invariant(obj));
5758         LASSERT(!dt_object_remote(dt));
5759         LASSERT(handle != NULL);
5760
5761         rc = obj_name2lu_name(obj, (char *)key, strlen((char *)key), &ln);
5762         if (rc)
5763                 RETURN(rc);
5764
5765         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
5766
5767         oh = container_of(handle, struct osd_thandle, ot_super);
5768         LASSERT(oh->ot_handle != NULL);
5769         LASSERT(oh->ot_handle->h_transaction != NULL);
5770
5771         dquot_initialize(dir);
5772         dentry = osd_child_dentry_get(env, obj, ln.ln_name, ln.ln_namelen);
5773
5774         if (obj->oo_hl_head != NULL) {
5775                 hlock = osd_oti_get(env)->oti_hlock;
5776                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
5777                                    dir, LDISKFS_HLOCK_DEL);
5778         } else {
5779                 down_write(&obj->oo_ext_idx_sem);
5780         }
5781
5782         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5783         if (!IS_ERR(bh)) {
5784                 /*
5785                  * If this is not the ".." entry, it might be a remote DNE
5786                  * entry and  we need to check if the FID is for a remote
5787                  * MDT.  If the FID is  not in the directory entry (e.g.
5788                  * upgraded 1.8 filesystem without dirdata enabled) then
5789                  * we need to get the FID from the LMA. For a remote directory
5790                  * there HAS to be an LMA, it cannot be an IGIF inode in this
5791                  * case.
5792                  *
5793                  * Delete the entry before the agent inode in order to
5794                  * simplify error handling.  At worst an error after deleting
5795                  * the entry first might leak the agent inode afterward. The
5796                  * reverse would need filesystem abort in case of error deleting
5797                  * the entry after the agent had been removed, or leave a
5798                  * dangling entry pointing at a random inode.
5799                  */
5800                 if (strcmp((char *)key, dotdot) != 0)
5801                         osd_take_care_of_agent(env, osd, oh, de);
5802                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
5803                 brelse(bh);
5804         } else {
5805                 rc = PTR_ERR(bh);
5806         }
5807
5808         if (!rc && fid_is_namespace_visible(lu_object_fid(&dt->do_lu)))
5809                 atomic_dec_if_positive(&obj->oo_dirent_count);
5810         if (hlock != NULL)
5811                 ldiskfs_htree_unlock(hlock);
5812         else
5813                 up_write(&obj->oo_ext_idx_sem);
5814         GOTO(out, rc);
5815 out:
5816         LASSERT(osd_invariant(obj));
5817         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
5818         if (ln.ln_name != (char *)key)
5819                 kfree(ln.ln_name);
5820         RETURN(rc);
5821 }
5822
5823 /**
5824  *      Lookup index for \a key and copy record to \a rec.
5825  *
5826  *      \param  dt      osd index object
5827  *      \param  key     key for index
5828  *      \param  rec     record reference
5829  *
5830  *      \retval  +ve  success : exact mach
5831  *      \retval  0    return record with key not greater than \a key
5832  *      \retval -ve   failure
5833  */
5834 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
5835                                 struct dt_rec *rec, const struct dt_key *key)
5836 {
5837         struct osd_object *obj = osd_dt_obj(dt);
5838         struct iam_path_descr *ipd;
5839         struct iam_container *bag = &obj->oo_dir->od_container;
5840         struct osd_thread_info *oti = osd_oti_get(env);
5841         struct iam_iterator *it = &oti->oti_idx_it;
5842         struct iam_rec *iam_rec;
5843         int rc;
5844
5845         ENTRY;
5846
5847         if (!dt_object_exists(dt))
5848                 RETURN(-ENOENT);
5849
5850         LASSERT(osd_invariant(obj));
5851         LASSERT(!dt_object_remote(dt));
5852         LASSERT(bag->ic_object == obj->oo_inode);
5853
5854         ipd = osd_idx_ipd_get(env, bag);
5855         if (IS_ERR(ipd))
5856                 RETURN(-ENOMEM);
5857
5858         /* got ipd now we can start iterator. */
5859         iam_it_init(it, bag, 0, ipd);
5860
5861         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5862                 /* swab quota uid/gid provided by caller */
5863                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5864                 key = (const struct dt_key *)&oti->oti_quota_id;
5865         }
5866
5867         rc = iam_it_get(it, (struct iam_key *)key);
5868         if (rc >= 0) {
5869                 if (S_ISDIR(obj->oo_inode->i_mode))
5870                         iam_rec = (struct iam_rec *)oti->oti_ldp;
5871                 else
5872                         iam_rec = (struct iam_rec *)rec;
5873
5874                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
5875
5876                 if (S_ISDIR(obj->oo_inode->i_mode))
5877                         osd_fid_unpack((struct lu_fid *)rec,
5878                                        (struct osd_fid_pack *)iam_rec);
5879                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
5880                         osd_quota_unpack(obj, rec);
5881         }
5882
5883         iam_it_put(it);
5884         iam_it_fini(it);
5885         osd_ipd_put(env, bag, ipd);
5886
5887         LINVRNT(osd_invariant(obj));
5888
5889         RETURN(rc);
5890 }
5891
5892 static int osd_index_declare_iam_insert(const struct lu_env *env,
5893                                         struct dt_object *dt,
5894                                         const struct dt_rec *rec,
5895                                         const struct dt_key *key,
5896                                         struct thandle *handle)
5897 {
5898         struct osd_thandle *oh;
5899
5900         LASSERT(handle != NULL);
5901
5902         oh = container_of(handle, struct osd_thandle, ot_super);
5903         LASSERT(oh->ot_handle == NULL);
5904
5905         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
5906                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
5907
5908         return 0;
5909 }
5910
5911 /**
5912  *      Inserts (key, value) pair in \a dt index object.
5913  *
5914  *      \param  dt      osd index object
5915  *      \param  key     key for index
5916  *      \param  rec     record reference
5917  *      \param  th      transaction handler
5918  *
5919  *      \retval  0  success
5920  *      \retval -ve failure
5921  */
5922 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
5923                                 const struct dt_rec *rec,
5924                                 const struct dt_key *key, struct thandle *th)
5925 {
5926         struct osd_object *obj = osd_dt_obj(dt);
5927         struct iam_path_descr *ipd;
5928         struct osd_thandle *oh;
5929         struct iam_container *bag;
5930         struct osd_thread_info *oti = osd_oti_get(env);
5931         struct iam_rec *iam_rec;
5932         int rc;
5933
5934         ENTRY;
5935
5936         if (!dt_object_exists(dt))
5937                 RETURN(-ENOENT);
5938
5939         LINVRNT(osd_invariant(obj));
5940         LASSERT(!dt_object_remote(dt));
5941
5942         bag = &obj->oo_dir->od_container;
5943         LASSERT(bag->ic_object == obj->oo_inode);
5944         LASSERT(th != NULL);
5945
5946         osd_trans_exec_op(env, th, OSD_OT_INSERT);
5947
5948         ipd = osd_idx_ipd_get(env, bag);
5949         if (unlikely(ipd == NULL))
5950                 RETURN(-ENOMEM);
5951
5952         oh = container_of(th, struct osd_thandle, ot_super);
5953         LASSERT(oh->ot_handle != NULL);
5954         LASSERT(oh->ot_handle->h_transaction != NULL);
5955         if (S_ISDIR(obj->oo_inode->i_mode)) {
5956                 iam_rec = (struct iam_rec *)oti->oti_ldp;
5957                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec,
5958                              &oti->oti_fid);
5959         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5960                 /* pack quota uid/gid */
5961                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5962                 key = (const struct dt_key *)&oti->oti_quota_id;
5963                 /* pack quota record */
5964                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
5965                 iam_rec = (struct iam_rec *)rec;
5966         } else {
5967                 iam_rec = (struct iam_rec *)rec;
5968         }
5969
5970         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
5971                         iam_rec, ipd);
5972         osd_ipd_put(env, bag, ipd);
5973         LINVRNT(osd_invariant(obj));
5974         osd_trans_exec_check(env, th, OSD_OT_INSERT);
5975         RETURN(rc);
5976 }
5977
5978 /**
5979  * Calls ldiskfs_add_entry() to add directory entry
5980  * into the directory. This is required for
5981  * interoperability mode (b11826)
5982  *
5983  * \retval   0, on success
5984  * \retval -ve, on error
5985  */
5986 static int __osd_ea_add_rec(struct osd_thread_info *info,
5987                             struct osd_object *pobj, struct inode  *cinode,
5988                             const char *name, const struct lu_fid *fid,
5989                             struct htree_lock *hlock, struct thandle *th)
5990 {
5991         struct ldiskfs_dentry_param *ldp;
5992         struct dentry *child;
5993         struct osd_thandle *oth;
5994         struct lu_name ln;
5995         int rc;
5996
5997         oth = container_of(th, struct osd_thandle, ot_super);
5998         LASSERT(oth->ot_handle != NULL);
5999         LASSERT(oth->ot_handle->h_transaction != NULL);
6000         LASSERT(pobj->oo_inode);
6001
6002         rc = obj_name2lu_name(pobj, name, strlen(name), &ln);
6003         if (rc)
6004                 RETURN(rc);
6005
6006         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
6007         if (unlikely(osd_object_is_root(pobj)))
6008                 ldp->edp_magic = 0;
6009         else
6010                 osd_get_ldiskfs_dirent_param(ldp, fid);
6011         child = osd_child_dentry_get(info->oti_env, pobj,
6012                                      ln.ln_name, ln.ln_namelen);
6013         child->d_fsdata = (void *)ldp;
6014         dquot_initialize(pobj->oo_inode);
6015         rc = osd_ldiskfs_add_entry(info, osd_obj2dev(pobj), oth->ot_handle,
6016                                    child, cinode, hlock);
6017         if (rc == 0 && CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_TYPE)) {
6018                 struct ldiskfs_dir_entry_2      *de;
6019                 struct buffer_head              *bh;
6020                 int                              rc1;
6021
6022                 bh = osd_ldiskfs_find_entry(pobj->oo_inode, &child->d_name, &de,
6023                                             NULL, hlock);
6024                 if (!IS_ERR(bh)) {
6025                         rc1 = osd_ldiskfs_journal_get_write_access(
6026                                 oth->ot_handle, pobj->oo_inode->i_sb, bh,
6027                                 LDISKFS_JTR_NONE);
6028                         if (rc1 == 0) {
6029                                 if (S_ISDIR(cinode->i_mode))
6030                                         de->file_type = LDISKFS_DIRENT_LUFID |
6031                                                         LDISKFS_FT_REG_FILE;
6032                                 else
6033                                         de->file_type = LDISKFS_DIRENT_LUFID |
6034                                                         LDISKFS_FT_DIR;
6035                                 ldiskfs_handle_dirty_metadata(oth->ot_handle,
6036                                                               NULL, bh);
6037                         }
6038                         brelse(bh);
6039                 }
6040         }
6041
6042         if (ln.ln_name != name)
6043                 kfree(ln.ln_name);
6044         RETURN(rc);
6045 }
6046
6047 /**
6048  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
6049  * into the directory.Also sets flags into osd object to
6050  * indicate dot and dotdot are created. This is required for
6051  * interoperability mode (b11826)
6052  *
6053  * \param dir   directory for dot and dotdot fixup.
6054  * \param obj   child object for linking
6055  *
6056  * \retval   0, on success
6057  * \retval -ve, on error
6058  */
6059 static int osd_add_dot_dotdot(struct osd_thread_info *info,
6060                               struct osd_object *dir,
6061                               struct inode *parent_dir, const char *name,
6062                               const struct lu_fid *dot_fid,
6063                               const struct lu_fid *dot_dot_fid,
6064                               struct thandle *th)
6065 {
6066         struct inode *inode = dir->oo_inode;
6067         struct osd_thandle *oth;
6068         int result = 0;
6069
6070         oth = container_of(th, struct osd_thandle, ot_super);
6071         LASSERT(oth->ot_handle->h_transaction != NULL);
6072         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
6073
6074         if (strcmp(name, dot) == 0) {
6075                 if (dir->oo_compat_dot_created) {
6076                         result = -EEXIST;
6077                 } else {
6078                         LASSERT(inode->i_ino == parent_dir->i_ino);
6079                         dir->oo_compat_dot_created = 1;
6080                         result = 0;
6081                 }
6082         } else if (strcmp(name, dotdot) == 0) {
6083                 if (!dir->oo_compat_dot_created)
6084                         return -EINVAL;
6085                 /* in case of rename, dotdot is already created */
6086                 if (dir->oo_compat_dotdot_created) {
6087                         return __osd_ea_add_rec(info, dir, parent_dir, name,
6088                                                 dot_dot_fid, NULL, th);
6089                 }
6090
6091                 if (CFS_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
6092                         struct lu_fid tfid = *dot_dot_fid;
6093
6094                         tfid.f_oid--;
6095                         result = osd_add_dot_dotdot_internal(info,
6096                                         dir->oo_inode, parent_dir, dot_fid,
6097                                         &tfid, oth);
6098                 } else {
6099                         result = osd_add_dot_dotdot_internal(info,
6100                                         dir->oo_inode, parent_dir, dot_fid,
6101                                         dot_dot_fid, oth);
6102                 }
6103
6104                 if (result == 0)
6105                         dir->oo_compat_dotdot_created = 1;
6106         }
6107
6108         return result;
6109 }
6110
6111
6112 /**
6113  * It will call the appropriate osd_add* function and return the
6114  * value, return by respective functions.
6115  */
6116 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
6117                           struct inode *cinode, const char *name,
6118                           const struct lu_fid *fid, struct thandle *th)
6119 {
6120         struct osd_thread_info *info = osd_oti_get(env);
6121         struct htree_lock *hlock;
6122         int rc;
6123
6124         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
6125
6126         if (name[0] == '.' && (name[1] == '\0' ||
6127                                (name[1] == '.' && name[2] == '\0'))) {
6128                 if (hlock != NULL) {
6129                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
6130                                            pobj->oo_inode, 0);
6131                 } else {
6132                         down_write(&pobj->oo_ext_idx_sem);
6133                 }
6134
6135                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
6136                                         lu_object_fid(&pobj->oo_dt.do_lu),
6137                                         fid, th);
6138         } else {
6139                 if (hlock != NULL) {
6140                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
6141                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
6142                 } else {
6143                         down_write(&pobj->oo_ext_idx_sem);
6144                 }
6145
6146                 if (CFS_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
6147                         struct lu_fid *tfid = &info->oti_fid;
6148
6149                         *tfid = *fid;
6150                         tfid->f_ver = ~0;
6151                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
6152                                               tfid, hlock, th);
6153                 } else {
6154                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
6155                                               hlock, th);
6156                 }
6157         }
6158         if (!rc && fid_is_namespace_visible(lu_object_fid(&pobj->oo_dt.do_lu))){
6159                 int dirent_count = atomic_read(&pobj->oo_dirent_count);
6160
6161                 /* avoid extremely unlikely 2B-entry directory overflow case */
6162                 if (dirent_count != LU_DIRENT_COUNT_UNSET &&
6163                     likely(dirent_count < INT_MAX - NR_CPUS))
6164                         atomic_inc(&pobj->oo_dirent_count);
6165         }
6166
6167         if (hlock != NULL)
6168                 ldiskfs_htree_unlock(hlock);
6169         else
6170                 up_write(&pobj->oo_ext_idx_sem);
6171
6172         return rc;
6173 }
6174
6175 static int
6176 osd_ldiskfs_consistency_check(struct osd_thread_info *oti,
6177                               struct osd_device *dev,
6178                               const struct lu_fid *fid,
6179                               struct osd_inode_id *id)
6180 {
6181         struct lustre_scrub *scrub = &dev->od_scrub.os_scrub;
6182         struct inode *inode = NULL;
6183         int once = 0;
6184         bool insert;
6185         int rc;
6186
6187         ENTRY;
6188         if (!scrub_needs_check(scrub, fid, id->oii_ino))
6189                 RETURN(0);
6190 again:
6191         rc = osd_oi_lookup(oti, dev, fid, &oti->oti_id, 0);
6192         if (rc == -ENOENT) {
6193                 __u32 gen = id->oii_gen;
6194
6195                 insert = true;
6196                 if (inode != NULL)
6197                         goto trigger;
6198
6199                 inode = osd_iget(oti, dev, id);
6200                 /* The inode has been removed (by race maybe). */
6201                 if (IS_ERR(inode)) {
6202                         rc = PTR_ERR(inode);
6203
6204                         RETURN(rc == -ESTALE ? -ENOENT : rc);
6205                 }
6206
6207                 /* The OI mapping is lost. */
6208                 if (gen != OSD_OII_NOGEN)
6209                         goto trigger;
6210
6211                 /*
6212                  * The inode may has been reused by others, we do not know,
6213                  * leave it to be handled by subsequent osd_fid_lookup().
6214                  */
6215                 GOTO(out, rc = 0);
6216         } else if (rc || osd_id_eq(id, &oti->oti_id)) {
6217                 GOTO(out, rc);
6218         }
6219
6220         insert = false;
6221
6222 trigger:
6223         if (scrub->os_running) {
6224                 if (inode == NULL) {
6225                         inode = osd_iget(oti, dev, id);
6226                         /* The inode has been removed (by race maybe). */
6227                         if (IS_ERR(inode)) {
6228                                 rc = PTR_ERR(inode);
6229
6230                                 RETURN(rc == -ESTALE ? -ENOENT : rc);
6231                         }
6232                 }
6233
6234                 rc = osd_scrub_oi_insert(dev, fid, id, insert);
6235                 /*
6236                  * There is race condition between osd_oi_lookup and OI scrub.
6237                  * The OI scrub finished just after osd_oi_lookup() failure.
6238                  * Under such case, it is unnecessary to trigger OI scrub again,
6239                  * but try to call osd_oi_lookup() again.
6240                  */
6241                 if (unlikely(rc == -EAGAIN))
6242                         goto again;
6243
6244                 if (!S_ISDIR(inode->i_mode))
6245                         rc = 0;
6246                 else
6247                         rc = osd_check_lmv(oti, dev, inode);
6248
6249                 GOTO(out, rc);
6250         }
6251
6252         if (dev->od_scrub.os_scrub.os_auto_scrub_interval != AS_NEVER &&
6253             ++once == 1) {
6254                 rc = osd_scrub_start(oti->oti_env, dev, SS_AUTO_PARTIAL |
6255                                      SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT);
6256                 CDEBUG_LIMIT(D_LFSCK | D_CONSOLE | D_WARNING,
6257                              "%s: trigger partial OI scrub for RPC inconsistency, checking FID "DFID"/%u: rc = %d\n",
6258                              osd_dev2name(dev), PFID(fid), id->oii_ino, rc);
6259                 if (rc == 0 || rc == -EALREADY)
6260                         goto again;
6261         }
6262
6263         GOTO(out, rc);
6264
6265 out:
6266         iput(inode);
6267
6268         RETURN(rc);
6269 }
6270
6271 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
6272                                struct osd_device *dev,
6273                                struct lu_fid *fid, __u32 ino)
6274 {
6275         struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
6276         struct osd_idmap_cache *oic = &oti->oti_cache;
6277         struct inode *inode;
6278         int rc;
6279
6280         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
6281         inode = osd_iget(oti, dev, &oic->oic_lid);
6282         if (IS_ERR(inode)) {
6283                 fid_zero(&oic->oic_fid);
6284                 return PTR_ERR(inode);
6285         }
6286
6287         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, loa);
6288         iput(inode);
6289         if (rc != 0)
6290                 fid_zero(&oic->oic_fid);
6291         else
6292                 *fid = oic->oic_fid = loa->loa_lma.lma_self_fid;
6293         return rc;
6294 }
6295
6296 void osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
6297                       struct osd_inode_id *id, const struct lu_fid *fid)
6298 {
6299         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
6300                id->oii_ino, id->oii_gen, info);
6301         info->oti_cache.oic_lid = *id;
6302         info->oti_cache.oic_fid = *fid;
6303         info->oti_cache.oic_dev = osd;
6304 }
6305
6306 /**
6307  * Get parent FID from the linkEA.
6308  *
6309  * For a directory which parent resides on remote MDT, to satisfy the
6310  * local e2fsck, we insert it into the /REMOTE_PARENT_DIR locally. On
6311  * the other hand, to make the lookup(..) on the directory can return
6312  * the real parent FID, we append the real parent FID after its ".."
6313  * name entry in the /REMOTE_PARENT_DIR.
6314  *
6315  * Unfortunately, such PFID-in-dirent cannot be preserved via file-level
6316  * backup. So after the restore, we cannot get the right parent FID from
6317  * its ".." name entry in the /REMOTE_PARENT_DIR. Under such case, since
6318  * we have stored the real parent FID in the directory object's linkEA,
6319  * we can parse the linkEA for the real parent FID.
6320  *
6321  * \param[in] env       pointer to the thread context
6322  * \param[in] obj       pointer to the object to be handled
6323  * \param[out]fid       pointer to the buffer to hold the parent FID
6324  *
6325  * \retval              0 for getting the real parent FID successfully
6326  * \retval              negative error number on failure
6327  */
6328 static int osd_get_pfid_from_linkea(const struct lu_env *env,
6329                                     struct osd_object *obj,
6330                                     struct lu_fid *fid)
6331 {
6332         struct osd_thread_info *oti = osd_oti_get(env);
6333         struct lu_buf *buf = &oti->oti_big_buf;
6334         struct dentry *dentry = &oti->oti_obj_dentry;
6335         struct inode *inode = obj->oo_inode;
6336         struct linkea_data ldata = { NULL };
6337         int rc;
6338
6339         ENTRY;
6340
6341         fid_zero(fid);
6342         if (!S_ISDIR(inode->i_mode))
6343                 RETURN(-EIO);
6344
6345 again:
6346         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
6347                              buf->lb_buf, buf->lb_len);
6348         if (rc == -ERANGE) {
6349                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
6350                                      NULL, 0);
6351                 if (rc > 0) {
6352                         lu_buf_realloc(buf, rc);
6353                         if (buf->lb_buf == NULL)
6354                                 RETURN(-ENOMEM);
6355
6356                         goto again;
6357                 }
6358         }
6359
6360         if (unlikely(rc == 0))
6361                 RETURN(-ENODATA);
6362
6363         if (rc < 0)
6364                 RETURN(rc);
6365
6366         if (unlikely(buf->lb_buf == NULL)) {
6367                 lu_buf_realloc(buf, rc);
6368                 if (buf->lb_buf == NULL)
6369                         RETURN(-ENOMEM);
6370
6371                 goto again;
6372         }
6373
6374         ldata.ld_buf = buf;
6375         rc = linkea_init_with_rec(&ldata);
6376         if (!rc) {
6377                 linkea_first_entry(&ldata);
6378                 linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, NULL, fid);
6379         }
6380
6381         RETURN(rc);
6382 }
6383
6384 static int osd_verify_ent_by_linkea(const struct lu_env *env,
6385                                     struct inode *inode,
6386                                     const struct lu_fid *pfid,
6387                                     const char *name, const int namelen)
6388 {
6389         struct osd_thread_info *oti = osd_oti_get(env);
6390         struct lu_buf *buf = &oti->oti_big_buf;
6391         struct dentry *dentry = &oti->oti_obj_dentry;
6392         struct linkea_data ldata = { NULL };
6393         struct lu_name cname = { .ln_name = name,
6394                                  .ln_namelen = namelen };
6395         int rc;
6396
6397         ENTRY;
6398
6399 again:
6400         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
6401                              buf->lb_buf, buf->lb_len);
6402         if (rc == -ERANGE)
6403                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK, NULL, 0);
6404
6405         if (rc < 0)
6406                 RETURN(rc);
6407
6408         if (unlikely(rc == 0))
6409                 RETURN(-ENODATA);
6410
6411         if (buf->lb_len < rc) {
6412                 lu_buf_realloc(buf, rc);
6413                 if (buf->lb_buf == NULL)
6414                         RETURN(-ENOMEM);
6415
6416                 goto again;
6417         }
6418
6419         ldata.ld_buf = buf;
6420         rc = linkea_init_with_rec(&ldata);
6421         if (!rc)
6422                 rc = linkea_links_find(&ldata, &cname, pfid);
6423
6424         RETURN(rc);
6425 }
6426
6427 /**
6428  * Calls ->lookup() to find dentry. From dentry get inode and
6429  * read inode's ea to get fid. This is required for  interoperability
6430  * mode (b11826)
6431  *
6432  * \retval   0, on success
6433  * \retval -ve, on error
6434  */
6435 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
6436                              struct dt_rec *rec, const struct lu_name *ln)
6437 {
6438         struct inode *dir = obj->oo_inode;
6439         struct dentry *dentry;
6440         struct ldiskfs_dir_entry_2 *de;
6441         struct buffer_head *bh;
6442         struct lu_fid *fid = (struct lu_fid *)rec;
6443         struct htree_lock *hlock = NULL;
6444         int ino;
6445         int rc;
6446
6447         ENTRY;
6448
6449         LASSERT(dir->i_op != NULL);
6450         LASSERT(dir->i_op->lookup != NULL);
6451
6452         dentry = osd_child_dentry_get(env, obj, ln->ln_name, ln->ln_namelen);
6453
6454         if (obj->oo_hl_head != NULL) {
6455                 hlock = osd_oti_get(env)->oti_hlock;
6456                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
6457                                    dir, LDISKFS_HLOCK_LOOKUP);
6458         } else {
6459                 down_read(&obj->oo_ext_idx_sem);
6460         }
6461
6462         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
6463         if (!IS_ERR(bh)) {
6464                 struct osd_thread_info *oti = osd_oti_get(env);
6465                 struct osd_inode_id *id = &oti->oti_id;
6466                 struct osd_device *dev = osd_obj2dev(obj);
6467
6468                 ino = le32_to_cpu(de->inode);
6469                 if (CFS_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
6470                         brelse(bh);
6471                         rc = osd_fail_fid_lookup(oti, dev, fid, ino);
6472                         GOTO(out, rc);
6473                 }
6474
6475                 rc = osd_get_fid_from_dentry(de, rec);
6476
6477                 /* done with de, release bh */
6478                 brelse(bh);
6479                 if (rc != 0) {
6480                         if (unlikely(is_remote_parent_ino(dev, ino))) {
6481                                 /*
6482                                  * If the parent is on remote MDT, and there
6483                                  * is no FID-in-dirent, then we have to get
6484                                  * the parent FID from the linkEA.
6485                                  */
6486                                 if (likely(ln->ln_namelen == 2 &&
6487                                            ln->ln_name[0] == '.' && ln->ln_name[1] == '.'))
6488                                         rc = osd_get_pfid_from_linkea(env, obj,
6489                                                                       fid);
6490                         } else {
6491                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
6492                         }
6493                 } else {
6494                         osd_id_gen(id, ino, OSD_OII_NOGEN);
6495                 }
6496
6497                 if (rc != 0 || osd_remote_fid(env, dev, fid))
6498                         GOTO(out, rc);
6499
6500                 rc = osd_ldiskfs_consistency_check(oti, dev, fid, id);
6501                 if (rc != -ENOENT) {
6502                         /* Other error should not affect lookup result. */
6503                         rc = 0;
6504
6505                         /* Normal file mapping should be added into OI cache
6506                          * after FID in LMA check, but for local files like
6507                          * hsm_actions, their FIDs are not stored in OI files,
6508                          * see osd_initial_OI_scrub(), and here is the only
6509                          * place to load mapping into OI cache.
6510                          */
6511                         if (!fid_is_namespace_visible(fid))
6512                                 osd_add_oi_cache(osd_oti_get(env),
6513                                                  osd_obj2dev(obj), id, fid);
6514                 }
6515                 CDEBUG(D_INODE, DFID"/"DNAME" => "DFID"\n",
6516                        PFID(lu_object_fid(&obj->oo_dt.do_lu)), PNAME(ln),
6517                        PFID(fid));
6518         } else {
6519                 rc = PTR_ERR(bh);
6520         }
6521
6522         GOTO(out, rc);
6523
6524 out:
6525         if (hlock != NULL)
6526                 ldiskfs_htree_unlock(hlock);
6527         else
6528                 up_read(&obj->oo_ext_idx_sem);
6529         RETURN(rc);
6530 }
6531
6532 static int osd_index_declare_ea_insert(const struct lu_env *env,
6533                                        struct dt_object *dt,
6534                                        const struct dt_rec *rec,
6535                                        const struct dt_key *key,
6536                                        struct thandle *handle)
6537 {
6538         struct osd_thandle *oh;
6539         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
6540         struct dt_insert_rec *rec1 = (struct dt_insert_rec *)rec;
6541         const struct lu_fid *fid = rec1->rec_fid;
6542         int credits, rc = 0;
6543         struct osd_idmap_cache *idc;
6544
6545         ENTRY;
6546
6547         LASSERT(!dt_object_remote(dt));
6548         LASSERT(handle != NULL);
6549         LASSERT(fid != NULL);
6550         LASSERT(rec1->rec_type != 0);
6551
6552         oh = container_of(handle, struct osd_thandle, ot_super);
6553         LASSERT(oh->ot_handle == NULL);
6554
6555         credits = osd_dto_credits_noquota[DTO_INDEX_INSERT];
6556
6557         /*
6558          * we can't call iget() while a transactions is running
6559          * (this can lead to a deadlock), but we need to know
6560          * inum and object type. so we find this information at
6561          * declaration and cache in per-thread info
6562          */
6563         idc = osd_idc_find_or_init(env, osd, fid);
6564         if (IS_ERR(idc))
6565                 RETURN(PTR_ERR(idc));
6566         if (idc->oic_remote) {
6567                 /*
6568                  * a reference to remote inode is represented by an
6569                  * agent inode which we have to create
6570                  */
6571                 credits += osd_dto_credits_noquota[DTO_OBJECT_CREATE];
6572                 credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
6573         }
6574
6575         osd_trans_declare_op(env, oh, OSD_OT_INSERT, credits);
6576
6577         if (osd_dt_obj(dt)->oo_inode != NULL) {
6578                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
6579
6580                 /*
6581                  * We ignore block quota on meta pool (MDTs), so needn't
6582                  * calculate how many blocks will be consumed by this index
6583                  * insert
6584                  */
6585                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
6586                                            i_gid_read(inode),
6587                                            i_projid_read(inode), 0,
6588                                            oh, osd_dt_obj(dt), NULL,
6589                                            OSD_QID_BLK);
6590                 if (rc)
6591                         RETURN(rc);
6592
6593 #ifdef HAVE_PROJECT_QUOTA
6594                 /*
6595                  * Reserve credits for local agent inode to transfer
6596                  * to 0, quota enforcement is ignored in this case.
6597                  */
6598                 if (idc->oic_remote &&
6599                     LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
6600                     i_projid_read(inode) != 0)
6601                         rc = osd_declare_attr_qid(env, osd_dt_obj(dt), oh,
6602                                                   0, i_projid_read(inode),
6603                                                   0, false, PRJQUOTA);
6604 #endif
6605         }
6606
6607         RETURN(rc);
6608 }
6609
6610 /**
6611  * Index add function for interoperability mode (b11826).
6612  * It will add the directory entry.This entry is needed to
6613  * maintain name->fid mapping.
6614  *
6615  * \param key it is key i.e. file entry to be inserted
6616  * \param rec it is value of given key i.e. fid
6617  *
6618  * \retval   0, on success
6619  * \retval -ve, on error
6620  */
6621 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
6622                                const struct dt_rec *rec,
6623                                const struct dt_key *key, struct thandle *th)
6624 {
6625         struct osd_object *obj = osd_dt_obj(dt);
6626         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
6627         struct dt_insert_rec *rec1 = (struct dt_insert_rec *)rec;
6628         const struct lu_fid *fid = rec1->rec_fid;
6629         const char *name = (const char *)key;
6630         struct osd_thread_info *oti = osd_oti_get(env);
6631         struct inode *child_inode = NULL;
6632         struct osd_idmap_cache *idc;
6633         int rc;
6634
6635         ENTRY;
6636
6637         if (!dt_object_exists(dt))
6638                 RETURN(-ENOENT);
6639
6640         LASSERT(osd_invariant(obj));
6641         LASSERT(!dt_object_remote(dt));
6642         LASSERT(th != NULL);
6643
6644         osd_trans_exec_op(env, th, OSD_OT_INSERT);
6645
6646         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!\n", PFID(fid));
6647
6648         idc = osd_idc_find(env, osd, fid);
6649         if (unlikely(idc == NULL)) {
6650                 idc = osd_idc_find_or_init(env, osd, fid);
6651                 if (IS_ERR(idc)) {
6652                         /*
6653                          * this dt_insert() wasn't declared properly, so
6654                          * FID is missing in OI cache. we better do not
6655                          * lookup FID in FLDB/OI and don't risk to deadlock,
6656                          * but in some special cases (lfsck testing, etc)
6657                          * it's much simpler than fixing a caller.
6658                          *
6659                          * normally this error should be placed after the first
6660                          * find, but migrate may attach source stripes to
6661                          * target, which doesn't create stripes.
6662                          */
6663                         CERROR("%s: "DFID" wasn't declared for insert\n",
6664                                osd_name(osd), PFID(fid));
6665                         dump_stack();
6666                         RETURN(PTR_ERR(idc));
6667                 }
6668         }
6669
6670         if (idc->oic_remote) {
6671                 /* Insert remote entry */
6672                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
6673                         child_inode =
6674                         igrab(osd->od_mdt_map->omm_remote_parent->d_inode);
6675                 } else {
6676                         child_inode = osd_create_local_agent_inode(env, osd,
6677                                         obj, fid, rec1->rec_type & S_IFMT, th);
6678                         if (IS_ERR(child_inode))
6679                                 RETURN(PTR_ERR(child_inode));
6680                 }
6681         } else {
6682                 /* Insert local entry */
6683                 if (unlikely(idc->oic_lid.oii_ino == 0)) {
6684                         /* for a reason OI cache wasn't filled properly */
6685                         CERROR("%s: OIC for "DFID" isn't filled\n",
6686                                osd_name(osd), PFID(fid));
6687                         RETURN(-EINVAL);
6688                 }
6689                 child_inode = oti->oti_inode;
6690                 if (unlikely(child_inode == NULL)) {
6691                         struct ldiskfs_inode_info *lii;
6692
6693                         OBD_ALLOC_PTR(lii);
6694                         if (lii == NULL)
6695                                 RETURN(-ENOMEM);
6696                         child_inode = oti->oti_inode = &lii->vfs_inode;
6697                 }
6698                 child_inode->i_sb = osd_sb(osd);
6699                 child_inode->i_ino = idc->oic_lid.oii_ino;
6700                 child_inode->i_mode = rec1->rec_type & S_IFMT;
6701         }
6702
6703         rc = osd_ea_add_rec(env, obj, child_inode, name, fid, th);
6704
6705         CDEBUG(D_INODE, "parent %lu insert %s:%lu rc = %d\n",
6706                obj->oo_inode->i_ino, name, child_inode->i_ino, rc);
6707
6708         if (child_inode && child_inode != oti->oti_inode)
6709                 iput(child_inode);
6710         LASSERT(osd_invariant(obj));
6711         osd_trans_exec_check(env, th, OSD_OT_INSERT);
6712
6713         RETURN(rc);
6714 }
6715
6716 /**
6717  *  Initialize osd Iterator for given osd index object.
6718  *
6719  *  \param  dt      osd index object
6720  */
6721
6722 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
6723                                      struct dt_object *dt,
6724                                      __u32 unused)
6725 {
6726         struct osd_it_iam *it;
6727         struct osd_object *obj = osd_dt_obj(dt);
6728         struct lu_object *lo = &dt->do_lu;
6729         struct iam_path_descr *ipd;
6730         struct iam_container *bag = &obj->oo_dir->od_container;
6731
6732         if (!dt_object_exists(dt))
6733                 return ERR_PTR(-ENOENT);
6734
6735         OBD_ALLOC_PTR(it);
6736         if (it == NULL)
6737                 return ERR_PTR(-ENOMEM);
6738
6739         ipd = osd_it_ipd_get(env, bag);
6740         if (likely(ipd != NULL)) {
6741                 it->oi_obj = obj;
6742                 it->oi_ipd = ipd;
6743                 lu_object_get(lo);
6744                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
6745                 return (struct dt_it *)it;
6746         } else {
6747                 OBD_FREE_PTR(it);
6748                 return ERR_PTR(-ENOMEM);
6749         }
6750 }
6751
6752 /**
6753  * free given Iterator.
6754  */
6755 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
6756 {
6757         struct osd_it_iam *it  = (struct osd_it_iam *)di;
6758         struct osd_object *obj = it->oi_obj;
6759
6760         iam_it_fini(&it->oi_it);
6761         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
6762         osd_object_put(env, obj);
6763         OBD_FREE_PTR(it);
6764 }
6765
6766 /**
6767  *  Move Iterator to record specified by \a key
6768  *
6769  *  \param  di      osd iterator
6770  *  \param  key     key for index
6771  *
6772  *  \retval +ve  di points to record with least key not larger than key
6773  *  \retval  0   di points to exact matched key
6774  *  \retval -ve  failure
6775  */
6776
6777 static int osd_it_iam_get(const struct lu_env *env,
6778                           struct dt_it *di, const struct dt_key *key)
6779 {
6780         struct osd_thread_info *oti = osd_oti_get(env);
6781         struct osd_it_iam *it = (struct osd_it_iam *)di;
6782
6783         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
6784                 /* swab quota uid/gid */
6785                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
6786                 key = (struct dt_key *)&oti->oti_quota_id;
6787         }
6788
6789         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
6790 }
6791
6792 /**
6793  *  Release Iterator
6794  *
6795  *  \param  di      osd iterator
6796  */
6797 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
6798 {
6799         struct osd_it_iam *it = (struct osd_it_iam *)di;
6800
6801         iam_it_put(&it->oi_it);
6802 }
6803
6804 /**
6805  *  Move iterator by one record
6806  *
6807  *  \param  di      osd iterator
6808  *
6809  *  \retval +1   end of container reached
6810  *  \retval  0   success
6811  *  \retval -ve  failure
6812  */
6813
6814 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
6815 {
6816         struct osd_it_iam *it = (struct osd_it_iam *)di;
6817
6818         return iam_it_next(&it->oi_it);
6819 }
6820
6821 /**
6822  * Return pointer to the key under iterator.
6823  */
6824
6825 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
6826                                      const struct dt_it *di)
6827 {
6828         struct osd_thread_info *oti = osd_oti_get(env);
6829         struct osd_it_iam *it = (struct osd_it_iam *)di;
6830         struct osd_object *obj = it->oi_obj;
6831         struct dt_key *key;
6832
6833         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
6834
6835         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
6836                 /* swab quota uid/gid */
6837                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
6838                 key = (struct dt_key *)&oti->oti_quota_id;
6839         }
6840
6841         return key;
6842 }
6843
6844 /**
6845  * Return size of key under iterator (in bytes)
6846  */
6847
6848 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
6849 {
6850         struct osd_it_iam *it = (struct osd_it_iam *)di;
6851
6852         return iam_it_key_size(&it->oi_it);
6853 }
6854
6855 static inline void
6856 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
6857 {
6858         /* check if file type is required */
6859         if (ent->lde_attrs & LUDA_TYPE) {
6860                 struct luda_type *lt;
6861                 int align = sizeof(*lt) - 1;
6862
6863                 len = (len + align) & ~align;
6864                 lt = (struct luda_type *)(ent->lde_name + len);
6865                 lt->lt_type = cpu_to_le16(DTTOIF(type));
6866         }
6867
6868         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
6869 }
6870
6871 /**
6872  * build lu direct from backend fs dirent.
6873  */
6874
6875 static inline void
6876 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
6877                    char *name, __u16 namelen, __u16 type, __u32 attr)
6878 {
6879         ent->lde_attrs = attr | LUDA_FID;
6880         fid_cpu_to_le(&ent->lde_fid, fid);
6881
6882         ent->lde_hash = cpu_to_le64(offset);
6883         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
6884
6885         strncpy(ent->lde_name, name, namelen);
6886         ent->lde_name[namelen] = '\0';
6887         ent->lde_namelen = cpu_to_le16(namelen);
6888
6889         /* append lustre attributes */
6890         osd_it_append_attrs(ent, namelen, type);
6891 }
6892
6893 /**
6894  * Return pointer to the record under iterator.
6895  */
6896 static int osd_it_iam_rec(const struct lu_env *env,
6897                           const struct dt_it *di,
6898                           struct dt_rec *dtrec, __u32 attr)
6899 {
6900         struct osd_it_iam *it = (struct osd_it_iam *)di;
6901         struct osd_thread_info *info = osd_oti_get(env);
6902
6903         ENTRY;
6904
6905         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
6906                 const struct osd_fid_pack *rec;
6907                 struct lu_fid *fid = &info->oti_fid;
6908                 struct lu_dirent *lde = (struct lu_dirent *)dtrec;
6909                 char *name;
6910                 int namelen;
6911                 __u64 hash;
6912                 int rc;
6913
6914                 name = (char *)iam_it_key_get(&it->oi_it);
6915                 if (IS_ERR(name))
6916                         RETURN(PTR_ERR(name));
6917
6918                 namelen = iam_it_key_size(&it->oi_it);
6919
6920                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
6921                 if (IS_ERR(rec))
6922                         RETURN(PTR_ERR(rec));
6923
6924                 rc = osd_fid_unpack(fid, rec);
6925                 if (rc)
6926                         RETURN(rc);
6927
6928                 hash = iam_it_store(&it->oi_it);
6929
6930                 /* IAM does not store object type in IAM index (dir) */
6931                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
6932                                    0, LUDA_FID);
6933         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
6934                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
6935                            (struct iam_rec *)dtrec);
6936                 osd_quota_unpack(it->oi_obj, dtrec);
6937         } else {
6938                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
6939                            (struct iam_rec *)dtrec);
6940         }
6941
6942         RETURN(0);
6943 }
6944
6945 /**
6946  * Returns cookie for current Iterator position.
6947  */
6948 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
6949 {
6950         struct osd_it_iam *it = (struct osd_it_iam *)di;
6951
6952         return iam_it_store(&it->oi_it);
6953 }
6954
6955 /**
6956  * Restore iterator from cookie.
6957  *
6958  * \param  di      osd iterator
6959  * \param  hash    Iterator location cookie
6960  *
6961  * \retval +ve  di points to record with least key not larger than key.
6962  * \retval  0   di points to exact matched key
6963  * \retval -ve  failure
6964  */
6965
6966 static int osd_it_iam_load(const struct lu_env *env,
6967                            const struct dt_it *di, __u64 hash)
6968 {
6969         struct osd_it_iam *it = (struct osd_it_iam *)di;
6970
6971         return iam_it_load(&it->oi_it, hash);
6972 }
6973
6974 static const struct dt_index_operations osd_index_iam_ops = {
6975         .dio_lookup         = osd_index_iam_lookup,
6976         .dio_declare_insert = osd_index_declare_iam_insert,
6977         .dio_insert         = osd_index_iam_insert,
6978         .dio_declare_delete = osd_index_declare_iam_delete,
6979         .dio_delete         = osd_index_iam_delete,
6980         .dio_it     = {
6981                 .init     = osd_it_iam_init,
6982                 .fini     = osd_it_iam_fini,
6983                 .get      = osd_it_iam_get,
6984                 .put      = osd_it_iam_put,
6985                 .next     = osd_it_iam_next,
6986                 .key      = osd_it_iam_key,
6987                 .key_size = osd_it_iam_key_size,
6988                 .rec      = osd_it_iam_rec,
6989                 .store    = osd_it_iam_store,
6990                 .load     = osd_it_iam_load
6991         }
6992 };
6993
6994 struct osd_it_ea *osd_it_dir_init(const struct lu_env *env,
6995                                   struct osd_device *dev,
6996                                   struct inode *inode, u32 attr)
6997 {
6998         struct osd_thread_info *info = osd_oti_get(env);
6999         struct osd_it_ea *oie;
7000         struct file *file;
7001
7002         ENTRY;
7003         file = alloc_file_pseudo(inode, dev->od_mnt, "/", O_NOATIME,
7004                                  inode->i_fop);
7005         if (IS_ERR(file))
7006                 RETURN(ERR_CAST(file));
7007
7008         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
7009         if (attr & LUDA_64BITHASH)
7010                 file->f_mode |= FMODE_64BITHASH;
7011         else
7012                 file->f_mode |= FMODE_32BITHASH;
7013         ihold(inode);
7014
7015         OBD_SLAB_ALLOC_PTR(oie, osd_itea_cachep);
7016         if (!oie)
7017                 goto out_fput;
7018
7019         oie->oie_rd_dirent       = 0;
7020         oie->oie_it_dirent       = 0;
7021         oie->oie_dirent          = NULL;
7022         if (unlikely(!info->oti_it_ea_buf_used)) {
7023                 oie->oie_buf = info->oti_it_ea_buf;
7024                 info->oti_it_ea_buf_used = 1;
7025         } else {
7026                 OBD_ALLOC(oie->oie_buf, OSD_IT_EA_BUFSIZE);
7027                 if (!oie->oie_buf)
7028                         goto out_free;
7029         }
7030         oie->oie_obj = NULL;
7031         oie->oie_file = file;
7032
7033         RETURN(oie);
7034
7035 out_free:
7036         OBD_SLAB_FREE_PTR(oie, osd_itea_cachep);
7037 out_fput:
7038         fput(file);
7039
7040         return ERR_PTR(-ENOMEM);
7041 }
7042
7043 /**
7044  * Creates or initializes iterator context.
7045  *
7046  * \retval struct osd_it_ea, iterator structure on success
7047  *
7048  */
7049 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
7050                                     struct dt_object *dt,
7051                                     __u32 attr)
7052 {
7053         struct osd_object *obj = osd_dt_obj(dt);
7054         struct osd_device *dev = osd_obj2dev(obj);
7055         struct lu_object *lo = &dt->do_lu;
7056         struct osd_it_ea *oie;
7057
7058         ENTRY;
7059
7060         if (!dt_object_exists(dt) || obj->oo_destroyed)
7061                 RETURN(ERR_PTR(-ENOENT));
7062
7063         oie = osd_it_dir_init(env, dev, obj->oo_inode, attr);
7064         if (IS_ERR(oie))
7065                 RETURN(ERR_CAST(oie));
7066
7067         oie->oie_obj = obj;
7068         lu_object_get(lo);
7069         RETURN((struct dt_it *)oie);
7070 }
7071
7072 void osd_it_dir_fini(const struct lu_env *env, struct osd_it_ea *oie,
7073                      struct inode *inode)
7074 {
7075         struct osd_thread_info *info = osd_oti_get(env);
7076
7077         ENTRY;
7078         fput(oie->oie_file);
7079         if (unlikely(oie->oie_buf != info->oti_it_ea_buf))
7080                 OBD_FREE(oie->oie_buf, OSD_IT_EA_BUFSIZE);
7081         else
7082                 info->oti_it_ea_buf_used = 0;
7083         OBD_SLAB_FREE_PTR(oie, osd_itea_cachep);
7084         EXIT;
7085 }
7086
7087 /**
7088  * Destroy or finishes iterator context.
7089  *
7090  * \param di iterator structure to be destroyed
7091  */
7092 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
7093 {
7094         struct osd_it_ea *oie = (struct osd_it_ea *)di;
7095         struct osd_object *obj = oie->oie_obj;
7096         struct inode *inode = obj->oo_inode;
7097
7098         ENTRY;
7099         osd_it_dir_fini(env, (struct osd_it_ea *)di, inode);
7100         osd_object_put(env, obj);
7101         EXIT;
7102 }
7103
7104 /**
7105  * It position the iterator at given key, so that next lookup continues from
7106  * that key Or it is similar to dio_it->load() but based on a key,
7107  * rather than file position.
7108  *
7109  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
7110  * to the beginning.
7111  *
7112  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
7113  */
7114 static int osd_it_ea_get(const struct lu_env *env,
7115                          struct dt_it *di, const struct dt_key *key)
7116 {
7117         struct osd_it_ea *it = (struct osd_it_ea *)di;
7118
7119         ENTRY;
7120         LASSERT(((const char *)key)[0] == '\0');
7121         it->oie_file->f_pos = 0;
7122         it->oie_rd_dirent = 0;
7123         it->oie_it_dirent = 0;
7124         it->oie_dirent = NULL;
7125
7126         RETURN(+1);
7127 }
7128
7129 /**
7130  * Does nothing
7131  */
7132 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
7133 {
7134 }
7135
7136 struct osd_filldir_cbs {
7137         struct dir_context ctx;
7138         struct osd_it_ea  *it;
7139 };
7140 /**
7141  * It is called internally by ->iterate*(). It fills the
7142  * iterator's in-memory data structure with required
7143  * information i.e. name, namelen, rec_size etc.
7144  *
7145  * \param buf in which information to be filled in.
7146  * \param name name of the file in given dir
7147  *
7148  * \retval 0 on success
7149  * \retval 1 on buffer full
7150  */
7151 #ifdef HAVE_FILLDIR_USE_CTX
7152 static FILLDIR_TYPE do_osd_ldiskfs_filldir(struct dir_context *ctx,
7153 #else
7154 static int osd_ldiskfs_filldir(void *ctx,
7155 #endif
7156                                const char *name, int namelen,
7157                                loff_t offset, __u64 ino, unsigned int d_type)
7158 {
7159         struct osd_it_ea *it = ((struct osd_filldir_cbs *)ctx)->it;
7160         struct osd_object *obj = it->oie_obj;
7161         struct osd_it_ea_dirent *ent = it->oie_dirent;
7162         struct lu_fid *fid = &ent->oied_fid;
7163         char *buf = it->oie_buf;
7164         struct osd_fid_pack *rec;
7165         ENTRY;
7166
7167         /* this should never happen */
7168         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
7169                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
7170                 RETURN(-EIO);
7171         }
7172
7173         /* Check for enough space. Note oied_name is not NUL terminated. */
7174         if (&ent->oied_name[namelen] > buf + OSD_IT_EA_BUFSIZE)
7175                 RETURN(1);
7176
7177         /* "." is just the object itself. */
7178         if (namelen == 1 && name[0] == '.') {
7179                 if (obj != NULL)
7180                         *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
7181         } else if (d_type & LDISKFS_DIRENT_LUFID) {
7182                 rec = (struct osd_fid_pack *)(name + namelen + 1);
7183                 if (osd_fid_unpack(fid, rec) != 0)
7184                         fid_zero(fid);
7185         } else {
7186                 fid_zero(fid);
7187         }
7188         d_type &= ~LDISKFS_DIRENT_LUFID;
7189
7190         /* NOT export local root. */
7191         if (obj != NULL &&
7192             unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
7193                 ino = obj->oo_inode->i_ino;
7194                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
7195         }
7196
7197         if (obj == NULL || !(obj->oo_lma_flags & LUSTRE_ENCRYPT_FL)) {
7198                 ent->oied_namelen = namelen;
7199                 memcpy(ent->oied_name, name, namelen);
7200         } else {
7201                 int encoded_namelen = critical_chars(name, namelen);
7202
7203                 /* Check again for enough space. */
7204                 if (&ent->oied_name[encoded_namelen] > buf + OSD_IT_EA_BUFSIZE)
7205                         RETURN(1);
7206
7207                 ent->oied_namelen = encoded_namelen;
7208
7209                 if (encoded_namelen == namelen)
7210                         memcpy(ent->oied_name, name, namelen);
7211                 else
7212                         critical_encode(name, namelen, ent->oied_name);
7213         }
7214
7215         ent->oied_ino     = ino;
7216         ent->oied_off     = offset;
7217         ent->oied_type    = d_type;
7218
7219         it->oie_rd_dirent++;
7220         it->oie_dirent = (void *)ent + round_up(sizeof(*ent) + ent->oied_namelen, 8);
7221         RETURN(0);
7222 }
7223
7224 WRAP_FILLDIR_FN(do_, osd_ldiskfs_filldir)
7225
7226 /**
7227  * Calls ->iterate*() to load a directory entry at a time
7228  * and stored it in iterator's in-memory data structure.
7229  *
7230  * \param di iterator's in memory structure
7231  *
7232  * \retval   0 on success
7233  * \retval -ve on error
7234  * \retval +1 reach the end of entry
7235  */
7236 int osd_ldiskfs_it_fill(const struct lu_env *env, const struct dt_it *di)
7237 {
7238         struct osd_it_ea *it = (struct osd_it_ea *)di;
7239         struct osd_object *obj = it->oie_obj;
7240         struct htree_lock *hlock = NULL;
7241         struct file *filp = it->oie_file;
7242         int rc = 0;
7243         struct osd_filldir_cbs buf = {
7244                 .ctx.actor = osd_ldiskfs_filldir,
7245                 .it = it
7246         };
7247
7248         ENTRY;
7249         it->oie_dirent = it->oie_buf;
7250         it->oie_rd_dirent = 0;
7251
7252         if (obj) {
7253                 if (obj->oo_hl_head != NULL) {
7254                         hlock = osd_oti_get(env)->oti_hlock;
7255                         ldiskfs_htree_lock(hlock, obj->oo_hl_head,
7256                                            obj->oo_inode,
7257                                            LDISKFS_HLOCK_READDIR);
7258                 } else {
7259                         down_read(&obj->oo_ext_idx_sem);
7260                 }
7261         }
7262
7263         rc = iterate_dir(filp, &buf.ctx);
7264         if (rc)
7265                 GOTO(unlock, rc);
7266
7267         if (it->oie_rd_dirent == 0) {
7268                 /*
7269                  * If it does not get any dirent, it means it has been reached
7270                  * to the end of the dir
7271                  */
7272                 it->oie_file->f_pos = ldiskfs_get_htree_eof(it->oie_file);
7273                 if (rc == 0)
7274                         rc = 1;
7275         } else {
7276                 it->oie_dirent = it->oie_buf;
7277                 it->oie_it_dirent = 1;
7278         }
7279 unlock:
7280         if (obj) {
7281                 if (hlock != NULL)
7282                         ldiskfs_htree_unlock(hlock);
7283                 else
7284                         up_read(&obj->oo_ext_idx_sem);
7285         }
7286
7287         RETURN(rc);
7288 }
7289
7290 /**
7291  * It calls osd_ldiskfs_it_fill() which will use ->iterate*()
7292  * to load a directory entry at a time and stored it in
7293  * iterator's in-memory data structure.
7294  *
7295  * \param di iterator's in memory structure
7296  *
7297  * \retval +ve iterator reached to end
7298  * \retval   0 iterator not reached to end
7299  * \retval -ve on error
7300  */
7301 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
7302 {
7303         struct osd_it_ea *it = (struct osd_it_ea *)di;
7304         int rc;
7305
7306         ENTRY;
7307
7308         if (it->oie_it_dirent < it->oie_rd_dirent) {
7309                 it->oie_dirent =
7310                         (void *)it->oie_dirent +
7311                         round_up(sizeof(struct osd_it_ea_dirent) +
7312                                        it->oie_dirent->oied_namelen, 8);
7313                 it->oie_it_dirent++;
7314                 rc = 0;
7315         } else {
7316                 if (it->oie_file->f_pos == ldiskfs_get_htree_eof(it->oie_file))
7317                         rc = 1;
7318                 else
7319                         rc = osd_ldiskfs_it_fill(env, di);
7320         }
7321
7322         RETURN(rc);
7323 }
7324
7325 /**
7326  * Returns the key at current position from iterator's in memory structure.
7327  *
7328  * \param di iterator's in memory structure
7329  *
7330  * \retval key i.e. struct dt_key on success
7331  */
7332 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
7333                                     const struct dt_it *di)
7334 {
7335         struct osd_it_ea *it = (struct osd_it_ea *)di;
7336
7337         return (struct dt_key *)it->oie_dirent->oied_name;
7338 }
7339
7340 /**
7341  * Returns key's size at current position from iterator's in memory structure.
7342  *
7343  * \param di iterator's in memory structure
7344  *
7345  * \retval key_size i.e. struct dt_key on success
7346  */
7347 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
7348 {
7349         struct osd_it_ea *it = (struct osd_it_ea *)di;
7350
7351         return it->oie_dirent->oied_namelen;
7352 }
7353
7354 #if defined LDISKFS_DIR_ENTRY_LEN && defined LDISKFS_DIR_ENTRY_LEN_
7355 #undef LDISKFS_DIR_REC_LEN
7356 # if defined LDISKFS_DIR_REC_LEN_WITH_DIR
7357 #  define LDISKFS_DIR_REC_LEN(de, dir)  LDISKFS_DIR_ENTRY_LEN_((de), (dir))
7358 # else
7359 #  define LDISKFS_DIR_REC_LEN(de)       LDISKFS_DIR_ENTRY_LEN_((de))
7360 # endif
7361 #endif
7362
7363 #if defined LDISKFS_DIR_REC_LEN_WITH_DIR
7364 # define LDISKFS_DIR_REC_LEN_DIR(de)    LDISKFS_DIR_REC_LEN((de), NULL)
7365 #else
7366 # define LDISKFS_DIR_REC_LEN_DIR(de)    LDISKFS_DIR_REC_LEN((de))
7367 #endif
7368
7369 static inline bool osd_dotdot_has_space(struct ldiskfs_dir_entry_2 *de)
7370 {
7371         if (LDISKFS_DIR_REC_LEN_DIR(de) >=
7372             __LDISKFS_DIR_REC_LEN(2 + 1 + sizeof(struct osd_fid_pack)))
7373                 return true;
7374
7375         return false;
7376 }
7377
7378 static inline bool
7379 osd_dirent_has_space(struct ldiskfs_dir_entry_2 *de, __u16 namelen,
7380                      unsigned int blocksize, bool dotdot)
7381 {
7382         if (dotdot)
7383                 return osd_dotdot_has_space(de);
7384
7385         if (ldiskfs_rec_len_from_disk(de->rec_len, blocksize) >=
7386             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
7387                 return true;
7388
7389         return false;
7390 }
7391
7392 static int
7393 osd_dirent_reinsert(const struct lu_env *env, struct osd_device *dev,
7394                     handle_t *jh, struct dentry *dentry,
7395                     const struct lu_fid *fid, struct buffer_head *bh,
7396                     struct ldiskfs_dir_entry_2 *de, struct htree_lock *hlock,
7397                     bool dotdot)
7398 {
7399         struct inode *dir = dentry->d_parent->d_inode;
7400         struct inode *inode = dentry->d_inode;
7401         struct osd_fid_pack *rec;
7402         struct ldiskfs_dentry_param *ldp;
7403         int namelen = dentry->d_name.len;
7404         int rc;
7405         struct osd_thread_info *info = osd_oti_get(env);
7406
7407         ENTRY;
7408
7409         if (!ldiskfs_has_feature_dirdata(inode->i_sb))
7410                 RETURN(0);
7411
7412         /* There is enough space to hold the FID-in-dirent. */
7413         if (osd_dirent_has_space(de, namelen, dir->i_sb->s_blocksize, dotdot)) {
7414                 rc = osd_ldiskfs_journal_get_write_access(jh, dir->i_sb, bh,
7415                                                           LDISKFS_JTR_NONE);
7416                 if (rc != 0)
7417                         RETURN(rc);
7418
7419                 de->name[namelen] = 0;
7420                 rec = (struct osd_fid_pack *)(de->name + namelen + 1);
7421                 rec->fp_len = sizeof(struct lu_fid) + 1;
7422                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
7423                 de->file_type |= LDISKFS_DIRENT_LUFID;
7424                 rc = ldiskfs_handle_dirty_metadata(jh, NULL, bh);
7425
7426                 RETURN(rc);
7427         }
7428
7429         LASSERT(!dotdot);
7430
7431         rc = ldiskfs_delete_entry(jh, dir, de, bh);
7432         if (rc != 0)
7433                 RETURN(rc);
7434
7435         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
7436         osd_get_ldiskfs_dirent_param(ldp, fid);
7437         dentry->d_fsdata = (void *)ldp;
7438         dquot_initialize(dir);
7439         rc = osd_ldiskfs_add_entry(info, dev, jh, dentry, inode, hlock);
7440         /*
7441          * It is too bad, we cannot reinsert the name entry back.
7442          * That means we lose it!
7443          */
7444         if (rc != 0)
7445                 CDEBUG(D_LFSCK,
7446                        "%s: fail to reinsert the dirent, dir = %lu/%u, name = %.*s, "DFID": rc = %d\n",
7447                        osd_ino2name(inode), dir->i_ino, dir->i_generation,
7448                        namelen, dentry->d_name.name, PFID(fid), rc);
7449
7450         RETURN(rc);
7451 }
7452
7453 static int
7454 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
7455                         struct osd_it_ea *it, struct lu_fid *fid,
7456                         struct osd_inode_id *id, __u32 *attr)
7457 {
7458         struct osd_thread_info *info = osd_oti_get(env);
7459         struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
7460         struct osd_device *dev = osd_obj2dev(obj);
7461         struct super_block *sb = osd_sb(dev);
7462         const char *devname = osd_name(dev);
7463         struct osd_it_ea_dirent *ent = it->oie_dirent;
7464         struct inode *dir = obj->oo_inode;
7465         struct htree_lock *hlock = NULL;
7466         struct buffer_head *bh = NULL;
7467         handle_t *jh = NULL;
7468         struct ldiskfs_dir_entry_2 *de;
7469         struct dentry *dentry;
7470         struct inode *inode;
7471         const struct lu_fid *pfid = lu_object_fid(&obj->oo_dt.do_lu);
7472         int credits;
7473         int rc;
7474         bool dotdot = false;
7475         bool dirty = false;
7476         struct lu_name ln;
7477
7478         ENTRY;
7479
7480         if (ent->oied_name[0] == '.') {
7481                 if (ent->oied_namelen == 1)
7482                         RETURN(0);
7483
7484                 if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
7485                         dotdot = true;
7486         }
7487
7488         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
7489         inode = osd_iget(info, dev, id);
7490         if (IS_ERR(inode)) {
7491                 rc = PTR_ERR(inode);
7492                 if (rc == -ENOENT || rc == -ESTALE) {
7493                         /*
7494                          * Maybe dangling name entry, or
7495                          * corrupted directory entry.
7496                          */
7497                         *attr |= LUDA_UNKNOWN;
7498                         rc = 0;
7499                 } else {
7500                         CDEBUG(D_LFSCK, "%s: fail to iget() for dirent "
7501                                "check_repair, dir = %lu/%u, name = %.*s, "
7502                                "ino = %llu, rc = %d\n",
7503                                devname, dir->i_ino, dir->i_generation,
7504                                ent->oied_namelen, ent->oied_name,
7505                                ent->oied_ino, rc);
7506                 }
7507
7508                 RETURN(rc);
7509         }
7510
7511         rc = obj_name2lu_name(obj, ent->oied_name, ent->oied_namelen, &ln);
7512         if (rc)
7513                 RETURN(rc);
7514
7515         dentry = osd_child_dentry_by_inode(env, dir, ln.ln_name, ln.ln_namelen);
7516         rc = osd_get_lma(info, inode, dentry, &info->oti_ost_attrs);
7517         if (rc == -ENODATA || !fid_is_sane(&lma->lma_self_fid))
7518                 lma = NULL;
7519         else if (rc != 0)
7520                 GOTO(out, rc);
7521
7522         /*
7523          * We need to ensure that the name entry is still valid.
7524          * Because it may be removed or renamed by other already.
7525          *
7526          * The unlink or rename operation will start journal before PDO lock,
7527          * so to avoid deadlock, here we need to start journal handle before
7528          * related PDO lock also. But because we do not know whether there
7529          * will be something to be repaired before PDO lock, we just start
7530          * journal without conditions.
7531          *
7532          * We may need to remove the name entry firstly, then insert back.
7533          * One credit is for user quota file update.
7534          * One credit is for group quota file update.
7535          * Two credits are for dirty inode.
7536          */
7537         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
7538                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
7539
7540         if (dev->od_dirent_journal != 0) {
7541
7542 again:
7543                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
7544                 if (IS_ERR(jh)) {
7545                         rc = PTR_ERR(jh);
7546                         CDEBUG(D_LFSCK, "%s: fail to start trans for dirent "
7547                                "check_repair, dir = %lu/%u, credits = %d, "
7548                                "name = %.*s, ino = %llu: rc = %d\n",
7549                                devname, dir->i_ino, dir->i_generation, credits,
7550                                ent->oied_namelen, ent->oied_name,
7551                                ent->oied_ino, rc);
7552
7553                         GOTO(out_inode, rc);
7554                 }
7555
7556                 if (obj->oo_hl_head != NULL) {
7557                         hlock = osd_oti_get(env)->oti_hlock;
7558                         /*
7559                          * "0" means exclusive lock for the whole directory.
7560                          * We need to prevent others access such name entry
7561                          * during the delete + insert. Neither HLOCK_ADD nor
7562                          * HLOCK_DEL cannot guarantee the atomicity.
7563                          */
7564                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
7565                 } else {
7566                         down_write(&obj->oo_ext_idx_sem);
7567                 }
7568         } else {
7569                 if (obj->oo_hl_head != NULL) {
7570                         hlock = osd_oti_get(env)->oti_hlock;
7571                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
7572                                            LDISKFS_HLOCK_LOOKUP);
7573                 } else {
7574                         down_read(&obj->oo_ext_idx_sem);
7575                 }
7576         }
7577
7578         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
7579         if (IS_ERR(bh) || le32_to_cpu(de->inode) != inode->i_ino) {
7580                 *attr |= LUDA_IGNORE;
7581
7582                 GOTO(out, rc = 0);
7583         }
7584
7585         /*
7586          * For dotdot entry, if there is not enough space to hold the
7587          * FID-in-dirent, just keep them there. It only happens when the
7588          * device upgraded from 1.8 or restored from MDT file-level backup.
7589          * For the whole directory, only dotdot entry have no FID-in-dirent
7590          * and needs to get FID from LMA when readdir, it will not affect the
7591          * performance much.
7592          */
7593         if (dotdot && !osd_dotdot_has_space(de)) {
7594                 *attr |= LUDA_UNKNOWN;
7595
7596                 GOTO(out, rc = 0);
7597         }
7598
7599         if (lma != NULL) {
7600                 if (lu_fid_eq(fid, &lma->lma_self_fid))
7601                         GOTO(out, rc = 0);
7602
7603                 if (unlikely(lma->lma_compat & LMAC_NOT_IN_OI)) {
7604                         struct lu_fid *tfid = &lma->lma_self_fid;
7605
7606                         if (likely(dotdot &&
7607                                    fid_seq(tfid) == FID_SEQ_LOCAL_FILE &&
7608                                    fid_oid(tfid) == REMOTE_PARENT_DIR_OID)) {
7609                                 /*
7610                                  * It must be REMOTE_PARENT_DIR and as the
7611                                  * 'dotdot' entry of remote directory
7612                                  */
7613                                 *attr |= LUDA_IGNORE;
7614                         } else {
7615                                 CDEBUG(D_LFSCK, "%s: expect remote agent "
7616                                        "parent directory, but got %.*s under "
7617                                        "dir = %lu/%u with the FID "DFID"\n",
7618                                        devname, ent->oied_namelen,
7619                                        ent->oied_name, dir->i_ino,
7620                                        dir->i_generation, PFID(tfid));
7621
7622                                 *attr |= LUDA_UNKNOWN;
7623                         }
7624
7625                         GOTO(out, rc = 0);
7626                 }
7627         }
7628
7629         if (!fid_is_zero(fid)) {
7630                 rc = osd_verify_ent_by_linkea(env, inode, pfid, ent->oied_name,
7631                                               ent->oied_namelen);
7632                 if (rc == -ENOENT ||
7633                     (rc == -ENODATA &&
7634                      !(dev->od_scrub.os_scrub.os_file.sf_flags & SF_UPGRADE))) {
7635                         /*
7636                          * linkEA does not recognize the dirent entry,
7637                          * it may because the dirent entry corruption
7638                          * and points to other's inode.
7639                          */
7640                         CDEBUG(D_LFSCK, "%s: the target inode does not "
7641                                "recognize the dirent, dir = %lu/%u, "
7642                                " name = %.*s, ino = %llu, "
7643                                DFID": rc = %d\n", devname, dir->i_ino,
7644                                dir->i_generation, ent->oied_namelen,
7645                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
7646                         *attr |= LUDA_UNKNOWN;
7647
7648                         GOTO(out, rc = 0);
7649                 }
7650
7651                 if (rc && rc != -ENODATA) {
7652                         CDEBUG(D_LFSCK, "%s: fail to verify FID in the dirent, "
7653                                "dir = %lu/%u, name = %.*s, ino = %llu, "
7654                                DFID": rc = %d\n", devname, dir->i_ino,
7655                                dir->i_generation, ent->oied_namelen,
7656                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
7657                         *attr |= LUDA_UNKNOWN;
7658
7659                         GOTO(out, rc = 0);
7660                 }
7661         }
7662
7663         if (lma != NULL) {
7664                 /*
7665                  * linkEA recognizes the dirent entry, the FID-in-LMA is
7666                  * valid, trusted, in spite of fid_is_sane(fid) or not.
7667                  */
7668                 if (*attr & LUDA_VERIFY_DRYRUN) {
7669                         *fid = lma->lma_self_fid;
7670                         *attr |= LUDA_REPAIR;
7671
7672                         GOTO(out, rc = 0);
7673                 }
7674
7675                 if (jh == NULL) {
7676                         brelse(bh);
7677                         dev->od_dirent_journal = 1;
7678                         if (hlock != NULL) {
7679                                 ldiskfs_htree_unlock(hlock);
7680                                 hlock = NULL;
7681                         } else {
7682                                 up_read(&obj->oo_ext_idx_sem);
7683                         }
7684
7685                         goto again;
7686                 }
7687
7688                 *fid = lma->lma_self_fid;
7689                 dirty = true;
7690                 /* Update or append the FID-in-dirent. */
7691                 rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
7692                                          bh, de, hlock, dotdot);
7693                 if (rc == 0)
7694                         *attr |= LUDA_REPAIR;
7695                 else
7696                         CDEBUG(D_LFSCK, "%s: fail to re-insert FID after "
7697                                "the dirent, dir = %lu/%u, name = %.*s, "
7698                                "ino = %llu, "DFID": rc = %d\n",
7699                                devname, dir->i_ino, dir->i_generation,
7700                                ent->oied_namelen, ent->oied_name,
7701                                ent->oied_ino, PFID(fid), rc);
7702         } else {
7703                 /* lma is NULL, trust the FID-in-dirent if it is valid. */
7704                 if (*attr & LUDA_VERIFY_DRYRUN) {
7705                         if (fid_is_sane(fid)) {
7706                                 *attr |= LUDA_REPAIR;
7707                         } else if (dev->od_index == 0) {
7708                                 lu_igif_build(fid, inode->i_ino,
7709                                               inode->i_generation);
7710                                 *attr |= LUDA_UPGRADE;
7711                         }
7712
7713                         GOTO(out, rc = 0);
7714                 }
7715
7716                 if (jh == NULL) {
7717                         brelse(bh);
7718                         dev->od_dirent_journal = 1;
7719                         if (hlock != NULL) {
7720                                 ldiskfs_htree_unlock(hlock);
7721                                 hlock = NULL;
7722                         } else {
7723                                 up_read(&obj->oo_ext_idx_sem);
7724                         }
7725
7726                         goto again;
7727                 }
7728
7729                 dirty = true;
7730                 if (unlikely(fid_is_sane(fid))) {
7731                         /*
7732                          * FID-in-dirent exists, but FID-in-LMA is lost.
7733                          * Trust the FID-in-dirent, and add FID-in-LMA.
7734                          */
7735                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
7736                         if (rc == 0)
7737                                 *attr |= LUDA_REPAIR;
7738                         else
7739                                 CDEBUG(D_LFSCK, "%s: fail to set LMA for "
7740                                        "update dirent, dir = %lu/%u, "
7741                                        "name = %.*s, ino = %llu, "
7742                                        DFID": rc = %d\n",
7743                                        devname, dir->i_ino, dir->i_generation,
7744                                        ent->oied_namelen, ent->oied_name,
7745                                        ent->oied_ino, PFID(fid), rc);
7746                 } else if (dev->od_index == 0) {
7747                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
7748                         /*
7749                          * It is probably IGIF object. Only aappend the
7750                          * FID-in-dirent. OI scrub will process FID-in-LMA.
7751                          */
7752                         rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
7753                                                  bh, de, hlock, dotdot);
7754                         if (rc == 0)
7755                                 *attr |= LUDA_UPGRADE;
7756                         else
7757                                 CDEBUG(D_LFSCK, "%s: fail to append IGIF "
7758                                        "after the dirent, dir = %lu/%u, "
7759                                        "name = %.*s, ino = %llu, "
7760                                        DFID": rc = %d\n",
7761                                        devname, dir->i_ino, dir->i_generation,
7762                                        ent->oied_namelen, ent->oied_name,
7763                                        ent->oied_ino, PFID(fid), rc);
7764                 }
7765         }
7766
7767         GOTO(out, rc);
7768
7769 out:
7770         if (!IS_ERR(bh))
7771                 brelse(bh);
7772         if (hlock != NULL) {
7773                 ldiskfs_htree_unlock(hlock);
7774         } else {
7775                 if (dev->od_dirent_journal != 0)
7776                         up_write(&obj->oo_ext_idx_sem);
7777                 else
7778                         up_read(&obj->oo_ext_idx_sem);
7779         }
7780
7781         if (jh != NULL)
7782                 ldiskfs_journal_stop(jh);
7783
7784 out_inode:
7785         iput(inode);
7786         if (rc >= 0 && !dirty)
7787                 dev->od_dirent_journal = 0;
7788         if (ln.ln_name != ent->oied_name)
7789                 kfree(ln.ln_name);
7790
7791         return rc;
7792 }
7793
7794 /**
7795  * Returns the value at current position from iterator's in memory structure.
7796  *
7797  * \param di struct osd_it_ea, iterator's in memory structure
7798  * \param attr attr requested for dirent.
7799  * \param lde lustre dirent
7800  *
7801  * \retval   0 no error and \param lde has correct lustre dirent.
7802  * \retval -ve on error
7803  */
7804 static inline int osd_it_ea_rec(const struct lu_env *env,
7805                                 const struct dt_it *di,
7806                                 struct dt_rec *dtrec, __u32 attr)
7807 {
7808         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
7809         struct osd_object      *obj   = it->oie_obj;
7810         struct osd_device      *dev   = osd_obj2dev(obj);
7811         struct osd_thread_info *oti   = osd_oti_get(env);
7812         struct osd_inode_id    *id    = &oti->oti_id;
7813         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
7814         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
7815         __u32 ino = it->oie_dirent->oied_ino;
7816         int rc = 0;
7817
7818         ENTRY;
7819
7820         LASSERT(!is_remote_parent_ino(dev, obj->oo_inode->i_ino));
7821
7822         if (attr & LUDA_VERIFY) {
7823                 if (unlikely(is_remote_parent_ino(dev, ino))) {
7824                         attr |= LUDA_IGNORE;
7825                         /*
7826                          * If the parent is on remote MDT, and there
7827                          * is no FID-in-dirent, then we have to get
7828                          * the parent FID from the linkEA.
7829                          */
7830                         if (!fid_is_sane(fid) &&
7831                             it->oie_dirent->oied_namelen == 2 &&
7832                             it->oie_dirent->oied_name[0] == '.' &&
7833                             it->oie_dirent->oied_name[1] == '.')
7834                                 osd_get_pfid_from_linkea(env, obj, fid);
7835                 } else {
7836                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
7837                                                      &attr);
7838                 }
7839
7840                 if (!fid_is_sane(fid))
7841                         attr |= LUDA_UNKNOWN;
7842         } else {
7843                 attr &= ~LU_DIRENT_ATTRS_MASK;
7844                 if (!fid_is_sane(fid)) {
7845                         bool is_dotdot = false;
7846
7847                         if (it->oie_dirent->oied_namelen == 2 &&
7848                             it->oie_dirent->oied_name[0] == '.' &&
7849                             it->oie_dirent->oied_name[1] == '.')
7850                                 is_dotdot = true;
7851                         /*
7852                          * If the parent is on remote MDT, and there
7853                          * is no FID-in-dirent, then we have to get
7854                          * the parent FID from the linkEA.
7855                          */
7856                         if (is_remote_parent_ino(dev, ino) && is_dotdot) {
7857                                 rc = osd_get_pfid_from_linkea(env, obj, fid);
7858                         } else {
7859                                 if (is_dotdot == false &&
7860                                     CFS_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
7861                                         RETURN(-ENOENT);
7862
7863                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
7864                         }
7865                 }
7866         }
7867
7868         /* Pack the entry anyway, at least the offset is right. */
7869         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
7870                            it->oie_dirent->oied_name,
7871                            it->oie_dirent->oied_namelen,
7872                            it->oie_dirent->oied_type, attr);
7873
7874         RETURN(rc > 0 ? 0 : rc);
7875 }
7876
7877 /**
7878  * Returns the record size size at current position.
7879  *
7880  * This function will return record(lu_dirent) size in bytes.
7881  *
7882  * \param[in] env       execution environment
7883  * \param[in] di        iterator's in memory structure
7884  * \param[in] attr      attribute of the entry, only requires LUDA_TYPE to
7885  *                      calculate the lu_dirent size.
7886  *
7887  * \retval      record size(in bytes & in memory) of the current lu_dirent
7888  *              entry.
7889  */
7890 static int osd_it_ea_rec_size(const struct lu_env *env, const struct dt_it *di,
7891                               __u32 attr)
7892 {
7893         struct osd_it_ea *it = (struct osd_it_ea *)di;
7894
7895         return lu_dirent_calc_size(it->oie_dirent->oied_namelen, attr);
7896 }
7897
7898 /**
7899  * Returns a cookie for current position of the iterator head, so that
7900  * user can use this cookie to load/start the iterator next time.
7901  *
7902  * \param di iterator's in memory structure
7903  *
7904  * \retval cookie for current position, on success
7905  */
7906 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
7907 {
7908         struct osd_it_ea *it = (struct osd_it_ea *)di;
7909
7910         return it->oie_dirent->oied_off;
7911 }
7912
7913 /**
7914  * It calls osd_ldiskfs_it_fill() which will use ->iterate*()
7915  * to load a directory entry at a time and stored it i inn,
7916  * in iterator's in-memory data structure.
7917  *
7918  * \param di struct osd_it_ea, iterator's in memory structure
7919  *
7920  * \retval +ve on success
7921  * \retval -ve on error
7922  */
7923 static int osd_it_ea_load(const struct lu_env *env,
7924                           const struct dt_it *di, __u64 hash)
7925 {
7926         struct osd_it_ea *it = (struct osd_it_ea *)di;
7927         int rc;
7928
7929         ENTRY;
7930         it->oie_file->f_pos = hash;
7931
7932         rc =  osd_ldiskfs_it_fill(env, di);
7933         if (rc > 0)
7934                 rc = -ENODATA;
7935
7936         if (rc == 0)
7937                 rc = 1;
7938
7939         RETURN(rc);
7940 }
7941
7942 int osd_olc_lookup(const struct lu_env *env, struct osd_object *obj,
7943                           u64 iversion, struct dt_rec *rec,
7944                           const struct lu_name *ln, int *result)
7945 {
7946         struct osd_thread_info *oti = osd_oti_get(env);
7947         struct osd_lookup_cache *olc = oti->oti_lookup_cache;
7948         struct osd_device *osd = osd_obj2dev(obj);
7949         struct osd_lookup_cache_object *cobj = &oti->oti_cobj;
7950         int i;
7951
7952         if (unlikely(olc == NULL))
7953                 return 0;
7954
7955         if (unlikely(atomic_read(&osd_mount_seq) != olc->olc_mount_seq)) {
7956                 /*
7957                  * umount has happened, a new OSD could land to the previous
7958                  * address so we can't use it any more, invalidate our cache
7959                  */
7960                 memset(olc, 0, sizeof(*olc));
7961                 olc->olc_mount_seq = atomic_read(&osd_mount_seq);
7962                 return 0;
7963         }
7964
7965         memset(cobj, 0, sizeof(*cobj));
7966         cobj->lco_osd = osd;
7967         cobj->lco_ino = obj->oo_inode->i_ino;
7968         cobj->lco_gen = obj->oo_inode->i_generation;
7969         cobj->lco_version = iversion;
7970
7971         for (i = 0; i < OSD_LOOKUP_CACHE_MAX; i++) {
7972                 struct osd_lookup_cache_entry *entry;
7973
7974                 entry = &olc->olc_entry[i];
7975                 /* compare if osd/ino/generation/version match */
7976                 if (memcmp(&entry->lce_obj, cobj, sizeof(*cobj)) != 0)
7977                         continue;
7978                 if (entry->lce_namelen != ln->ln_namelen)
7979                         continue;
7980                 if (memcmp(entry->lce_name, ln->ln_name, ln->ln_namelen) != 0)
7981                         continue;
7982                 /* match */
7983                 memcpy(rec, &entry->lce_fid, sizeof(entry->lce_fid));
7984                 *result = entry->lce_rc;
7985                 return 1;
7986         }
7987         return 0;
7988 }
7989
7990 void osd_olc_save(const struct lu_env *env, struct osd_object *obj,
7991                           struct dt_rec *rec, const struct lu_name *ln,
7992                           const int result, u64 iversion)
7993 {
7994         struct osd_thread_info *oti = osd_oti_get(env);
7995         struct osd_lookup_cache_entry *entry;
7996         struct osd_lookup_cache *olc;
7997
7998         if (unlikely(oti->oti_lookup_cache == NULL)) {
7999                 OBD_ALLOC_PTR(oti->oti_lookup_cache);
8000                 if (oti->oti_lookup_cache == NULL)
8001                         return;
8002         }
8003
8004         olc = oti->oti_lookup_cache;
8005         if (unlikely(atomic_read(&osd_mount_seq) != olc->olc_mount_seq)) {
8006                 memset(olc, 0, sizeof(*olc));
8007                 olc->olc_mount_seq = atomic_read(&osd_mount_seq);
8008         }
8009
8010         entry = &olc->olc_entry[olc->olc_cur];
8011
8012         /* invaliate cache slot if needed */
8013         if (entry->lce_obj.lco_osd)
8014                 memset(&entry->lce_obj, 0, sizeof(entry->lce_obj));
8015
8016         /* XXX: some kind of LRU */
8017         entry->lce_obj.lco_osd = osd_obj2dev(obj);
8018         entry->lce_obj.lco_ino = obj->oo_inode->i_ino;
8019         entry->lce_obj.lco_gen = obj->oo_inode->i_generation;
8020         entry->lce_obj.lco_version = iversion;
8021
8022         LASSERT(ln->ln_namelen <= LDISKFS_NAME_LEN + 1);
8023         entry->lce_namelen = ln->ln_namelen;
8024         memcpy(entry->lce_name, ln->ln_name, ln->ln_namelen);
8025         memcpy(&entry->lce_fid, rec, sizeof(entry->lce_fid));
8026         entry->lce_rc = result;
8027
8028         if (++olc->olc_cur == OSD_LOOKUP_CACHE_MAX)
8029                 olc->olc_cur = 0;
8030 }
8031
8032 /**
8033  * Index lookup function for interoperability mode (b11826).
8034  *
8035  * \param key,  key i.e. file name to be searched
8036  *
8037  * \retval +ve, on success
8038  * \retval -ve, on error
8039  */
8040 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
8041                                struct dt_rec *rec, const struct dt_key *key)
8042 {
8043         struct osd_object *obj = osd_dt_obj(dt);
8044         struct lu_name ln;
8045         int rc, result;
8046         u64 iversion;
8047
8048         ENTRY;
8049
8050         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
8051         LINVRNT(osd_invariant(obj));
8052
8053         rc = obj_name2lu_name(obj, (char *)key, strlen((char *)key), &ln);
8054         if (rc)
8055                 RETURN(rc);
8056
8057         /*
8058          * grab version before actual lookup, so that we recognize potential
8059          * insert between osd_ea_lookup_rec() and osd_olc_save()
8060          */
8061         iversion = inode_peek_iversion(obj->oo_inode);
8062
8063         if (osd_olc_lookup(env, obj, iversion, rec, &ln, &result))
8064                 GOTO(out, rc = result);
8065
8066         rc = osd_ea_lookup_rec(env, obj, rec, &ln);
8067         if (rc == 0)
8068                 rc = 1;
8069
8070         osd_olc_save(env, obj, rec, &ln, rc, iversion);
8071
8072 out:
8073         if (ln.ln_name != (char *)key)
8074                 kfree(ln.ln_name);
8075         RETURN(rc);
8076 }
8077
8078 /**
8079  * Index and Iterator operations for interoperability
8080  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
8081  */
8082 static const struct dt_index_operations osd_index_ea_ops = {
8083         .dio_lookup         = osd_index_ea_lookup,
8084         .dio_declare_insert = osd_index_declare_ea_insert,
8085         .dio_insert         = osd_index_ea_insert,
8086         .dio_declare_delete = osd_index_declare_ea_delete,
8087         .dio_delete         = osd_index_ea_delete,
8088         .dio_it     = {
8089                 .init     = osd_it_ea_init,
8090                 .fini     = osd_it_ea_fini,
8091                 .get      = osd_it_ea_get,
8092                 .put      = osd_it_ea_put,
8093                 .next     = osd_it_ea_next,
8094                 .key      = osd_it_ea_key,
8095                 .key_size = osd_it_ea_key_size,
8096                 .rec      = osd_it_ea_rec,
8097                 .rec_size = osd_it_ea_rec_size,
8098                 .store    = osd_it_ea_store,
8099                 .load     = osd_it_ea_load
8100         }
8101 };
8102
8103 static void *osd_key_init(const struct lu_context *ctx,
8104                           struct lu_context_key *key)
8105 {
8106         struct osd_thread_info *info;
8107
8108         OBD_ALLOC_PTR(info);
8109         if (info == NULL)
8110                 return ERR_PTR(-ENOMEM);
8111
8112         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
8113         if (info->oti_it_ea_buf == NULL)
8114                 goto out_free_info;
8115
8116         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
8117
8118         info->oti_hlock = ldiskfs_htree_lock_alloc();
8119         if (info->oti_hlock == NULL)
8120                 goto out_free_ea;
8121
8122         return info;
8123
8124 out_free_ea:
8125         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
8126 out_free_info:
8127         OBD_FREE_PTR(info);
8128         return ERR_PTR(-ENOMEM);
8129 }
8130
8131 static void osd_key_fini(const struct lu_context *ctx,
8132                          struct lu_context_key *key, void *data)
8133 {
8134         struct osd_thread_info *info = data;
8135         struct ldiskfs_inode_info *lli = LDISKFS_I(info->oti_inode);
8136         struct osd_idmap_cache *idc = info->oti_ins_cache;
8137
8138         if (info->oti_dio_pages) {
8139                 int i;
8140                 for (i = 0; i < PTLRPC_MAX_BRW_PAGES; i++) {
8141                         struct page *page = info->oti_dio_pages[i];
8142                         if (page) {
8143                                 LASSERT(PagePrivate2(page));
8144                                 LASSERT(PageLocked(page));
8145                                 ClearPagePrivate2(page);
8146                                 unlock_page(page);
8147                                 __free_page(page);
8148                         }
8149                 }
8150                 OBD_FREE_PTR_ARRAY_LARGE(info->oti_dio_pages,
8151                                          PTLRPC_MAX_BRW_PAGES);
8152         }
8153
8154         if (info->oti_inode != NULL)
8155                 OBD_FREE_PTR(lli);
8156         if (info->oti_hlock != NULL)
8157                 ldiskfs_htree_lock_free(info->oti_hlock);
8158         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
8159         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
8160         lu_buf_free(&info->oti_iobuf.dr_lnb_buf);
8161         lu_buf_free(&info->oti_big_buf);
8162         if (idc != NULL) {
8163                 LASSERT(info->oti_ins_cache_size > 0);
8164                 OBD_FREE_PTR_ARRAY_LARGE(idc, info->oti_ins_cache_size);
8165                 info->oti_ins_cache = NULL;
8166                 info->oti_ins_cache_size = 0;
8167         }
8168         if (info->oti_lookup_cache)
8169                 OBD_FREE_PTR(info->oti_lookup_cache);
8170         OBD_FREE_PTR(info);
8171 }
8172
8173 static void osd_key_exit(const struct lu_context *ctx,
8174                          struct lu_context_key *key, void *data)
8175 {
8176         struct osd_thread_info *info = data;
8177         struct osd_lookup_cache *olc = info->oti_lookup_cache;
8178
8179         if (olc)
8180                 memset(olc, 0, sizeof(*olc));
8181         LASSERT(info->oti_r_locks == 0);
8182         LASSERT(info->oti_w_locks == 0);
8183         LASSERT(info->oti_txns    == 0);
8184         LASSERTF(info->oti_dio_pages_used == 0, "%d\n",
8185                  info->oti_dio_pages_used);
8186 }
8187
8188 /* type constructor/destructor: osd_type_init, osd_type_fini */
8189 LU_TYPE_INIT_FINI(osd, &osd_key);
8190
8191 struct lu_context_key osd_key = {
8192         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
8193         .lct_init = osd_key_init,
8194         .lct_fini = osd_key_fini,
8195         .lct_exit = osd_key_exit
8196 };
8197
8198
8199 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
8200                            const char *name, struct lu_device *next)
8201 {
8202         struct osd_device *osd = osd_dev(d);
8203
8204         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname)) >=
8205             sizeof(osd->od_svname))
8206                 return -E2BIG;
8207         return osd_procfs_init(osd, name);
8208 }
8209
8210 static int osd_fid_init(const struct lu_env *env, struct osd_device *osd)
8211 {
8212         struct seq_server_site *ss = osd_seq_site(osd);
8213         int rc = 0;
8214
8215         ENTRY;
8216
8217         if (osd->od_is_ost || osd->od_cl_seq != NULL)
8218                 RETURN(0);
8219
8220         if (unlikely(ss == NULL))
8221                 RETURN(-ENODEV);
8222
8223         OBD_ALLOC_PTR(osd->od_cl_seq);
8224         if (osd->od_cl_seq == NULL)
8225                 RETURN(-ENOMEM);
8226
8227         seq_client_init(osd->od_cl_seq, NULL, LUSTRE_SEQ_METADATA,
8228                         osd->od_svname, ss->ss_server_seq);
8229
8230         if (ss->ss_node_id == 0) {
8231                 /*
8232                  * If the OSD on the sequence controller(MDT0), then allocate
8233                  * sequence here, otherwise allocate sequence after connected
8234                  * to MDT0 (see mdt_register_lwp_callback()).
8235                  */
8236                 rc = seq_server_alloc_meta(osd->od_cl_seq->lcs_srv,
8237                                    &osd->od_cl_seq->lcs_space, env);
8238         }
8239
8240         RETURN(rc);
8241 }
8242
8243 static void osd_fid_fini(const struct lu_env *env, struct osd_device *osd)
8244 {
8245         if (osd->od_cl_seq == NULL)
8246                 return;
8247
8248         seq_client_fini(osd->od_cl_seq);
8249         OBD_FREE_PTR(osd->od_cl_seq);
8250         osd->od_cl_seq = NULL;
8251 }
8252
8253 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
8254 {
8255         ENTRY;
8256
8257         /* shutdown quota slave instance associated with the device */
8258         if (o->od_quota_slave_md != NULL) {
8259                 struct qsd_instance *qsd = o->od_quota_slave_md;
8260
8261                 o->od_quota_slave_md = NULL;
8262                 qsd_fini(env, qsd);
8263         }
8264
8265         if (o->od_quota_slave_dt != NULL) {
8266                 struct qsd_instance *qsd = o->od_quota_slave_dt;
8267
8268                 o->od_quota_slave_dt = NULL;
8269                 qsd_fini(env, qsd);
8270         }
8271
8272         osd_fid_fini(env, o);
8273         osd_scrub_cleanup(env, o);
8274
8275         RETURN(0);
8276 }
8277
8278 #ifdef HAVE_FLUSH_DELAYED_FPUT
8279 # define cfs_flush_delayed_fput() flush_delayed_fput()
8280 #else
8281 void (*cfs_flush_delayed_fput)(void);
8282 #endif /* HAVE_FLUSH_DELAYED_FPUT */
8283
8284 static void osd_umount(const struct lu_env *env, struct osd_device *o)
8285 {
8286         ENTRY;
8287
8288         atomic_inc(&osd_mount_seq);
8289
8290         if (o->od_mnt != NULL) {
8291                 shrink_dcache_sb(osd_sb(o));
8292                 osd_sync(env, &o->od_dt_dev);
8293                 wait_event(o->od_commit_cb_done,
8294                           !atomic_read(&o->od_commit_cb_in_flight));
8295
8296                 mntput(o->od_mnt);
8297                 o->od_mnt = NULL;
8298         }
8299
8300         /* to be sure all delayed fput are finished */
8301         cfs_flush_delayed_fput();
8302
8303         EXIT;
8304 }
8305
8306 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 53, 0)
8307 # ifndef LDISKFS_HAS_INCOMPAT_FEATURE
8308 /* Newer kernels provide the ldiskfs_set_feature_largedir() wrapper already,
8309  * which calls ldiskfs_update_dynamic_rev() to update ancient filesystems.
8310  * All ldiskfs filesystems are already v2, so it is a no-op and unnecessary.
8311  * This avoids maintaining patches to export this otherwise-useless function.
8312  */
8313 void ldiskfs_update_dynamic_rev(struct super_block *sb)
8314 {
8315         /* do nothing */
8316 }
8317 # endif
8318 #endif
8319
8320 static int osd_mount(const struct lu_env *env,
8321                      struct osd_device *o, struct lustre_cfg *cfg)
8322 {
8323         const char *name = lustre_cfg_string(cfg, 0);
8324         const char *dev = lustre_cfg_string(cfg, 1);
8325         const char *opts;
8326         unsigned long page, s_flags = 0, lmd_flags = 0;
8327         struct page *__page;
8328         struct file_system_type *type;
8329         char *options = NULL;
8330         const char *str;
8331         struct osd_thread_info *info = osd_oti_get(env);
8332         struct lu_fid *fid = &info->oti_fid;
8333         struct inode *inode;
8334         int rc = 0, force_over_1024tb = 0;
8335
8336         ENTRY;
8337
8338         if (o->od_mnt != NULL)
8339                 RETURN(0);
8340
8341         if (strlen(dev) >= sizeof(o->od_mntdev))
8342                 RETURN(-E2BIG);
8343         strcpy(o->od_mntdev, dev);
8344
8345         str = lustre_cfg_buf(cfg, 2);
8346         sscanf(str, "%lu:%lu", &s_flags, &lmd_flags);
8347
8348         opts = lustre_cfg_string(cfg, 3);
8349 #ifdef __BIG_ENDIAN
8350         if (opts == NULL || strstr(opts, "bigendian_extents") == NULL) {
8351                 CERROR("%s: device %s extents feature is not guaranteed to "
8352                        "work on big-endian systems. Use \"bigendian_extents\" "
8353                        "mount option to override.\n", name, dev);
8354                 RETURN(-EINVAL);
8355         }
8356 #endif
8357 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
8358         if (opts != NULL && strstr(opts, "force_over_128tb") != NULL) {
8359                 CWARN("force_over_128tb option is deprecated.  Filesystems smaller than 1024TB can be created without any force option. Use force_over_1024tb option for filesystems larger than 1024TB.\n");
8360         }
8361 #endif
8362 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 1, 53, 0)
8363         if (opts != NULL && strstr(opts, "force_over_256tb") != NULL) {
8364                 CWARN("force_over_256tb option is deprecated.  Filesystems smaller than 1024TB can be created without any force options. Use force_over_1024tb option for filesystems larger than 1024TB.\n");
8365         }
8366 #endif
8367 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 53, 0)
8368         if (opts != NULL && strstr(opts, "force_over_512tb") != NULL) {
8369                 CWARN("force_over_512tb option is deprecated.  Filesystems smaller than 1024TB can be created without any force options. Use force_over_1024tb option for filesystems larger than 1024TB.\n");
8370         }
8371 #endif
8372
8373         if (opts != NULL && strstr(opts, "force_over_1024tb") != NULL)
8374                 force_over_1024tb = 1;
8375
8376         __page = alloc_page(GFP_KERNEL);
8377         if (__page == NULL)
8378                 GOTO(out, rc = -ENOMEM);
8379         page = (unsigned long)page_address(__page);
8380         options = (char *)page;
8381         *options = '\0';
8382         if (opts != NULL) {
8383                 /* strip out the options for back compatiblity */
8384                 static const char * const sout[] = {
8385                         "mballoc",
8386                         "iopen",
8387                         "noiopen",
8388                         "iopen_nopriv",
8389                         "extents",
8390                         "noextents",
8391                         /* strip out option we processed in osd */
8392                         "bigendian_extents",
8393                         "force_over_128tb",
8394                         "force_over_256tb",
8395                         "force_over_512tb",
8396                         "force_over_1024tb",
8397                         "resetoi",
8398                         NULL
8399                 };
8400                 strncat(options, opts, PAGE_SIZE);
8401                 for (rc = 0, str = options; sout[rc]; ) {
8402                         char *op = strstr(str, sout[rc]);
8403
8404                         if (op == NULL) {
8405                                 rc++;
8406                                 str = options;
8407                                 continue;
8408                         }
8409                         if (op == options || *(op - 1) == ',') {
8410                                 str = op + strlen(sout[rc]);
8411                                 if (*str == ',' || *str == '\0') {
8412                                         *str == ',' ? str++ : str;
8413                                         memmove(op, str, strlen(str) + 1);
8414                                 }
8415                         }
8416                         for (str = op; *str != ',' && *str != '\0'; str++)
8417                                 ;
8418                 }
8419         } else {
8420                 strncat(options, "user_xattr,acl", PAGE_SIZE);
8421         }
8422
8423         /* Glom up mount options */
8424         if (*options != '\0')
8425                 strncat(options, ",", PAGE_SIZE);
8426         strncat(options, "no_mbcache,nodelalloc", PAGE_SIZE);
8427
8428         type = get_fs_type("ldiskfs");
8429         if (!type) {
8430                 CERROR("%s: cannot find ldiskfs module\n", name);
8431                 GOTO(out, rc = -ENODEV);
8432         }
8433
8434         s_flags |= SB_KERNMOUNT;
8435         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
8436         module_put(type->owner);
8437
8438         if (IS_ERR(o->od_mnt)) {
8439                 rc = PTR_ERR(o->od_mnt);
8440                 o->od_mnt = NULL;
8441                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
8442                 GOTO(out, rc);
8443         }
8444
8445         if (ldiskfs_blocks_count(LDISKFS_SB(osd_sb(o))->s_es) <<
8446                                  osd_sb(o)->s_blocksize_bits > 1024ULL << 40 &&
8447                                  force_over_1024tb == 0) {
8448                 CERROR("%s: device %s LDISKFS has not been tested on filesystems larger than 1024TB and may cause data corruption. Use 'force_over_1024tb' mount option to override.\n",
8449                        name, dev);
8450                 GOTO(out_mnt, rc = -EINVAL);
8451         }
8452
8453         if (test_bit(LMD_FLG_DEV_RDONLY, &lmd_flags)) {
8454                 LCONSOLE_WARN("%s: not support dev_rdonly on this device\n",
8455                               name);
8456
8457                 GOTO(out_mnt, rc = -EOPNOTSUPP);
8458         }
8459
8460         if (!ldiskfs_has_feature_journal(o->od_mnt->mnt_sb)) {
8461                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
8462                 GOTO(out_mnt, rc = -EINVAL);
8463         }
8464
8465         if (ldiskfs_has_feature_fast_commit(o->od_mnt->mnt_sb)) {
8466                 CERROR("%s: device %s is mounted with fast_commit that breaks recovery\n",
8467                        name, dev);
8468                 GOTO(out_mnt, rc = -EOPNOTSUPP);
8469         }
8470
8471 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 53, 0)
8472 #ifdef LDISKFS_MOUNT_DIRDATA
8473         if (ldiskfs_has_feature_dirdata(o->od_mnt->mnt_sb))
8474                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
8475         else if (strstr(name, "MDT")) /* don't complain for MGT or OSTs */
8476                 CWARN("%s: device %s was upgraded from Lustre-1.x without "
8477                       "enabling the dirdata feature. If you do not want to "
8478                       "downgrade to Lustre-1.x again, you can enable it via "
8479                       "'tune2fs -O dirdata device'\n", name, dev);
8480 #endif
8481         /* enable large_dir on MDTs to avoid REMOTE_PARENT_DIR overflow,
8482          * and on very large OSTs to avoid object directory overflow */
8483         if (unlikely(!ldiskfs_has_feature_largedir(o->od_mnt->mnt_sb) &&
8484                      !strstr(name, "MGS"))) {
8485                 ldiskfs_set_feature_largedir(o->od_mnt->mnt_sb);
8486                 LCONSOLE_INFO("%s: enabled 'large_dir' feature on device %s\n",
8487                               name, dev);
8488         }
8489 #endif
8490         inode = osd_sb(o)->s_root->d_inode;
8491         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
8492         if (!o->od_dt_dev.dd_rdonly) {
8493                 rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
8494                 if (rc != 0) {
8495                         CERROR("%s: failed to set lma on %s root inode\n",
8496                                name, dev);
8497                         GOTO(out_mnt, rc);
8498                 }
8499         }
8500
8501         if (test_bit(LMD_FLG_NOSCRUB, &lmd_flags))
8502                 o->od_scrub.os_scrub.os_auto_scrub_interval = AS_NEVER;
8503
8504         if (blk_queue_nonrot(bdev_get_queue(osd_sb(o)->s_bdev))) {
8505                 /* do not use pagecache with flash-backed storage */
8506                 o->od_writethrough_cache = 0;
8507                 o->od_read_cache = 0;
8508         }
8509
8510         GOTO(out, rc = 0);
8511
8512 out_mnt:
8513         mntput(o->od_mnt);
8514         o->od_mnt = NULL;
8515
8516 out:
8517         if (__page)
8518                 __free_page(__page);
8519
8520         return rc;
8521 }
8522
8523 static struct lu_device *osd_device_fini(const struct lu_env *env,
8524                                          struct lu_device *d)
8525 {
8526         struct osd_device *o = osd_dev(d);
8527
8528         ENTRY;
8529
8530         osd_index_backup(env, o, false);
8531         osd_shutdown(env, o);
8532         osd_procfs_fini(o);
8533         if (o->od_oi_table != NULL)
8534                 osd_oi_fini(osd_oti_get(env), o);
8535         if (o->od_extent_bytes_percpu)
8536                 free_percpu(o->od_extent_bytes_percpu);
8537         osd_obj_map_fini(o);
8538         osd_umount(env, o);
8539
8540         RETURN(NULL);
8541 }
8542
8543 static int osd_device_init0(const struct lu_env *env,
8544                             struct osd_device *o,
8545                             struct lustre_cfg *cfg)
8546 {
8547         struct lu_device *l = osd2lu_dev(o);
8548         struct osd_thread_info *info;
8549         int cplen = 0;
8550         char *opts = NULL;
8551         bool restored = false;
8552         int rc;
8553
8554         /* if the module was re-loaded, env can loose its keys */
8555         rc = lu_env_refill((struct lu_env *)env);
8556         if (rc)
8557                 GOTO(out, rc);
8558         info = osd_oti_get(env);
8559         LASSERT(info);
8560
8561         l->ld_ops = &osd_lu_ops;
8562         o->od_dt_dev.dd_ops = &osd_dt_ops;
8563
8564         spin_lock_init(&o->od_osfs_lock);
8565         mutex_init(&o->od_otable_mutex);
8566         INIT_LIST_HEAD(&o->od_orphan_list);
8567         INIT_LIST_HEAD(&o->od_index_backup_list);
8568         INIT_LIST_HEAD(&o->od_index_restore_list);
8569         spin_lock_init(&o->od_lock);
8570         o->od_index_backup_policy = LIBP_NONE;
8571         o->od_t10_type = 0;
8572         init_waitqueue_head(&o->od_commit_cb_done);
8573
8574         o->od_read_cache = 1;
8575         o->od_writethrough_cache = 1;
8576         o->od_enable_projid_xattr = 0;
8577         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
8578         o->od_readcache_max_iosize = OSD_READCACHE_MAX_IO_MB << 20;
8579         o->od_writethrough_max_iosize = OSD_WRITECACHE_MAX_IO_MB << 20;
8580         o->od_scrub.os_scrub.os_auto_scrub_interval = AS_DEFAULT;
8581         /* default fallocate to unwritten extents: LU-14326/LU-14333 */
8582         o->od_fallocate_zero_blocks = 0;
8583
8584         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
8585                         sizeof(o->od_svname));
8586         if (cplen >= sizeof(o->od_svname)) {
8587                 rc = -E2BIG;
8588                 GOTO(out, rc);
8589         }
8590
8591         o->od_index_backup_stop = 0;
8592         o->od_index = -1; /* -1 means index is invalid */
8593         rc = server_name2index(o->od_svname, &o->od_index, NULL);
8594         if (rc == LDD_F_SV_TYPE_OST)
8595                 o->od_is_ost = 1;
8596
8597         o->od_full_scrub_ratio = OFSR_DEFAULT;
8598         o->od_full_scrub_threshold_rate = FULL_SCRUB_THRESHOLD_RATE_DEFAULT;
8599         rc = osd_mount(env, o, cfg);
8600         if (rc != 0)
8601                 GOTO(out, rc);
8602
8603         /* Can only check block device after mount */
8604         o->od_nonrotational =
8605                 blk_queue_nonrot(bdev_get_queue(osd_sb(o)->s_bdev));
8606
8607         rc = osd_obj_map_init(env, o);
8608         if (rc != 0)
8609                 GOTO(out_mnt, rc);
8610
8611         rc = lu_site_init(&o->od_site, l);
8612         if (rc != 0)
8613                 GOTO(out_compat, rc);
8614         o->od_site.ls_bottom_dev = l;
8615
8616         rc = lu_site_init_finish(&o->od_site);
8617         if (rc != 0)
8618                 GOTO(out_site, rc);
8619
8620         opts = lustre_cfg_string(cfg, 3);
8621         if (opts && strstr(opts, "resetoi"))
8622                 restored = true;
8623
8624         INIT_LIST_HEAD(&o->od_ios_list);
8625
8626         rc = lprocfs_init_brw_stats(&o->od_brw_stats);
8627         if (rc)
8628                 GOTO(out_brw_stats, rc);
8629
8630         /* setup scrub, including OI files initialization */
8631         o->od_in_init = 1;
8632         rc = osd_scrub_setup(env, o, restored);
8633         o->od_in_init = 0;
8634         if (rc < 0)
8635                 GOTO(out_brw_stats, rc);
8636
8637         rc = osd_procfs_init(o, o->od_svname);
8638         if (rc != 0) {
8639                 CERROR("%s: can't initialize procfs: rc = %d\n",
8640                        o->od_svname, rc);
8641                 GOTO(out_scrub, rc);
8642         }
8643
8644         LASSERT(l->ld_site->ls_linkage.next != NULL);
8645         LASSERT(l->ld_site->ls_linkage.prev != NULL);
8646
8647         /* initialize quota slave instance */
8648         /* currently it's no need to prepare qsd_instance_md for OST */
8649         if (!o->od_is_ost) {
8650                 o->od_quota_slave_md = qsd_init(env, o->od_svname,
8651                                                 &o->od_dt_dev, o->od_proc_entry,
8652                                                 true, true);
8653                 if (IS_ERR(o->od_quota_slave_md)) {
8654                         rc = PTR_ERR(o->od_quota_slave_md);
8655                         o->od_quota_slave_md = NULL;
8656                         GOTO(out_procfs, rc);
8657                 }
8658         }
8659
8660         o->od_quota_slave_dt = qsd_init(env, o->od_svname, &o->od_dt_dev,
8661                                         o->od_proc_entry, false, true);
8662
8663         if (IS_ERR(o->od_quota_slave_dt)) {
8664                 if (o->od_quota_slave_md != NULL) {
8665                         qsd_fini(env, o->od_quota_slave_md);
8666                         o->od_quota_slave_md = NULL;
8667                 }
8668
8669                 rc = PTR_ERR(o->od_quota_slave_dt);
8670                 o->od_quota_slave_dt = NULL;
8671                 GOTO(out_procfs, rc);
8672         }
8673
8674         o->od_extent_bytes_percpu = alloc_percpu(unsigned int);
8675         if (!o->od_extent_bytes_percpu) {
8676                 rc = -ENOMEM;
8677                 GOTO(out_procfs, rc);
8678         }
8679
8680         RETURN(0);
8681
8682 out_procfs:
8683         osd_procfs_fini(o);
8684 out_scrub:
8685         osd_scrub_cleanup(env, o);
8686 out_brw_stats:
8687         lprocfs_fini_brw_stats(&o->od_brw_stats);
8688 out_site:
8689         lu_site_fini(&o->od_site);
8690 out_compat:
8691         osd_obj_map_fini(o);
8692 out_mnt:
8693         osd_umount(env, o);
8694 out:
8695         return rc;
8696 }
8697
8698 static struct lu_device *osd_device_alloc(const struct lu_env *env,
8699                                           struct lu_device_type *t,
8700                                           struct lustre_cfg *cfg)
8701 {
8702         struct osd_device *o;
8703         int rc;
8704
8705         OBD_ALLOC_PTR(o);
8706         if (o == NULL)
8707                 return ERR_PTR(-ENOMEM);
8708
8709         rc = dt_device_init(&o->od_dt_dev, t);
8710         if (rc == 0) {
8711                 /*
8712                  * Because the ctx might be revived in dt_device_init,
8713                  * refill the env here
8714                  */
8715                 lu_env_refill((struct lu_env *)env);
8716                 rc = osd_device_init0(env, o, cfg);
8717                 if (rc)
8718                         dt_device_fini(&o->od_dt_dev);
8719         }
8720
8721         if (unlikely(rc != 0))
8722                 OBD_FREE_PTR(o);
8723
8724         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
8725 }
8726
8727 static struct lu_device *osd_device_free(const struct lu_env *env,
8728                                          struct lu_device *d)
8729 {
8730         struct osd_device *o = osd_dev(d);
8731
8732         ENTRY;
8733
8734         /* XXX: make osd top device in order to release reference */
8735         d->ld_site->ls_top_dev = d;
8736         lu_site_purge(env, d->ld_site, -1);
8737         lu_site_print(env, d->ld_site, &d->ld_site->ls_obj_hash.nelems,
8738                       D_ERROR, lu_cdebug_printer);
8739         lu_site_fini(&o->od_site);
8740         dt_device_fini(&o->od_dt_dev);
8741         OBD_FREE_PTR(o);
8742         RETURN(NULL);
8743 }
8744
8745 static int osd_process_config(const struct lu_env *env,
8746                               struct lu_device *d, struct lustre_cfg *cfg)
8747 {
8748         struct osd_device *o = osd_dev(d);
8749         ssize_t count;
8750         int rc;
8751
8752         ENTRY;
8753
8754         switch (cfg->lcfg_command) {
8755         case LCFG_SETUP:
8756                 rc = osd_mount(env, o, cfg);
8757                 break;
8758         case LCFG_CLEANUP:
8759                 /*
8760                  * For the case LCFG_PRE_CLEANUP is not called in advance,
8761                  * that may happend if hit failure during mount process.
8762                  */
8763                 osd_index_backup(env, o, false);
8764                 lu_dev_del_linkage(d->ld_site, d);
8765                 rc = osd_shutdown(env, o);
8766                 break;
8767         case LCFG_PARAM:
8768                 LASSERT(&o->od_dt_dev);
8769                 count  = class_modify_config(cfg, PARAM_OSD,
8770                                              &o->od_dt_dev.dd_kobj);
8771                 if (count < 0)
8772                         count = class_modify_config(cfg, PARAM_OST,
8773                                                     &o->od_dt_dev.dd_kobj);
8774                 rc = count > 0 ? 0 : count;
8775                 break;
8776         case LCFG_PRE_CLEANUP:
8777                 osd_scrub_stop(o);
8778                 osd_index_backup(env, o,
8779                                  o->od_index_backup_policy != LIBP_NONE);
8780                 rc = 0;
8781                 break;
8782         default:
8783                 rc = -ENOSYS;
8784         }
8785
8786         RETURN(rc);
8787 }
8788
8789 static int osd_recovery_complete(const struct lu_env *env,
8790                                  struct lu_device *d)
8791 {
8792         struct osd_device *osd = osd_dev(d);
8793         int rc = 0;
8794
8795         ENTRY;
8796
8797         if (osd->od_quota_slave_md == NULL && osd->od_quota_slave_dt == NULL)
8798                 RETURN(0);
8799
8800         /*
8801          * start qsd instance on recovery completion, this notifies the quota
8802          * slave code that we are about to process new requests now
8803          */
8804         rc = qsd_start(env, osd->od_quota_slave_dt);
8805         if (rc == 0 && osd->od_quota_slave_md != NULL)
8806                 rc = qsd_start(env, osd->od_quota_slave_md);
8807
8808         RETURN(rc);
8809 }
8810
8811 /*
8812  * we use exports to track all osd users
8813  */
8814 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
8815                            struct obd_device *obd, struct obd_uuid *cluuid,
8816                            struct obd_connect_data *data, void *localdata)
8817 {
8818         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8819         struct lustre_handle conn;
8820         int rc;
8821
8822         ENTRY;
8823
8824         CDEBUG(D_CONFIG, "connect #%d\n", atomic_read(&osd->od_connects));
8825
8826         rc = class_connect(&conn, obd, cluuid);
8827         if (rc)
8828                 RETURN(rc);
8829
8830         *exp = class_conn2export(&conn);
8831
8832         atomic_inc(&osd->od_connects);
8833
8834         RETURN(0);
8835 }
8836
8837 /*
8838  * once last export (we don't count self-export) disappeared
8839  * osd can be released
8840  */
8841 static int osd_obd_disconnect(struct obd_export *exp)
8842 {
8843         struct obd_device *obd = exp->exp_obd;
8844         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8845         int rc, release = 0;
8846
8847         ENTRY;
8848
8849         /* Only disconnect the underlying layers on the final disconnect. */
8850         release = atomic_dec_and_test(&osd->od_connects);
8851
8852         rc = class_disconnect(exp); /* bz 9811 */
8853
8854         if (rc == 0 && release)
8855                 class_manual_cleanup(obd);
8856         RETURN(rc);
8857 }
8858
8859 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
8860                        struct lu_device *dev)
8861 {
8862         struct osd_device *osd = osd_dev(dev);
8863         struct lr_server_data *lsd =
8864                         &osd->od_dt_dev.dd_lu_dev.ld_site->ls_tgt->lut_lsd;
8865         int result = 0;
8866
8867         ENTRY;
8868
8869         if (osd->od_quota_slave_md != NULL) {
8870                 /* set up quota slave objects for inode */
8871                 result = qsd_prepare(env, osd->od_quota_slave_md);
8872                 if (result != 0)
8873                         RETURN(result);
8874         }
8875
8876         if (osd->od_quota_slave_dt != NULL) {
8877                 /* set up quota slave objects for block */
8878                 result = qsd_prepare(env, osd->od_quota_slave_dt);
8879                 if (result != 0)
8880                         RETURN(result);
8881         }
8882
8883
8884         if (lsd->lsd_feature_incompat & OBD_COMPAT_OST) {
8885 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 52, 0)
8886                 if (lsd->lsd_feature_rocompat & OBD_ROCOMPAT_IDX_IN_IDIF) {
8887                         osd->od_index_in_idif = 1;
8888                 } else {
8889                         osd->od_index_in_idif = 0;
8890                         result = osd_register_proc_index_in_idif(osd);
8891                         if (result != 0)
8892                                 RETURN(result);
8893                 }
8894 #else
8895                 osd->od_index_in_idif = 1;
8896 #endif
8897         }
8898
8899         result = osd_fid_init(env, osd);
8900
8901         RETURN(result);
8902 }
8903
8904 /**
8905  * Implementation of lu_device_operations::ldo_fid_alloc() for OSD
8906  *
8907  * Allocate FID.
8908  *
8909  * see include/lu_object.h for the details.
8910  */
8911 static int osd_fid_alloc(const struct lu_env *env, struct lu_device *d,
8912                          struct lu_fid *fid, struct lu_object *parent,
8913                          const struct lu_name *name)
8914 {
8915         struct osd_device *osd = osd_dev(d);
8916
8917         return seq_client_alloc_fid(env, osd->od_cl_seq, fid);
8918 }
8919
8920 static const struct lu_object_operations osd_lu_obj_ops = {
8921         .loo_object_init      = osd_object_init,
8922         .loo_object_delete    = osd_object_delete,
8923         .loo_object_release   = osd_object_release,
8924         .loo_object_free      = osd_object_free,
8925         .loo_object_print     = osd_object_print,
8926         .loo_object_invariant = osd_object_invariant
8927 };
8928
8929 const struct lu_device_operations osd_lu_ops = {
8930         .ldo_object_alloc      = osd_object_alloc,
8931         .ldo_process_config    = osd_process_config,
8932         .ldo_recovery_complete = osd_recovery_complete,
8933         .ldo_prepare           = osd_prepare,
8934         .ldo_fid_alloc         = osd_fid_alloc,
8935 };
8936
8937 static const struct lu_device_type_operations osd_device_type_ops = {
8938         .ldto_init = osd_type_init,
8939         .ldto_fini = osd_type_fini,
8940
8941         .ldto_start = osd_type_start,
8942         .ldto_stop  = osd_type_stop,
8943
8944         .ldto_device_alloc = osd_device_alloc,
8945         .ldto_device_free  = osd_device_free,
8946
8947         .ldto_device_init = osd_device_init,
8948         .ldto_device_fini = osd_device_fini
8949 };
8950
8951 static struct lu_device_type osd_device_type = {
8952         .ldt_tags     = LU_DEVICE_DT,
8953         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
8954         .ldt_ops      = &osd_device_type_ops,
8955         .ldt_ctx_tags = LCT_LOCAL,
8956 };
8957
8958 static int osd_health_check(const struct lu_env *env, struct obd_device *obd)
8959 {
8960         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8961         struct super_block *sb = osd_sb(osd);
8962
8963         return (osd->od_mnt == NULL || sb->s_flags & SB_RDONLY);
8964 }
8965
8966 /*
8967  * lprocfs legacy support.
8968  */
8969 static const struct obd_ops osd_obd_device_ops = {
8970         .o_owner = THIS_MODULE,
8971         .o_connect      = osd_obd_connect,
8972         .o_disconnect   = osd_obd_disconnect,
8973         .o_health_check = osd_health_check,
8974 };
8975
8976 static ssize_t delayed_unlink_mb_show(struct kobject *kobj,
8977                                       struct attribute *attr, char *buf)
8978 {
8979         return snprintf(buf, PAGE_SIZE, "%d\n",
8980                         ldiskfs_delayed_unlink_blocks >> 11);
8981 }
8982
8983 static ssize_t delayed_unlink_mb_store(struct kobject *kobj,
8984                                        struct attribute *attr,
8985                                        const char *buffer, size_t count)
8986 {
8987         u64 delayed_unlink_bytes;
8988         int rc;
8989
8990         rc = sysfs_memparse(buffer, count, &delayed_unlink_bytes, "MiB");
8991         if (rc)
8992                 return rc;
8993
8994         ldiskfs_delayed_unlink_blocks = delayed_unlink_bytes >> 9;
8995
8996         return count;
8997 }
8998 LUSTRE_RW_ATTR(delayed_unlink_mb);
8999
9000
9001 static ssize_t track_declares_assert_show(struct kobject *kobj,
9002                                    struct attribute *attr,
9003                                    char *buf)
9004 {
9005         return sprintf(buf, "%d\n", ldiskfs_track_declares_assert);
9006 }
9007
9008 static ssize_t track_declares_assert_store(struct kobject *kobj,
9009                                            struct attribute *attr,
9010                                            const char *buffer, size_t count)
9011 {
9012         bool track_declares_assert;
9013         int rc;
9014
9015         rc = kstrtobool(buffer, &track_declares_assert);
9016         if (rc)
9017                 return rc;
9018
9019         ldiskfs_track_declares_assert = track_declares_assert;
9020
9021         return count;
9022 }
9023 LUSTRE_RW_ATTR(track_declares_assert);
9024
9025 static int __init osd_init(void)
9026 {
9027         struct kobject *kobj;
9028         int rc;
9029
9030         BUILD_BUG_ON(BH_DXLock >=
9031                      sizeof(((struct buffer_head *)0)->b_state) * 8);
9032 #if !defined(CONFIG_DEBUG_MUTEXES) && !defined(CONFIG_DEBUG_SPINLOCK)
9033         /* please, try to keep osd_thread_info smaller than a page */
9034         BUILD_BUG_ON(sizeof(struct osd_thread_info) > PAGE_SIZE);
9035 #endif
9036
9037         rc = libcfs_setup();
9038         if (rc)
9039                 return rc;
9040
9041         osd_oi_mod_init();
9042
9043         rc = lu_kmem_init(ldiskfs_caches);
9044         if (rc)
9045                 return rc;
9046
9047         rc = class_register_type(&osd_obd_device_ops, NULL, true,
9048                                  LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
9049         if (rc) {
9050                 lu_kmem_fini(ldiskfs_caches);
9051                 return rc;
9052         }
9053
9054         kobj = kset_find_obj(lustre_kset, LUSTRE_OSD_LDISKFS_NAME);
9055         if (kobj) {
9056                 rc = sysfs_create_file(kobj,
9057                                        &lustre_attr_track_declares_assert.attr);
9058                 if (rc) {
9059                         CWARN("%s: track_declares_assert sysfs registration failed: rc = %d\n",
9060                               "osd-ldiskfs", rc);
9061                         rc = 0;
9062                 }
9063
9064                 rc = sysfs_create_file(kobj,
9065                                        &lustre_attr_delayed_unlink_mb.attr);
9066                 if (rc) {
9067                         CWARN("%s: delayed_unlink_mb registration failed: rc = %d\n",
9068                               "osd-ldiskfs", rc);
9069                         rc = 0;
9070                 }
9071
9072                 kobject_put(kobj);
9073         }
9074
9075 #ifndef HAVE_FLUSH_DELAYED_FPUT
9076         if (unlikely(cfs_flush_delayed_fput == NULL))
9077                 cfs_flush_delayed_fput =
9078                         cfs_kallsyms_lookup_name("flush_delayed_fput");
9079 #endif
9080
9081         return rc;
9082 }
9083
9084 static void __exit osd_exit(void)
9085 {
9086         struct kobject *kobj;
9087
9088         kobj = kset_find_obj(lustre_kset, LUSTRE_OSD_LDISKFS_NAME);
9089         if (kobj) {
9090                 sysfs_remove_file(kobj,
9091                                   &lustre_attr_track_declares_assert.attr);
9092                 kobject_put(kobj);
9093         }
9094         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
9095         lu_kmem_fini(ldiskfs_caches);
9096 }
9097
9098 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
9099 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
9100 MODULE_VERSION(LUSTRE_VERSION_STRING);
9101 MODULE_LICENSE("GPL");
9102
9103 module_init(osd_init);
9104 module_exit(osd_exit);