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