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