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