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