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