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