Whamcloud - gitweb
c711e39ec21a473283bfd02976a326eb935f8f03
[fs/lustre-release.git] / lustre / lod / lod_lov.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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright  2009 Sun Microsystems, Inc. All rights reserved
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * lustre/lod/lod_lov.c
30  *
31  * A set of helpers to maintain Logical Object Volume (LOV)
32  * Extended Attribute (EA) and known OST targets
33  *
34  * Author: Alex Zhuravlev <alexey.zhuravlev@intel.com>
35  */
36
37 #define DEBUG_SUBSYSTEM S_MDS
38
39 #include <obd_class.h>
40 #include <lustre_lfsck.h>
41 #include <lustre_lmv.h>
42 #include <lustre_swab.h>
43
44 #include "lod_internal.h"
45
46 /**
47  * Increase reference count on the target table.
48  *
49  * Increase reference count on the target table usage to prevent racing with
50  * addition/deletion. Any function that expects the table to remain
51  * stationary must take a ref.
52  *
53  * \param[in] ltd       target table (lod_ost_descs or lod_mdt_descs)
54  */
55 void lod_getref(struct lod_tgt_descs *ltd)
56 {
57         down_read(&ltd->ltd_rw_sem);
58         mutex_lock(&ltd->ltd_mutex);
59         ltd->ltd_refcount++;
60         mutex_unlock(&ltd->ltd_mutex);
61 }
62
63 /**
64  * Decrease reference count on the target table.
65  *
66  * Companion of lod_getref() to release a reference on the target table.
67  * If this is the last reference and the OST entry was scheduled for deletion,
68  * the descriptor is removed from the table.
69  *
70  * \param[in] lod       LOD device from which we release a reference
71  * \param[in] ltd       target table (lod_ost_descs or lod_mdt_descs)
72  */
73 void lod_putref(struct lod_device *lod, struct lod_tgt_descs *ltd)
74 {
75         mutex_lock(&ltd->ltd_mutex);
76         ltd->ltd_refcount--;
77         if (ltd->ltd_refcount == 0 && ltd->ltd_death_row) {
78                 struct lod_tgt_desc *tgt_desc, *tmp;
79                 struct list_head kill;
80                 unsigned int idx;
81
82                 CDEBUG(D_CONFIG, "destroying %d ltd desc\n",
83                        ltd->ltd_death_row);
84
85                 INIT_LIST_HEAD(&kill);
86
87                 cfs_foreach_bit(ltd->ltd_tgt_bitmap, idx) {
88                         tgt_desc = LTD_TGT(ltd, idx);
89                         LASSERT(tgt_desc);
90
91                         if (!tgt_desc->ltd_reap)
92                                 continue;
93
94                         list_add(&tgt_desc->ltd_kill, &kill);
95                         LTD_TGT(ltd, idx) = NULL;
96                         /*FIXME: only support ost pool for now */
97                         if (ltd == &lod->lod_ost_descs) {
98                                 lod_ost_pool_remove(&lod->lod_pool_info, idx);
99                                 if (tgt_desc->ltd_active)
100                                         lod->lod_desc.ld_active_tgt_count--;
101                         }
102                         ltd->ltd_tgtnr--;
103                         cfs_bitmap_clear(ltd->ltd_tgt_bitmap, idx);
104                         ltd->ltd_death_row--;
105                 }
106                 mutex_unlock(&ltd->ltd_mutex);
107                 up_read(&ltd->ltd_rw_sem);
108
109                 list_for_each_entry_safe(tgt_desc, tmp, &kill, ltd_kill) {
110                         int rc;
111                         list_del(&tgt_desc->ltd_kill);
112                         if (ltd == &lod->lod_ost_descs) {
113                                 /* remove from QoS structures */
114                                 rc = qos_del_tgt(lod, tgt_desc);
115                                 if (rc)
116                                         CERROR("%s: qos_del_tgt(%s) failed:"
117                                                "rc = %d\n",
118                                                lod2obd(lod)->obd_name,
119                                               obd_uuid2str(&tgt_desc->ltd_uuid),
120                                                rc);
121                         }
122                         rc = obd_disconnect(tgt_desc->ltd_exp);
123                         if (rc)
124                                 CERROR("%s: failed to disconnect %s: rc = %d\n",
125                                        lod2obd(lod)->obd_name,
126                                        obd_uuid2str(&tgt_desc->ltd_uuid), rc);
127                         OBD_FREE_PTR(tgt_desc);
128                 }
129         } else {
130                 mutex_unlock(&ltd->ltd_mutex);
131                 up_read(&ltd->ltd_rw_sem);
132         }
133 }
134
135 /**
136  * Expand size of target table.
137  *
138  * When the target table is full, we have to extend the table. To do so,
139  * we allocate new memory with some reserve, move data from the old table
140  * to the new one and release memory consumed by the old table.
141  * Notice we take ltd_rw_sem exclusively to ensure atomic switch.
142  *
143  * \param[in] ltd               target table
144  * \param[in] newsize           new size of the table
145  *
146  * \retval                      0 on success
147  * \retval                      -ENOMEM if reallocation failed
148  */
149 static int ltd_bitmap_resize(struct lod_tgt_descs *ltd, __u32 newsize)
150 {
151         struct cfs_bitmap *new_bitmap, *old_bitmap = NULL;
152         int           rc = 0;
153         ENTRY;
154
155         /* grab write reference on the lod. Relocating the array requires
156          * exclusive access */
157
158         down_write(&ltd->ltd_rw_sem);
159         if (newsize <= ltd->ltd_tgts_size)
160                 /* someone else has already resize the array */
161                 GOTO(out, rc = 0);
162
163         /* allocate new bitmap */
164         new_bitmap = CFS_ALLOCATE_BITMAP(newsize);
165         if (!new_bitmap)
166                 GOTO(out, rc = -ENOMEM);
167
168         if (ltd->ltd_tgts_size > 0) {
169                 /* the bitmap already exists, we need
170                  * to copy data from old one */
171                 cfs_bitmap_copy(new_bitmap, ltd->ltd_tgt_bitmap);
172                 old_bitmap = ltd->ltd_tgt_bitmap;
173         }
174
175         ltd->ltd_tgts_size  = newsize;
176         ltd->ltd_tgt_bitmap = new_bitmap;
177
178         if (old_bitmap)
179                 CFS_FREE_BITMAP(old_bitmap);
180
181         CDEBUG(D_CONFIG, "tgt size: %d\n", ltd->ltd_tgts_size);
182
183         EXIT;
184 out:
185         up_write(&ltd->ltd_rw_sem);
186         return rc;
187 }
188
189 /**
190  * Connect LOD to a new OSP and add it to the target table.
191  *
192  * Connect to the OSP device passed, initialize all the internal
193  * structures related to the device and add it to the target table.
194  *
195  * \param[in] env               execution environment for this thread
196  * \param[in] lod               LOD device to be connected to the new OSP
197  * \param[in] osp               name of OSP device name to be added
198  * \param[in] index             index of the new target
199  * \param[in] gen               target's generation number
200  * \param[in] tgt_index         OSP's group
201  * \param[in] type              type of device (mdc or osc)
202  * \param[in] active            state of OSP: 0 - inactive, 1 - active
203  *
204  * \retval                      0 if added successfully
205  * \retval                      negative error number on failure
206  */
207 int lod_add_device(const struct lu_env *env, struct lod_device *lod,
208                    char *osp, unsigned index, unsigned gen, int tgt_index,
209                    char *type, int active)
210 {
211         struct obd_connect_data *data = NULL;
212         struct obd_export       *exp = NULL;
213         struct obd_device       *obd;
214         struct lu_device        *lu_dev;
215         struct dt_device        *dt_dev;
216         int                      rc;
217         struct lod_tgt_desc     *tgt_desc;
218         struct lod_tgt_descs    *ltd;
219         struct lustre_cfg       *lcfg;
220         struct obd_uuid         obd_uuid;
221         bool                    for_ost;
222         bool lock = false;
223         bool connected = false;
224         ENTRY;
225
226         CDEBUG(D_CONFIG, "osp:%s idx:%d gen:%d\n", osp, index, gen);
227
228         if (gen <= 0) {
229                 CERROR("request to add OBD %s with invalid generation: %d\n",
230                        osp, gen);
231                 RETURN(-EINVAL);
232         }
233
234         obd_str2uuid(&obd_uuid, osp);
235
236         obd = class_find_client_obd(&obd_uuid, LUSTRE_OSP_NAME,
237                                 &lod->lod_dt_dev.dd_lu_dev.ld_obd->obd_uuid);
238         if (obd == NULL) {
239                 CERROR("can't find %s device\n", osp);
240                 RETURN(-EINVAL);
241         }
242
243         LASSERT(obd->obd_lu_dev != NULL);
244         LASSERT(obd->obd_lu_dev->ld_site == lod->lod_dt_dev.dd_lu_dev.ld_site);
245
246         lu_dev = obd->obd_lu_dev;
247         dt_dev = lu2dt_dev(lu_dev);
248
249         OBD_ALLOC_PTR(data);
250         if (data == NULL)
251                 GOTO(out_cleanup, rc = -ENOMEM);
252
253         data->ocd_connect_flags = OBD_CONNECT_INDEX | OBD_CONNECT_VERSION;
254         data->ocd_version = LUSTRE_VERSION_CODE;
255         data->ocd_index = index;
256
257         if (strcmp(LUSTRE_OSC_NAME, type) == 0) {
258                 for_ost = true;
259                 data->ocd_connect_flags |= OBD_CONNECT_AT |
260                                            OBD_CONNECT_FULL20 |
261                                            OBD_CONNECT_INDEX |
262 #ifdef HAVE_LRU_RESIZE_SUPPORT
263                                            OBD_CONNECT_LRU_RESIZE |
264 #endif
265                                            OBD_CONNECT_MDS |
266                                            OBD_CONNECT_REQPORTAL |
267                                            OBD_CONNECT_SKIP_ORPHAN |
268                                            OBD_CONNECT_FID |
269                                            OBD_CONNECT_LVB_TYPE |
270                                            OBD_CONNECT_VERSION |
271                                            OBD_CONNECT_PINGLESS |
272                                            OBD_CONNECT_LFSCK |
273                                            OBD_CONNECT_BULK_MBITS;
274
275                 data->ocd_group = tgt_index;
276                 ltd = &lod->lod_ost_descs;
277         } else {
278                 struct obd_import *imp = obd->u.cli.cl_import;
279
280                 for_ost = false;
281                 data->ocd_ibits_known = MDS_INODELOCK_UPDATE;
282                 data->ocd_connect_flags |= OBD_CONNECT_ACL |
283                                            OBD_CONNECT_IBITS |
284                                            OBD_CONNECT_MDS_MDS |
285                                            OBD_CONNECT_FID |
286                                            OBD_CONNECT_AT |
287                                            OBD_CONNECT_FULL20 |
288                                            OBD_CONNECT_LFSCK |
289                                            OBD_CONNECT_BULK_MBITS;
290                 spin_lock(&imp->imp_lock);
291                 imp->imp_server_timeout = 1;
292                 spin_unlock(&imp->imp_lock);
293                 imp->imp_client->cli_request_portal = OUT_PORTAL;
294                 CDEBUG(D_OTHER, "%s: Set 'mds' portal and timeout\n",
295                       obd->obd_name);
296                 ltd = &lod->lod_mdt_descs;
297         }
298
299         rc = obd_connect(env, &exp, obd, &obd->obd_uuid, data, NULL);
300         OBD_FREE_PTR(data);
301         if (rc) {
302                 CERROR("%s: cannot connect to next dev %s (%d)\n",
303                        obd->obd_name, osp, rc);
304                 GOTO(out_cleanup, rc);
305         }
306         connected = true;
307
308         /* Allocate ost descriptor and fill it */
309         OBD_ALLOC_PTR(tgt_desc);
310         if (!tgt_desc)
311                 GOTO(out_cleanup, rc = -ENOMEM);
312
313         tgt_desc->ltd_tgt    = dt_dev;
314         tgt_desc->ltd_exp    = exp;
315         tgt_desc->ltd_uuid   = obd->u.cli.cl_target_uuid;
316         tgt_desc->ltd_gen    = gen;
317         tgt_desc->ltd_index  = index;
318         tgt_desc->ltd_active = active;
319
320         lod_getref(ltd);
321         if (index >= ltd->ltd_tgts_size) {
322                 /* we have to increase the size of the lod_osts array */
323                 __u32  newsize;
324
325                 newsize = max(ltd->ltd_tgts_size, (__u32)2);
326                 while (newsize < index + 1)
327                         newsize = newsize << 1;
328
329                 /* lod_bitmap_resize() needs lod_rw_sem
330                  * which we hold with th reference */
331                 lod_putref(lod, ltd);
332
333                 rc = ltd_bitmap_resize(ltd, newsize);
334                 if (rc)
335                         GOTO(out_desc, rc);
336
337                 lod_getref(ltd);
338         }
339
340         mutex_lock(&ltd->ltd_mutex);
341         lock = true;
342         if (cfs_bitmap_check(ltd->ltd_tgt_bitmap, index)) {
343                 CERROR("%s: device %d is registered already\n", obd->obd_name,
344                        index);
345                 GOTO(out_mutex, rc = -EEXIST);
346         }
347
348         if (ltd->ltd_tgt_idx[index / TGT_PTRS_PER_BLOCK] == NULL) {
349                 OBD_ALLOC_PTR(ltd->ltd_tgt_idx[index / TGT_PTRS_PER_BLOCK]);
350                 if (ltd->ltd_tgt_idx[index / TGT_PTRS_PER_BLOCK] == NULL) {
351                         CERROR("can't allocate index to add %s\n",
352                                obd->obd_name);
353                         GOTO(out_mutex, rc = -ENOMEM);
354                 }
355         }
356
357         if (for_ost) {
358                 /* pool and qos are not supported for MDS stack yet */
359                 rc = lod_ost_pool_add(&lod->lod_pool_info, index,
360                                       lod->lod_osts_size);
361                 if (rc) {
362                         CERROR("%s: can't set up pool, failed with %d\n",
363                                obd->obd_name, rc);
364                         GOTO(out_mutex, rc);
365                 }
366
367                 rc = qos_add_tgt(lod, tgt_desc);
368                 if (rc) {
369                         CERROR("%s: qos_add_tgt failed with %d\n",
370                                 obd->obd_name, rc);
371                         GOTO(out_pool, rc);
372                 }
373
374                 /* The new OST is now a full citizen */
375                 if (index >= lod->lod_desc.ld_tgt_count)
376                         lod->lod_desc.ld_tgt_count = index + 1;
377                 if (active)
378                         lod->lod_desc.ld_active_tgt_count++;
379         }
380
381         LTD_TGT(ltd, index) = tgt_desc;
382         cfs_bitmap_set(ltd->ltd_tgt_bitmap, index);
383         ltd->ltd_tgtnr++;
384         mutex_unlock(&ltd->ltd_mutex);
385         lod_putref(lod, ltd);
386         lock = false;
387         if (lod->lod_recovery_completed)
388                 lu_dev->ld_ops->ldo_recovery_complete(env, lu_dev);
389
390         if (!for_ost && lod->lod_initialized) {
391                 rc = lod_sub_init_llog(env, lod, tgt_desc->ltd_tgt);
392                 if (rc != 0) {
393                         CERROR("%s: cannot start llog on %s:rc = %d\n",
394                                lod2obd(lod)->obd_name, osp, rc);
395                         GOTO(out_ltd, rc);
396                 }
397         }
398
399         rc = lfsck_add_target(env, lod->lod_child, dt_dev, exp, index, for_ost);
400         if (rc != 0) {
401                 CERROR("Fail to add LFSCK target: name = %s, type = %s, "
402                        "index = %u, rc = %d\n", osp, type, index, rc);
403                 GOTO(out_fini_llog, rc);
404         }
405         RETURN(rc);
406 out_fini_llog:
407         lod_sub_fini_llog(env, tgt_desc->ltd_tgt,
408                           tgt_desc->ltd_recovery_thread);
409 out_ltd:
410         lod_getref(ltd);
411         mutex_lock(&ltd->ltd_mutex);
412         lock = true;
413         if (!for_ost && LTD_TGT(ltd, index)->ltd_recovery_thread != NULL) {
414                 struct ptlrpc_thread *thread;
415
416                 thread = LTD_TGT(ltd, index)->ltd_recovery_thread;
417                 OBD_FREE_PTR(thread);
418         }
419         ltd->ltd_tgtnr--;
420         cfs_bitmap_clear(ltd->ltd_tgt_bitmap, index);
421         LTD_TGT(ltd, index) = NULL;
422 out_pool:
423         lod_ost_pool_remove(&lod->lod_pool_info, index);
424 out_mutex:
425         if (lock) {
426                 mutex_unlock(&ltd->ltd_mutex);
427                 lod_putref(lod, ltd);
428         }
429 out_desc:
430         OBD_FREE_PTR(tgt_desc);
431 out_cleanup:
432         /* XXX OSP needs us to send down LCFG_CLEANUP because it uses
433          * objects from the MDT stack. See LU-7184. */
434         lcfg = &lod_env_info(env)->lti_lustre_cfg;
435         memset(lcfg, 0, sizeof(*lcfg));
436         lcfg->lcfg_version = LUSTRE_CFG_VERSION;
437         lcfg->lcfg_command = LCFG_CLEANUP;
438         lu_dev->ld_ops->ldo_process_config(env, lu_dev, lcfg);
439
440         if (connected)
441                 obd_disconnect(exp);
442
443         return rc;
444 }
445
446 /**
447  * Schedule target removal from the target table.
448  *
449  * Mark the device as dead. The device is not removed here because it may
450  * still be in use. The device will be removed in lod_putref() when the
451  * last reference is released.
452  *
453  * \param[in] env               execution environment for this thread
454  * \param[in] lod               LOD device the target table belongs to
455  * \param[in] ltd               target table
456  * \param[in] idx               index of the target
457  * \param[in] for_ost           type of the target: 0 - MDT, 1 - OST
458  */
459 static void __lod_del_device(const struct lu_env *env, struct lod_device *lod,
460                              struct lod_tgt_descs *ltd, unsigned idx,
461                              bool for_ost)
462 {
463         LASSERT(LTD_TGT(ltd, idx));
464
465         lfsck_del_target(env, lod->lod_child, LTD_TGT(ltd, idx)->ltd_tgt,
466                          idx, for_ost);
467
468         if (!for_ost && LTD_TGT(ltd, idx)->ltd_recovery_thread != NULL) {
469                 struct ptlrpc_thread *thread;
470
471                 thread = LTD_TGT(ltd, idx)->ltd_recovery_thread;
472                 OBD_FREE_PTR(thread);
473         }
474
475         if (LTD_TGT(ltd, idx)->ltd_reap == 0) {
476                 LTD_TGT(ltd, idx)->ltd_reap = 1;
477                 ltd->ltd_death_row++;
478         }
479 }
480
481 /**
482  * Schedule removal of all the targets from the given target table.
483  *
484  * See more details in the description for __lod_del_device()
485  *
486  * \param[in] env               execution environment for this thread
487  * \param[in] lod               LOD device the target table belongs to
488  * \param[in] ltd               target table
489  * \param[in] for_ost           type of the target: MDT or OST
490  *
491  * \retval                      0 always
492  */
493 int lod_fini_tgt(const struct lu_env *env, struct lod_device *lod,
494                  struct lod_tgt_descs *ltd, bool for_ost)
495 {
496         unsigned int idx;
497
498         if (ltd->ltd_tgts_size <= 0)
499                 return 0;
500         lod_getref(ltd);
501         mutex_lock(&ltd->ltd_mutex);
502         cfs_foreach_bit(ltd->ltd_tgt_bitmap, idx)
503                 __lod_del_device(env, lod, ltd, idx, for_ost);
504         mutex_unlock(&ltd->ltd_mutex);
505         lod_putref(lod, ltd);
506         CFS_FREE_BITMAP(ltd->ltd_tgt_bitmap);
507         for (idx = 0; idx < TGT_PTRS; idx++) {
508                 if (ltd->ltd_tgt_idx[idx])
509                         OBD_FREE_PTR(ltd->ltd_tgt_idx[idx]);
510         }
511         ltd->ltd_tgts_size = 0;
512         return 0;
513 }
514
515 /**
516  * Remove device by name.
517  *
518  * Remove a device identified by \a osp from the target table. Given
519  * the device can be in use, the real deletion happens in lod_putref().
520  *
521  * \param[in] env               execution environment for this thread
522  * \param[in] lod               LOD device to be connected to the new OSP
523  * \param[in] ltd               target table
524  * \param[in] osp               name of OSP device to be removed
525  * \param[in] idx               index of the target
526  * \param[in] gen               generation number, not used currently
527  * \param[in] for_ost           type of the target: 0 - MDT, 1 - OST
528  *
529  * \retval                      0 if the device was scheduled for removal
530  * \retval                      -EINVAL if no device was found
531  */
532 int lod_del_device(const struct lu_env *env, struct lod_device *lod,
533                    struct lod_tgt_descs *ltd, char *osp, unsigned idx,
534                    unsigned gen, bool for_ost)
535 {
536         struct obd_device *obd;
537         int                rc = 0;
538         struct obd_uuid    uuid;
539         ENTRY;
540
541         CDEBUG(D_CONFIG, "osp:%s idx:%d gen:%d\n", osp, idx, gen);
542
543         obd_str2uuid(&uuid, osp);
544
545         obd = class_find_client_obd(&uuid, LUSTRE_OSP_NAME,
546                                    &lod->lod_dt_dev.dd_lu_dev.ld_obd->obd_uuid);
547         if (obd == NULL) {
548                 CERROR("can't find %s device\n", osp);
549                 RETURN(-EINVAL);
550         }
551
552         if (gen <= 0) {
553                 CERROR("%s: request to remove OBD %s with invalid generation %d"
554                        "\n", obd->obd_name, osp, gen);
555                 RETURN(-EINVAL);
556         }
557
558         obd_str2uuid(&uuid,  osp);
559
560         lod_getref(ltd);
561         mutex_lock(&ltd->ltd_mutex);
562         /* check that the index is allocated in the bitmap */
563         if (!cfs_bitmap_check(ltd->ltd_tgt_bitmap, idx) ||
564             !LTD_TGT(ltd, idx)) {
565                 CERROR("%s: device %d is not set up\n", obd->obd_name, idx);
566                 GOTO(out, rc = -EINVAL);
567         }
568
569         /* check that the UUID matches */
570         if (!obd_uuid_equals(&uuid, &LTD_TGT(ltd, idx)->ltd_uuid)) {
571                 CERROR("%s: LOD target UUID %s at index %d does not match %s\n",
572                        obd->obd_name, obd_uuid2str(&LTD_TGT(ltd,idx)->ltd_uuid),
573                        idx, osp);
574                 GOTO(out, rc = -EINVAL);
575         }
576
577         __lod_del_device(env, lod, ltd, idx, for_ost);
578         EXIT;
579 out:
580         mutex_unlock(&ltd->ltd_mutex);
581         lod_putref(lod, ltd);
582         return(rc);
583 }
584
585 /**
586  * Resize per-thread storage to hold specified size.
587  *
588  * A helper function to resize per-thread temporary storage. This storage
589  * is used to process LOV/LVM EAs and may be quite large. We do not want to
590  * allocate/release it every time, so instead we put it into the env and
591  * reallocate on demand. The memory is released when the correspondent thread
592  * is finished.
593  *
594  * \param[in] info              LOD-specific storage in the environment
595  * \param[in] size              new size to grow the buffer to
596
597  * \retval                      0 on success, -ENOMEM if reallocation failed
598  */
599 int lod_ea_store_resize(struct lod_thread_info *info, size_t size)
600 {
601         __u32 round = size_roundup_power2(size);
602
603         if (info->lti_ea_store) {
604                 LASSERT(info->lti_ea_store_size);
605                 LASSERT(info->lti_ea_store_size < round);
606                 CDEBUG(D_INFO, "EA store size %d is not enough, need %d\n",
607                        info->lti_ea_store_size, round);
608                 OBD_FREE_LARGE(info->lti_ea_store, info->lti_ea_store_size);
609                 info->lti_ea_store = NULL;
610                 info->lti_ea_store_size = 0;
611         }
612
613         OBD_ALLOC_LARGE(info->lti_ea_store, round);
614         if (info->lti_ea_store == NULL)
615                 RETURN(-ENOMEM);
616         info->lti_ea_store_size = round;
617
618         RETURN(0);
619 }
620
621 static void lod_free_comp_buffer(struct lod_layout_component *entries,
622                                  __u16 count, __u32 bufsize)
623 {
624         struct lod_layout_component *entry;
625         int i;
626
627         for (i = 0; i < count; i++) {
628                 entry = &entries[i];
629                 if (entry->llc_pool != NULL)
630                         lod_set_pool(&entry->llc_pool, NULL);
631                 if (entry->llc_ostlist.op_array)
632                         OBD_FREE(entry->llc_ostlist.op_array,
633                                  entry->llc_ostlist.op_size);
634                 LASSERT(entry->llc_stripe == NULL);
635                 LASSERT(entry->llc_stripes_allocated == 0);
636         }
637
638         if (bufsize != 0)
639                 OBD_FREE_LARGE(entries, bufsize);
640 }
641
642 void lod_free_def_comp_entries(struct lod_default_striping *lds)
643 {
644         lod_free_comp_buffer(lds->lds_def_comp_entries,
645                              lds->lds_def_comp_size_cnt,
646                              size_roundup_power2(
647                                      sizeof(*lds->lds_def_comp_entries) *
648                                      lds->lds_def_comp_size_cnt));
649         lds->lds_def_comp_entries = NULL;
650         lds->lds_def_comp_cnt = 0;
651         lds->lds_def_striping_is_composite = 0;
652         lds->lds_def_comp_size_cnt = 0;
653 }
654
655 /**
656  * Resize per-thread storage to hold default striping component entries
657  *
658  * A helper function to resize per-thread temporary storage. This storage
659  * is used to hold default LOV/LVM EAs and may be quite large. We do not want
660  * to allocate/release it every time, so instead we put it into the env and
661  * reallocate it on demand. The memory is released when the correspondent
662  * thread is finished.
663  *
664  * \param[in,out] lds           default striping
665  * \param[in] count             new component count to grow the buffer to
666
667  * \retval                      0 on success, -ENOMEM if reallocation failed
668  */
669 int lod_def_striping_comp_resize(struct lod_default_striping *lds, __u16 count)
670 {
671         struct lod_layout_component *entries;
672         __u32 new = size_roundup_power2(sizeof(*lds->lds_def_comp_entries) *
673                                         count);
674         __u32 old = size_roundup_power2(sizeof(*lds->lds_def_comp_entries) *
675                                         lds->lds_def_comp_size_cnt);
676
677         if (new <= old)
678                 return 0;
679
680         OBD_ALLOC_LARGE(entries, new);
681         if (entries == NULL)
682                 return -ENOMEM;
683
684         if (lds->lds_def_comp_entries != NULL) {
685                 CDEBUG(D_INFO, "default striping component size %d is not "
686                        "enough, need %d\n", old, new);
687                 lod_free_def_comp_entries(lds);
688         }
689
690         lds->lds_def_comp_entries = entries;
691         lds->lds_def_comp_size_cnt = count;
692
693         RETURN(0);
694 }
695
696 void lod_free_comp_entries(struct lod_object *lo)
697 {
698         if (lo->ldo_mirrors) {
699                 OBD_FREE(lo->ldo_mirrors,
700                          sizeof(*lo->ldo_mirrors) * lo->ldo_mirror_count);
701                 lo->ldo_mirrors = NULL;
702                 lo->ldo_mirror_count = 0;
703         }
704         lod_free_comp_buffer(lo->ldo_comp_entries,
705                              lo->ldo_comp_cnt,
706                              sizeof(*lo->ldo_comp_entries) * lo->ldo_comp_cnt);
707         lo->ldo_comp_entries = NULL;
708         lo->ldo_comp_cnt = 0;
709         lo->ldo_is_composite = 0;
710 }
711
712 int lod_alloc_comp_entries(struct lod_object *lo,
713                            int mirror_count, int comp_count)
714 {
715         LASSERT(comp_count != 0);
716         LASSERT(lo->ldo_comp_cnt == 0 && lo->ldo_comp_entries == NULL);
717
718         if (mirror_count > 0) {
719                 OBD_ALLOC(lo->ldo_mirrors,
720                           sizeof(*lo->ldo_mirrors) * mirror_count);
721                 if (!lo->ldo_mirrors)
722                         return -ENOMEM;
723
724                 lo->ldo_mirror_count = mirror_count;
725         }
726
727         OBD_ALLOC_LARGE(lo->ldo_comp_entries,
728                         sizeof(*lo->ldo_comp_entries) * comp_count);
729         if (lo->ldo_comp_entries == NULL) {
730                 OBD_FREE(lo->ldo_mirrors,
731                          sizeof(*lo->ldo_mirrors) * mirror_count);
732                 lo->ldo_mirror_count = 0;
733                 return -ENOMEM;
734         }
735
736         lo->ldo_comp_cnt = comp_count;
737         return 0;
738 }
739
740 int lod_fill_mirrors(struct lod_object *lo)
741 {
742         struct lod_layout_component *lod_comp;
743         int mirror_idx = -1;
744         __u16 mirror_id = 0xffff;
745         int i;
746         ENTRY;
747
748         LASSERT(equi(!lo->ldo_is_composite, lo->ldo_mirror_count == 0));
749
750         if (!lo->ldo_is_composite)
751                 RETURN(0);
752
753         lod_comp = &lo->ldo_comp_entries[0];
754         for (i = 0; i < lo->ldo_comp_cnt; i++, lod_comp++) {
755                 int stale = !!(lod_comp->llc_flags & LCME_FL_STALE);
756                 int preferred = !!(lod_comp->llc_flags & LCME_FL_PREF_WR);
757
758                 if (mirror_id_of(lod_comp->llc_id) == mirror_id) {
759                         lo->ldo_mirrors[mirror_idx].lme_stale |= stale;
760                         lo->ldo_mirrors[mirror_idx].lme_primary |= preferred;
761                         lo->ldo_mirrors[mirror_idx].lme_end = i;
762                         continue;
763                 }
764
765                 /* new mirror */
766                 ++mirror_idx;
767                 if (mirror_idx >= lo->ldo_mirror_count)
768                         RETURN(-EINVAL);
769
770                 mirror_id = mirror_id_of(lod_comp->llc_id);
771
772                 lo->ldo_mirrors[mirror_idx].lme_id = mirror_id;
773                 lo->ldo_mirrors[mirror_idx].lme_stale = stale;
774                 lo->ldo_mirrors[mirror_idx].lme_primary = preferred;
775                 lo->ldo_mirrors[mirror_idx].lme_start = i;
776                 lo->ldo_mirrors[mirror_idx].lme_end = i;
777         }
778         if (mirror_idx != lo->ldo_mirror_count - 1)
779                 RETURN(-EINVAL);
780
781         RETURN(0);
782 }
783
784 /**
785  * Generate on-disk lov_mds_md structure for each layout component based on
786  * the information in lod_object->ldo_comp_entries[i].
787  *
788  * \param[in] env               execution environment for this thread
789  * \param[in] lo                LOD object
790  * \param[in] comp_idx          index of ldo_comp_entries
791  * \param[in] lmm               buffer to cotain the on-disk lov_mds_md
792  * \param[in|out] lmm_size      buffer size/lmm size
793  * \param[in] is_dir            generate lov ea for dir or file? For dir case,
794  *                              the stripe info is from the default stripe
795  *                              template, which is collected in lod_ah_init(),
796  *                              either from parent object or root object; for
797  *                              file case, it's from the @lo object
798  *
799  * \retval                      0 if on disk structure is created successfully
800  * \retval                      negative error number on failure
801  */
802 static int lod_gen_component_ea(const struct lu_env *env,
803                                 struct lod_object *lo, int comp_idx,
804                                 struct lov_mds_md *lmm, int *lmm_size,
805                                 bool is_dir)
806 {
807         struct lod_thread_info  *info = lod_env_info(env);
808         const struct lu_fid     *fid  = lu_object_fid(&lo->ldo_obj.do_lu);
809         struct lod_device       *lod;
810         struct lov_ost_data_v1  *objs;
811         struct lod_layout_component *lod_comp;
812         __u32   magic;
813         __u16 stripe_count;
814         int     i, rc = 0;
815         ENTRY;
816
817         LASSERT(lo);
818         if (is_dir)
819                 lod_comp =
820                         &lo->ldo_def_striping->lds_def_comp_entries[comp_idx];
821         else
822                 lod_comp = &lo->ldo_comp_entries[comp_idx];
823
824         magic = lod_comp->llc_pool != NULL ? LOV_MAGIC_V3 : LOV_MAGIC_V1;
825         if (lod_comp->llc_pattern == 0) /* default striping */
826                 lod_comp->llc_pattern = LOV_PATTERN_RAID0;
827
828         lmm->lmm_magic = cpu_to_le32(magic);
829         lmm->lmm_pattern = cpu_to_le32(lod_comp->llc_pattern);
830         fid_to_lmm_oi(fid, &lmm->lmm_oi);
831         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_LMMOI))
832                 lmm->lmm_oi.oi.oi_id++;
833         lmm_oi_cpu_to_le(&lmm->lmm_oi, &lmm->lmm_oi);
834
835         lmm->lmm_stripe_size = cpu_to_le32(lod_comp->llc_stripe_size);
836         lmm->lmm_stripe_count = cpu_to_le16(lod_comp->llc_stripe_count);
837         /**
838          * for dir and uninstantiated component, lmm_layout_gen stores
839          * default stripe offset.
840          */
841         lmm->lmm_layout_gen =
842                 (is_dir || !lod_comp_inited(lod_comp)) ?
843                         cpu_to_le16(lod_comp->llc_stripe_offset) :
844                         cpu_to_le16(lod_comp->llc_layout_gen);
845
846         if (magic == LOV_MAGIC_V1) {
847                 objs = &lmm->lmm_objects[0];
848         } else {
849                 struct lov_mds_md_v3 *v3 = (struct lov_mds_md_v3 *)lmm;
850                 size_t cplen = strlcpy(v3->lmm_pool_name,
851                                        lod_comp->llc_pool,
852                                        sizeof(v3->lmm_pool_name));
853                 if (cplen >= sizeof(v3->lmm_pool_name))
854                         RETURN(-E2BIG);
855                 objs = &v3->lmm_objects[0];
856         }
857         stripe_count = lod_comp_entry_stripe_count(lo, lod_comp, is_dir);
858         if (stripe_count == 0 && !is_dir &&
859             !(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
860             !(lod_comp->llc_pattern & LOV_PATTERN_MDT))
861                 RETURN(-E2BIG);
862
863         if (!is_dir && lo->ldo_is_composite)
864                 lod_comp_shrink_stripe_count(lod_comp, &stripe_count);
865
866         if (is_dir || lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
867                 GOTO(done, rc = 0);
868
869         /* generate ost_idx of this component stripe */
870         lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
871         for (i = 0; i < stripe_count; i++) {
872                 struct dt_object *object;
873                 __u32 ost_idx = (__u32)-1UL;
874                 int type = LU_SEQ_RANGE_OST;
875
876                 if (lod_comp->llc_stripe && lod_comp->llc_stripe[i]) {
877                         object = lod_comp->llc_stripe[i];
878                         /* instantiated component */
879                         info->lti_fid = *lu_object_fid(&object->do_lu);
880
881                         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_MULTIPLE_REF) &&
882                             comp_idx == 0) {
883                                 if (cfs_fail_val == 0)
884                                         cfs_fail_val = info->lti_fid.f_oid;
885                                 else if (i == 0)
886                                         info->lti_fid.f_oid = cfs_fail_val;
887                         }
888
889                         rc = fid_to_ostid(&info->lti_fid, &info->lti_ostid);
890                         LASSERT(rc == 0);
891
892                         ostid_cpu_to_le(&info->lti_ostid, &objs[i].l_ost_oi);
893                         objs[i].l_ost_gen = cpu_to_le32(0);
894                         if (OBD_FAIL_CHECK(OBD_FAIL_MDS_FLD_LOOKUP))
895                                 rc = -ENOENT;
896                         else
897                                 rc = lod_fld_lookup(env, lod, &info->lti_fid,
898                                                     &ost_idx, &type);
899                         if (rc < 0) {
900                                 CERROR("%s: Can not locate "DFID": rc = %d\n",
901                                        lod2obd(lod)->obd_name,
902                                        PFID(&info->lti_fid), rc);
903                                 RETURN(rc);
904                         }
905                 } else if (lod_comp->llc_ostlist.op_array &&
906                            lod_comp->llc_ostlist.op_count) {
907                         /* user specified ost list */
908                         ost_idx = lod_comp->llc_ostlist.op_array[i];
909                 }
910                 /*
911                  * with un-instantiated or with no specified ost list
912                  * component, its l_ost_idx does not matter.
913                  */
914                 objs[i].l_ost_idx = cpu_to_le32(ost_idx);
915         }
916 done:
917         if (lmm_size != NULL)
918                 *lmm_size = lov_mds_md_size(stripe_count, magic);
919         RETURN(rc);
920 }
921
922 /**
923  * Generate on-disk lov_mds_md structure based on the information in
924  * the lod_object->ldo_comp_entries.
925  *
926  * \param[in] env               execution environment for this thread
927  * \param[in] lo                LOD object
928  * \param[in] lmm               buffer to cotain the on-disk lov_mds_md
929  * \param[in|out] lmm_size      buffer size/lmm size
930  * \param[in] is_dir            generate lov ea for dir or file? For dir case,
931  *                              the stripe info is from the default stripe
932  *                              template, which is collected in lod_ah_init(),
933  *                              either from parent object or root object; for
934  *                              file case, it's from the @lo object
935  *
936  * \retval                      0 if on disk structure is created successfully
937  * \retval                      negative error number on failure
938  */
939 int lod_generate_lovea(const struct lu_env *env, struct lod_object *lo,
940                        struct lov_mds_md *lmm, int *lmm_size, bool is_dir)
941 {
942         struct lov_comp_md_entry_v1 *lcme;
943         struct lov_comp_md_v1 *lcm;
944         struct lod_layout_component *comp_entries;
945         __u16 comp_cnt, mirror_cnt;
946         bool is_composite, is_foreign = false;
947         int i, rc = 0, offset;
948         ENTRY;
949
950         if (is_dir) {
951                 comp_cnt = lo->ldo_def_striping->lds_def_comp_cnt;
952                 mirror_cnt = lo->ldo_def_striping->lds_def_mirror_cnt;
953                 comp_entries = lo->ldo_def_striping->lds_def_comp_entries;
954                 is_composite =
955                         lo->ldo_def_striping->lds_def_striping_is_composite;
956         } else {
957                 comp_cnt = lo->ldo_comp_cnt;
958                 mirror_cnt = lo->ldo_mirror_count;
959                 comp_entries = lo->ldo_comp_entries;
960                 is_composite = lo->ldo_is_composite;
961                 is_foreign = lo->ldo_is_foreign;
962         }
963
964         LASSERT(lmm_size != NULL);
965
966         if (is_foreign) {
967                 struct lov_foreign_md *lfm;
968
969                 lfm = (struct lov_foreign_md *)lmm;
970                 memcpy(lfm, lo->ldo_foreign_lov, lo->ldo_foreign_lov_size);
971                 /* need to store little-endian */
972                 if (cpu_to_le32(LOV_MAGIC_FOREIGN) != LOV_MAGIC_FOREIGN) {
973                         __swab32s(&lfm->lfm_magic);
974                         __swab32s(&lfm->lfm_length);
975                         __swab32s(&lfm->lfm_type);
976                         __swab32s(&lfm->lfm_flags);
977                 }
978                 *lmm_size = lo->ldo_foreign_lov_size;
979                 RETURN(0);
980         }
981
982         LASSERT(comp_cnt != 0 && comp_entries != NULL);
983
984         if (!is_composite) {
985                 rc = lod_gen_component_ea(env, lo, 0, lmm, lmm_size, is_dir);
986                 RETURN(rc);
987         }
988
989         lcm = (struct lov_comp_md_v1 *)lmm;
990         memset(lcm, 0, sizeof(*lcm));
991
992         lcm->lcm_magic = cpu_to_le32(LOV_MAGIC_COMP_V1);
993         lcm->lcm_entry_count = cpu_to_le16(comp_cnt);
994         lcm->lcm_mirror_count = cpu_to_le16(mirror_cnt - 1);
995         lcm->lcm_flags = cpu_to_le16(lo->ldo_flr_state);
996
997         offset = sizeof(*lcm) + sizeof(*lcme) * comp_cnt;
998         LASSERT(offset % sizeof(__u64) == 0);
999
1000         for (i = 0; i < comp_cnt; i++) {
1001                 struct lod_layout_component *lod_comp;
1002                 struct lov_mds_md *sub_md;
1003                 int size;
1004
1005                 lod_comp = &comp_entries[i];
1006                 lcme = &lcm->lcm_entries[i];
1007
1008                 LASSERT(ergo(!is_dir, lod_comp->llc_id != LCME_ID_INVAL));
1009                 lcme->lcme_id = cpu_to_le32(lod_comp->llc_id);
1010
1011                 /* component could be un-inistantiated */
1012                 lcme->lcme_flags = cpu_to_le32(lod_comp->llc_flags);
1013                 if (lod_comp->llc_flags & LCME_FL_NOSYNC)
1014                         lcme->lcme_timestamp =
1015                                 cpu_to_le64(lod_comp->llc_timestamp);
1016                 lcme->lcme_extent.e_start =
1017                         cpu_to_le64(lod_comp->llc_extent.e_start);
1018                 lcme->lcme_extent.e_end =
1019                         cpu_to_le64(lod_comp->llc_extent.e_end);
1020                 lcme->lcme_offset = cpu_to_le32(offset);
1021
1022                 sub_md = (struct lov_mds_md *)((char *)lcm + offset);
1023                 rc = lod_gen_component_ea(env, lo, i, sub_md, &size, is_dir);
1024                 if (rc)
1025                         GOTO(out, rc);
1026                 lcme->lcme_size = cpu_to_le32(size);
1027                 offset += size;
1028                 LASSERTF((offset <= *lmm_size) && (offset % sizeof(__u64) == 0),
1029                          "offset:%d lmm_size:%d\n", offset, *lmm_size);
1030         }
1031         lcm->lcm_size = cpu_to_le32(offset);
1032         lcm->lcm_layout_gen = cpu_to_le32(is_dir ? 0 : lo->ldo_layout_gen);
1033
1034         lustre_print_user_md(D_LAYOUT, (struct lov_user_md *)lmm,
1035                              "generate lum");
1036 out:
1037         if (rc == 0)
1038                 *lmm_size = offset;
1039         RETURN(rc);
1040 }
1041
1042 /**
1043  * Get LOV EA.
1044  *
1045  * Fill lti_ea_store buffer in the environment with a value for the given
1046  * EA. The buffer is reallocated if the value doesn't fit.
1047  *
1048  * \param[in,out] env           execution environment for this thread
1049  *                              .lti_ea_store buffer is filled with EA's value
1050  * \param[in] lo                LOD object
1051  * \param[in] name              name of the EA
1052  *
1053  * \retval                      > 0 if EA is fetched successfully
1054  * \retval                      0 if EA is empty
1055  * \retval                      negative error number on failure
1056  */
1057 int lod_get_ea(const struct lu_env *env, struct lod_object *lo,
1058                const char *name)
1059 {
1060         struct lod_thread_info  *info = lod_env_info(env);
1061         struct dt_object        *next = dt_object_child(&lo->ldo_obj);
1062         int                     rc;
1063         ENTRY;
1064
1065         LASSERT(info);
1066
1067         if (unlikely(info->lti_ea_store == NULL)) {
1068                 /* just to enter in allocation block below */
1069                 rc = -ERANGE;
1070         } else {
1071 repeat:
1072                 info->lti_buf.lb_buf = info->lti_ea_store;
1073                 info->lti_buf.lb_len = info->lti_ea_store_size;
1074                 rc = dt_xattr_get(env, next, &info->lti_buf, name);
1075         }
1076
1077         /* if object is not striped or inaccessible */
1078         if (rc == -ENODATA || rc == -ENOENT)
1079                 RETURN(0);
1080
1081         if (rc == -ERANGE) {
1082                 /* EA doesn't fit, reallocate new buffer */
1083                 rc = dt_xattr_get(env, next, &LU_BUF_NULL, name);
1084                 if (rc == -ENODATA || rc == -ENOENT)
1085                         RETURN(0);
1086                 else if (rc < 0)
1087                         RETURN(rc);
1088
1089                 LASSERT(rc > 0);
1090                 rc = lod_ea_store_resize(info, rc);
1091                 if (rc)
1092                         RETURN(rc);
1093                 goto repeat;
1094         }
1095
1096         RETURN(rc);
1097 }
1098
1099 /**
1100  * Verify the target index is present in the current configuration.
1101  *
1102  * \param[in] md                LOD device where the target table is stored
1103  * \param[in] idx               target's index
1104  *
1105  * \retval                      0 if the index is present
1106  * \retval                      -EINVAL if not
1107  */
1108 static int validate_lod_and_idx(struct lod_device *md, __u32 idx)
1109 {
1110         if (unlikely(idx >= md->lod_ost_descs.ltd_tgts_size ||
1111                      !cfs_bitmap_check(md->lod_ost_bitmap, idx))) {
1112                 CERROR("%s: bad idx: %d of %d\n", lod2obd(md)->obd_name, idx,
1113                        md->lod_ost_descs.ltd_tgts_size);
1114                 return -EINVAL;
1115         }
1116
1117         if (unlikely(OST_TGT(md, idx) == NULL)) {
1118                 CERROR("%s: bad lod_tgt_desc for idx: %d\n",
1119                        lod2obd(md)->obd_name, idx);
1120                 return -EINVAL;
1121         }
1122
1123         if (unlikely(OST_TGT(md, idx)->ltd_ost == NULL)) {
1124                 CERROR("%s: invalid lod device, for idx: %d\n",
1125                        lod2obd(md)->obd_name , idx);
1126                 return -EINVAL;
1127         }
1128
1129         return 0;
1130 }
1131
1132 /**
1133  * Instantiate objects for stripes.
1134  *
1135  * Allocate and initialize LU-objects representing the stripes. The number
1136  * of the stripes (ldo_stripe_count) must be initialized already. The caller
1137  * must ensure nobody else is calling the function on the object at the same
1138  * time. FLDB service must be running to be able to map a FID to the targets
1139  * and find appropriate device representing that target.
1140  *
1141  * \param[in] env               execution environment for this thread
1142  * \param[in,out] lo            LOD object
1143  * \param[in] objs              an array of IDs to creates the objects from
1144  * \param[in] comp_idx          index of ldo_comp_entries
1145  *
1146  * \retval                      0 if the objects are instantiated successfully
1147  * \retval                      negative error number on failure
1148  */
1149 int lod_initialize_objects(const struct lu_env *env, struct lod_object *lo,
1150                            struct lov_ost_data_v1 *objs, int comp_idx)
1151 {
1152         struct lod_layout_component *lod_comp;
1153         struct lod_thread_info *info = lod_env_info(env);
1154         struct lod_device *md;
1155         struct lu_object *o, *n;
1156         struct lu_device *nd;
1157         struct dt_object **stripe = NULL;
1158         __u32 *ost_indices = NULL;
1159         int stripe_len;
1160         int i, rc = 0;
1161         __u32 idx;
1162         ENTRY;
1163
1164         LASSERT(lo != NULL);
1165         md = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1166
1167         LASSERT(lo->ldo_comp_cnt != 0 && lo->ldo_comp_entries != NULL);
1168         lod_comp = &lo->ldo_comp_entries[comp_idx];
1169
1170         LASSERT(lod_comp->llc_stripe == NULL);
1171         LASSERT(lod_comp->llc_stripe_count > 0);
1172         LASSERT(lod_comp->llc_stripe_size > 0);
1173
1174         stripe_len = lod_comp->llc_stripe_count;
1175         OBD_ALLOC(stripe, sizeof(stripe[0]) * stripe_len);
1176         if (stripe == NULL)
1177                 RETURN(-ENOMEM);
1178         OBD_ALLOC(ost_indices, sizeof(*ost_indices) * stripe_len);
1179         if (!ost_indices)
1180                 GOTO(out, rc = -ENOMEM);
1181
1182         for (i = 0; i < lod_comp->llc_stripe_count; i++) {
1183                 if (unlikely(lovea_slot_is_dummy(&objs[i])))
1184                         continue;
1185
1186                 ostid_le_to_cpu(&objs[i].l_ost_oi, &info->lti_ostid);
1187                 idx = le32_to_cpu(objs[i].l_ost_idx);
1188                 rc = ostid_to_fid(&info->lti_fid, &info->lti_ostid, idx);
1189                 if (rc != 0)
1190                         GOTO(out, rc);
1191                 LASSERTF(fid_is_sane(&info->lti_fid), ""DFID" insane!\n",
1192                          PFID(&info->lti_fid));
1193                 lod_getref(&md->lod_ost_descs);
1194
1195                 rc = validate_lod_and_idx(md, idx);
1196                 if (unlikely(rc != 0)) {
1197                         lod_putref(md, &md->lod_ost_descs);
1198                         GOTO(out, rc);
1199                 }
1200
1201                 nd = &OST_TGT(md,idx)->ltd_ost->dd_lu_dev;
1202                 lod_putref(md, &md->lod_ost_descs);
1203
1204                 /* In the function below, .hs_keycmp resolves to
1205                  * u_obj_hop_keycmp() */
1206                 /* coverity[overrun-buffer-val] */
1207                 o = lu_object_find_at(env, nd, &info->lti_fid, NULL);
1208                 if (IS_ERR(o))
1209                         GOTO(out, rc = PTR_ERR(o));
1210
1211                 n = lu_object_locate(o->lo_header, nd->ld_type);
1212                 LASSERT(n);
1213
1214                 stripe[i] = container_of(n, struct dt_object, do_lu);
1215                 ost_indices[i] = idx;
1216         }
1217
1218 out:
1219         if (rc != 0) {
1220                 for (i = 0; i < stripe_len; i++)
1221                         if (stripe[i] != NULL)
1222                                 dt_object_put(env, stripe[i]);
1223
1224                 OBD_FREE(stripe, sizeof(stripe[0]) * stripe_len);
1225                 lod_comp->llc_stripe_count = 0;
1226                 if (ost_indices)
1227                         OBD_FREE(ost_indices,
1228                                  sizeof(*ost_indices) * stripe_len);
1229         } else {
1230                 lod_comp->llc_stripe = stripe;
1231                 lod_comp->llc_ost_indices = ost_indices;
1232                 lod_comp->llc_stripes_allocated = stripe_len;
1233         }
1234
1235         RETURN(rc);
1236 }
1237
1238 /**
1239  * Instantiate objects for striping.
1240  *
1241  * Parse striping information in \a buf and instantiate the objects
1242  * representing the stripes.
1243  *
1244  * \param[in] env               execution environment for this thread
1245  * \param[in] lo                LOD object
1246  * \param[in] buf               buffer storing LOV EA to parse
1247  *
1248  * \retval                      0 if parsing and objects creation succeed
1249  * \retval                      negative error number on failure
1250  */
1251 int lod_parse_striping(const struct lu_env *env, struct lod_object *lo,
1252                        const struct lu_buf *buf)
1253 {
1254         struct lov_mds_md_v1    *lmm;
1255         struct lov_comp_md_v1   *comp_v1 = NULL;
1256         struct lov_foreign_md   *foreign = NULL;
1257         struct lov_ost_data_v1  *objs;
1258         __u32   magic, pattern;
1259         int     i, j, rc = 0;
1260         __u16   comp_cnt;
1261         __u16   mirror_cnt = 0;
1262         ENTRY;
1263
1264         LASSERT(buf);
1265         LASSERT(buf->lb_buf);
1266         LASSERT(buf->lb_len);
1267         LASSERT(mutex_is_locked(&lo->ldo_layout_mutex));
1268
1269         lmm = (struct lov_mds_md_v1 *)buf->lb_buf;
1270         magic = le32_to_cpu(lmm->lmm_magic);
1271
1272         if (magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3 &&
1273             magic != LOV_MAGIC_COMP_V1 && magic != LOV_MAGIC_FOREIGN)
1274                 GOTO(out, rc = -EINVAL);
1275
1276         if (lo->ldo_is_foreign)
1277                 lod_free_foreign_lov(lo);
1278         else
1279                 lod_free_comp_entries(lo);
1280
1281         if (magic == LOV_MAGIC_COMP_V1) {
1282                 comp_v1 = (struct lov_comp_md_v1 *)lmm;
1283                 comp_cnt = le16_to_cpu(comp_v1->lcm_entry_count);
1284                 if (comp_cnt == 0)
1285                         GOTO(out, rc = -EINVAL);
1286                 lo->ldo_layout_gen = le32_to_cpu(comp_v1->lcm_layout_gen);
1287                 lo->ldo_is_composite = 1;
1288                 lo->ldo_flr_state = le16_to_cpu(comp_v1->lcm_flags) &
1289                                         LCM_FL_FLR_MASK;
1290                 mirror_cnt = le16_to_cpu(comp_v1->lcm_mirror_count) + 1;
1291         } else if (magic == LOV_MAGIC_FOREIGN) {
1292                 size_t length;
1293
1294                 foreign = (struct lov_foreign_md *)buf->lb_buf;
1295                 length = offsetof(typeof(*foreign), lfm_value);
1296                 if (buf->lb_len < length ||
1297                     buf->lb_len < (length + le32_to_cpu(foreign->lfm_length))) {
1298                         CDEBUG(D_LAYOUT,
1299                                "buf len %zu too small for lov_foreign_md\n",
1300                                buf->lb_len);
1301                         GOTO(out, rc = -EINVAL);
1302                 }
1303
1304                 /* just cache foreign LOV EA raw */
1305                 rc = lod_alloc_foreign_lov(lo, length);
1306                 if (rc)
1307                         GOTO(out, rc);
1308                 memcpy(lo->ldo_foreign_lov, buf->lb_buf, length);
1309                 GOTO(out, rc);
1310         } else {
1311                 comp_cnt = 1;
1312                 lo->ldo_layout_gen = le16_to_cpu(lmm->lmm_layout_gen);
1313                 lo->ldo_is_composite = 0;
1314         }
1315
1316         rc = lod_alloc_comp_entries(lo, mirror_cnt, comp_cnt);
1317         if (rc)
1318                 GOTO(out, rc);
1319
1320         for (i = 0; i < comp_cnt; i++) {
1321                 struct lod_layout_component     *lod_comp;
1322                 struct lu_extent        *ext;
1323                 __u32   offs;
1324
1325                 lod_comp = &lo->ldo_comp_entries[i];
1326                 if (lo->ldo_is_composite) {
1327                         offs = le32_to_cpu(comp_v1->lcm_entries[i].lcme_offset);
1328                         lmm = (struct lov_mds_md_v1 *)((char *)comp_v1 + offs);
1329                         magic = le32_to_cpu(lmm->lmm_magic);
1330
1331                         ext = &comp_v1->lcm_entries[i].lcme_extent;
1332                         lod_comp->llc_extent.e_start =
1333                                 le64_to_cpu(ext->e_start);
1334                         lod_comp->llc_extent.e_end = le64_to_cpu(ext->e_end);
1335                         lod_comp->llc_flags =
1336                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_flags);
1337                         if (lod_comp->llc_flags & LCME_FL_NOSYNC)
1338                                 lod_comp->llc_timestamp = le64_to_cpu(
1339                                         comp_v1->lcm_entries[i].lcme_timestamp);
1340                         lod_comp->llc_id =
1341                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_id);
1342                         if (lod_comp->llc_id == LCME_ID_INVAL)
1343                                 GOTO(out, rc = -EINVAL);
1344                 } else {
1345                         lod_comp_set_init(lod_comp);
1346                 }
1347
1348                 pattern = le32_to_cpu(lmm->lmm_pattern);
1349                 if (!lov_pattern_supported(lov_pattern(pattern)))
1350                         GOTO(out, rc = -EINVAL);
1351
1352                 lod_comp->llc_pattern = pattern;
1353                 lod_comp->llc_stripe_size = le32_to_cpu(lmm->lmm_stripe_size);
1354                 lod_comp->llc_stripe_count = le16_to_cpu(lmm->lmm_stripe_count);
1355                 lod_comp->llc_layout_gen = le16_to_cpu(lmm->lmm_layout_gen);
1356
1357                 if (magic == LOV_MAGIC_V3) {
1358                         struct lov_mds_md_v3 *v3 = (struct lov_mds_md_v3 *)lmm;
1359                         lod_set_pool(&lod_comp->llc_pool, v3->lmm_pool_name);
1360                         objs = &v3->lmm_objects[0];
1361                 } else {
1362                         lod_set_pool(&lod_comp->llc_pool, NULL);
1363                         objs = &lmm->lmm_objects[0];
1364                 }
1365
1366                 /**
1367                  * If uninstantiated template component has valid l_ost_idx,
1368                  * then user has specified ost list for this component.
1369                  */
1370                 if (!lod_comp_inited(lod_comp)) {
1371                         __u16 stripe_count;
1372
1373                         if (objs[0].l_ost_idx != (__u32)-1UL) {
1374                                 stripe_count = lod_comp_entry_stripe_count(
1375                                                         lo, lod_comp, false);
1376                                 if (stripe_count == 0 &&
1377                                     !(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
1378                                     !(lod_comp->llc_pattern & LOV_PATTERN_MDT))
1379                                         GOTO(out, rc = -E2BIG);
1380                                 /**
1381                                  * load the user specified ost list, when this
1382                                  * component is instantiated later, it will be
1383                                  * used in lod_alloc_ost_list().
1384                                  */
1385                                 lod_comp->llc_ostlist.op_count = stripe_count;
1386                                 lod_comp->llc_ostlist.op_size =
1387                                         stripe_count * sizeof(__u32);
1388                                 OBD_ALLOC(lod_comp->llc_ostlist.op_array,
1389                                           lod_comp->llc_ostlist.op_size);
1390                                 if (!lod_comp->llc_ostlist.op_array)
1391                                         GOTO(out, rc = -ENOMEM);
1392
1393                                 for (j = 0; j < stripe_count; j++)
1394                                         lod_comp->llc_ostlist.op_array[j] =
1395                                                 le32_to_cpu(objs[j].l_ost_idx);
1396
1397                                 /**
1398                                  * this component OST objects starts from the
1399                                  * first ost_idx, lod_alloc_ost_list() will
1400                                  * check this.
1401                                  */
1402                                 lod_comp->llc_stripe_offset = objs[0].l_ost_idx;
1403                         } else {
1404                                 /**
1405                                  * for uninstantiated component,
1406                                  * lmm_layout_gen stores default stripe offset.
1407                                  */
1408                                 lod_comp->llc_stripe_offset =
1409                                                         lmm->lmm_layout_gen;
1410                         }
1411                 }
1412
1413                 /* skip un-instantiated component object initialization */
1414                 if (!lod_comp_inited(lod_comp))
1415                         continue;
1416
1417                 if (!(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
1418                     !(lod_comp->llc_pattern & LOV_PATTERN_MDT)) {
1419                         rc = lod_initialize_objects(env, lo, objs, i);
1420                         if (rc)
1421                                 GOTO(out, rc);
1422                 }
1423         }
1424
1425         rc = lod_fill_mirrors(lo);
1426         if (rc)
1427                 GOTO(out, rc);
1428
1429 out:
1430         if (rc)
1431                 lod_striping_free_nolock(env, lo);
1432         RETURN(rc);
1433 }
1434
1435 /**
1436  * Check whether the striping (LOVEA for regular file, LMVEA for directory)
1437  * is already cached.
1438  *
1439  * \param[in] lo        LOD object
1440  *
1441  * \retval              True if the striping is cached, otherwise
1442  *                      return false.
1443  */
1444 static bool lod_striping_loaded(struct lod_object *lo)
1445 {
1446         if (S_ISREG(lod2lu_obj(lo)->lo_header->loh_attr) &&
1447             lo->ldo_comp_cached)
1448                 return true;
1449
1450         if (S_ISDIR(lod2lu_obj(lo)->lo_header->loh_attr)) {
1451                 if (lo->ldo_dir_stripe_loaded)
1452                         return true;
1453
1454                 /* Never load LMV stripe for slaves of striped dir */
1455                 if (lo->ldo_dir_slave_stripe)
1456                         return true;
1457         }
1458
1459         return false;
1460 }
1461
1462 /**
1463  * A generic function to initialize the stripe objects.
1464  *
1465  * A protected version of lod_striping_load_locked() - load the striping
1466  * information from storage, parse that and instantiate LU objects to
1467  * represent the stripes.  The LOD object \a lo supplies a pointer to the
1468  * next sub-object in the LU stack so we can lock it. Also use \a lo to
1469  * return an array of references to the newly instantiated objects.
1470  *
1471  * \param[in] env               execution environment for this thread
1472  * \param[in,out] lo            LOD object, where striping is stored and
1473  *                              which gets an array of references
1474  *
1475  * \retval                      0 if parsing and object creation succeed
1476  * \retval                      negative error number on failure
1477  **/
1478 int lod_striping_load(const struct lu_env *env, struct lod_object *lo)
1479 {
1480         struct lod_thread_info *info = lod_env_info(env);
1481         struct dt_object *next = dt_object_child(&lo->ldo_obj);
1482         struct lu_buf *buf = &info->lti_buf;
1483         int rc = 0;
1484
1485         ENTRY;
1486
1487         if (!dt_object_exists(next))
1488                 RETURN(0);
1489
1490         if (lod_striping_loaded(lo))
1491                 RETURN(0);
1492
1493         mutex_lock(&lo->ldo_layout_mutex);
1494         if (lod_striping_loaded(lo))
1495                 GOTO(unlock, rc = 0);
1496
1497         if (S_ISREG(lod2lu_obj(lo)->lo_header->loh_attr)) {
1498                 rc = lod_get_lov_ea(env, lo);
1499                 if (rc <= 0)
1500                         GOTO(unlock, rc);
1501
1502                 /*
1503                  * there is LOV EA (striping information) in this object
1504                  * let's parse it and create in-core objects for the stripes
1505                  */
1506                 buf->lb_buf = info->lti_ea_store;
1507                 buf->lb_len = info->lti_ea_store_size;
1508                 rc = lod_parse_striping(env, lo, buf);
1509                 if (rc == 0)
1510                         lo->ldo_comp_cached = 1;
1511         } else if (S_ISDIR(lod2lu_obj(lo)->lo_header->loh_attr)) {
1512                 rc = lod_get_lmv_ea(env, lo);
1513                 if (rc > sizeof(struct lmv_foreign_md)) {
1514                         struct lmv_foreign_md *lfm = info->lti_ea_store;
1515
1516                         if (le32_to_cpu(lfm->lfm_magic) == LMV_MAGIC_FOREIGN) {
1517                                 lo->ldo_foreign_lmv = info->lti_ea_store;
1518                                 lo->ldo_foreign_lmv_size =
1519                                         info->lti_ea_store_size;
1520                                 info->lti_ea_store = NULL;
1521                                 info->lti_ea_store_size = 0;
1522
1523                                 lo->ldo_dir_stripe_loaded = 1;
1524                                 lo->ldo_dir_is_foreign = 1;
1525                                 GOTO(unlock, rc = 0);
1526                         }
1527                 }
1528
1529                 if (rc < (int)sizeof(struct lmv_mds_md_v1)) {
1530                         /* Let's set stripe_loaded to avoid further
1531                          * stripe loading especially for non-stripe directory,
1532                          * which can hurt performance. (See LU-9840)
1533                          */
1534                         if (rc == 0)
1535                                 lo->ldo_dir_stripe_loaded = 1;
1536                         GOTO(unlock, rc = rc > 0 ? -EINVAL : rc);
1537                 }
1538                 buf->lb_buf = info->lti_ea_store;
1539                 buf->lb_len = info->lti_ea_store_size;
1540                 if (rc == sizeof(struct lmv_mds_md_v1)) {
1541                         rc = lod_load_lmv_shards(env, lo, buf, true);
1542                         if (buf->lb_buf != info->lti_ea_store) {
1543                                 OBD_FREE_LARGE(info->lti_ea_store,
1544                                                info->lti_ea_store_size);
1545                                 info->lti_ea_store = buf->lb_buf;
1546                                 info->lti_ea_store_size = buf->lb_len;
1547                         }
1548
1549                         if (rc < 0)
1550                                 GOTO(unlock, rc);
1551                 }
1552
1553                 /*
1554                  * there is LMV EA (striping information) in this object
1555                  * let's parse it and create in-core objects for the stripes
1556                  */
1557                 rc = lod_parse_dir_striping(env, lo, buf);
1558                 if (rc == 0)
1559                         lo->ldo_dir_stripe_loaded = 1;
1560         }
1561         EXIT;
1562 unlock:
1563         mutex_unlock(&lo->ldo_layout_mutex);
1564
1565         return rc;
1566 }
1567
1568 int lod_striping_reload(const struct lu_env *env, struct lod_object *lo,
1569                          const struct lu_buf *buf)
1570 {
1571         int rc;
1572
1573         ENTRY;
1574
1575         mutex_lock(&lo->ldo_layout_mutex);
1576         lod_striping_free_nolock(env, lo);
1577         rc = lod_parse_striping(env, lo, buf);
1578         mutex_unlock(&lo->ldo_layout_mutex);
1579
1580         RETURN(rc);
1581 }
1582
1583 /**
1584  * Verify lov_user_md_v1/v3 striping.
1585  *
1586  * Check the validity of all fields including the magic, stripe size,
1587  * stripe count, stripe offset and that the pool is present.  Also check
1588  * that each target index points to an existing target. The additional
1589  * \a is_from_disk turns additional checks. In some cases zero fields
1590  * are allowed (like pattern=0).
1591  *
1592  * \param[in] d                 LOD device
1593  * \param[in] buf               buffer with LOV EA to verify
1594  * \param[in] is_from_disk      0 - from user, allow some fields to be 0
1595  *                              1 - from disk, do not allow
1596  *
1597  * \retval                      0 if the striping is valid
1598  * \retval                      -EINVAL if striping is invalid
1599  */
1600 static int lod_verify_v1v3(struct lod_device *d, const struct lu_buf *buf,
1601                            bool is_from_disk)
1602 {
1603         struct lov_user_md_v1   *lum;
1604         struct lov_user_md_v3   *lum3;
1605         struct pool_desc        *pool = NULL;
1606         __u32                    magic;
1607         __u32                    stripe_size;
1608         __u16                    stripe_count;
1609         __u16                    stripe_offset;
1610         size_t                   lum_size;
1611         int                      rc = 0;
1612         ENTRY;
1613
1614         lum = buf->lb_buf;
1615
1616         if (buf->lb_len < sizeof(*lum)) {
1617                 CDEBUG(D_LAYOUT, "buf len %zu too small for lov_user_md\n",
1618                        buf->lb_len);
1619                 GOTO(out, rc = -EINVAL);
1620         }
1621
1622         magic = le32_to_cpu(lum->lmm_magic) & ~LOV_MAGIC_DEFINED;
1623         if (magic != LOV_USER_MAGIC_V1 &&
1624             magic != LOV_USER_MAGIC_V3 &&
1625             magic != LOV_USER_MAGIC_SPECIFIC) {
1626                 CDEBUG(D_LAYOUT, "bad userland LOV MAGIC: %#x\n",
1627                        le32_to_cpu(lum->lmm_magic));
1628                 GOTO(out, rc = -EINVAL);
1629         }
1630
1631         /* the user uses "0" for default stripe pattern normally. */
1632         if (!is_from_disk && lum->lmm_pattern == LOV_PATTERN_NONE)
1633                 lum->lmm_pattern = cpu_to_le32(LOV_PATTERN_RAID0);
1634
1635         if (!lov_pattern_supported(le32_to_cpu(lum->lmm_pattern))) {
1636                 CDEBUG(D_LAYOUT, "bad userland stripe pattern: %#x\n",
1637                        le32_to_cpu(lum->lmm_pattern));
1638                 GOTO(out, rc = -EINVAL);
1639         }
1640
1641         /* a released lum comes from creating orphan on hsm release,
1642          * doesn't make sense to verify it. */
1643         if (le32_to_cpu(lum->lmm_pattern) & LOV_PATTERN_F_RELEASED)
1644                 GOTO(out, rc = 0);
1645
1646         /* 64kB is the largest common page size we see (ia64), and matches the
1647          * check in lfs */
1648         stripe_size = le32_to_cpu(lum->lmm_stripe_size);
1649         if (stripe_size & (LOV_MIN_STRIPE_SIZE - 1)) {
1650                 CDEBUG(D_LAYOUT, "stripe size %u not a multiple of %u\n",
1651                        stripe_size, LOV_MIN_STRIPE_SIZE);
1652                 GOTO(out, rc = -EINVAL);
1653         }
1654
1655         stripe_offset = le16_to_cpu(lum->lmm_stripe_offset);
1656         if (!is_from_disk && stripe_offset != LOV_OFFSET_DEFAULT &&
1657             lov_pattern(le32_to_cpu(lum->lmm_pattern)) != LOV_PATTERN_MDT) {
1658                 /* if offset is not within valid range [0, osts_size) */
1659                 if (stripe_offset >= d->lod_osts_size) {
1660                         CDEBUG(D_LAYOUT, "stripe offset %u >= bitmap size %u\n",
1661                                stripe_offset, d->lod_osts_size);
1662                         GOTO(out, rc = -EINVAL);
1663                 }
1664
1665                 /* if lmm_stripe_offset is *not* in bitmap */
1666                 if (!cfs_bitmap_check(d->lod_ost_bitmap, stripe_offset)) {
1667                         CDEBUG(D_LAYOUT, "stripe offset %u not in bitmap\n",
1668                                stripe_offset);
1669                         GOTO(out, rc = -EINVAL);
1670                 }
1671         }
1672
1673         if (magic == LOV_USER_MAGIC_V1)
1674                 lum_size = offsetof(struct lov_user_md_v1,
1675                                     lmm_objects[0]);
1676         else if (magic == LOV_USER_MAGIC_V3 || magic == LOV_USER_MAGIC_SPECIFIC)
1677                 lum_size = offsetof(struct lov_user_md_v3,
1678                                     lmm_objects[0]);
1679         else
1680                 GOTO(out, rc = -EINVAL);
1681
1682         stripe_count = le16_to_cpu(lum->lmm_stripe_count);
1683         if (buf->lb_len < lum_size) {
1684                 CDEBUG(D_LAYOUT, "invalid buf len %zu/%zu for lov_user_md with "
1685                        "magic %#x and stripe_count %u\n",
1686                        buf->lb_len, lum_size, magic, stripe_count);
1687                 GOTO(out, rc = -EINVAL);
1688         }
1689
1690         if (!(magic == LOV_USER_MAGIC_V3 || magic == LOV_USER_MAGIC_SPECIFIC))
1691                 goto out;
1692
1693         lum3 = buf->lb_buf;
1694         /* In the function below, .hs_keycmp resolves to
1695          * pool_hashkey_keycmp() */
1696         /* coverity[overrun-buffer-val] */
1697         pool = lod_find_pool(d, lum3->lmm_pool_name);
1698         if (pool == NULL)
1699                 goto out;
1700
1701         if (!is_from_disk && stripe_offset != LOV_OFFSET_DEFAULT) {
1702                 rc = lod_check_index_in_pool(stripe_offset, pool);
1703                 if (rc < 0)
1704                         GOTO(out, rc = -EINVAL);
1705         }
1706
1707         if (is_from_disk && stripe_count > pool_tgt_count(pool)) {
1708                 CDEBUG(D_LAYOUT, "stripe count %u > # OSTs %u in the pool\n",
1709                        stripe_count, pool_tgt_count(pool));
1710                 GOTO(out, rc = -EINVAL);
1711         }
1712
1713 out:
1714         if (pool != NULL)
1715                 lod_pool_putref(pool);
1716
1717         RETURN(rc);
1718 }
1719
1720 static inline
1721 struct lov_comp_md_entry_v1 *comp_entry_v1(struct lov_comp_md_v1 *comp, int i)
1722 {
1723         LASSERTF((le32_to_cpu(comp->lcm_magic) & ~LOV_MAGIC_DEFINED) ==
1724                  LOV_USER_MAGIC_COMP_V1, "Wrong magic %x\n",
1725                  le32_to_cpu(comp->lcm_magic));
1726         LASSERTF(i >= 0 && i < le16_to_cpu(comp->lcm_entry_count),
1727                  "bad index %d, max = %d\n",
1728                  i, le16_to_cpu(comp->lcm_entry_count));
1729
1730         return &comp->lcm_entries[i];
1731 }
1732
1733 #define for_each_comp_entry_v1(comp, entry) \
1734         for (entry = comp_entry_v1(comp, 0); \
1735              entry <= comp_entry_v1(comp, \
1736                                    le16_to_cpu(comp->lcm_entry_count) - 1); \
1737              entry++)
1738
1739 int lod_erase_dom_stripe(struct lov_comp_md_v1 *comp_v1)
1740 {
1741         struct lov_comp_md_entry_v1 *ent, *dom_ent;
1742         __u16 entries;
1743         __u32 dom_off, dom_size, comp_size;
1744         void *blob_src, *blob_dst;
1745         unsigned int blob_size, blob_shift;
1746
1747         entries = le16_to_cpu(comp_v1->lcm_entry_count) - 1;
1748         /* if file has only DoM stripe return just error */
1749         if (entries == 0)
1750                 return -EFBIG;
1751
1752         comp_size = le32_to_cpu(comp_v1->lcm_size);
1753         dom_ent = &comp_v1->lcm_entries[0];
1754         dom_off = le32_to_cpu(dom_ent->lcme_offset);
1755         dom_size = le32_to_cpu(dom_ent->lcme_size);
1756
1757         /* shift entries array first */
1758         comp_v1->lcm_entry_count = cpu_to_le16(entries);
1759         memmove(dom_ent, dom_ent + 1,
1760                 entries * sizeof(struct lov_comp_md_entry_v1));
1761
1762         /* now move blob of layouts */
1763         blob_dst = (void *)comp_v1 + dom_off - sizeof(*dom_ent);
1764         blob_src = (void *)comp_v1 + dom_off + dom_size;
1765         blob_size = (unsigned long)((void *)comp_v1 + comp_size - blob_src);
1766         blob_shift = sizeof(*dom_ent) + dom_size;
1767
1768         memmove(blob_dst, blob_src, blob_size);
1769
1770         for_each_comp_entry_v1(comp_v1, ent) {
1771                 __u32 off;
1772
1773                 off = le32_to_cpu(ent->lcme_offset);
1774                 ent->lcme_offset = cpu_to_le32(off - blob_shift);
1775         }
1776
1777         comp_v1->lcm_size = cpu_to_le32(comp_size - blob_shift);
1778
1779         /* notify a caller to re-check entry */
1780         return -ERESTART;
1781 }
1782
1783 int lod_fix_dom_stripe(struct lod_device *d, struct lov_comp_md_v1 *comp_v1)
1784 {
1785         struct lov_comp_md_entry_v1 *ent, *dom_ent;
1786         struct lu_extent *dom_ext, *ext;
1787         struct lov_user_md_v1 *lum;
1788         __u32 stripe_size;
1789         __u16 mid, dom_mid;
1790         int rc = 0;
1791
1792         dom_ent = &comp_v1->lcm_entries[0];
1793         dom_ext = &dom_ent->lcme_extent;
1794         dom_mid = mirror_id_of(le32_to_cpu(dom_ent->lcme_id));
1795         stripe_size = d->lod_dom_max_stripesize;
1796
1797         lum = (void *)comp_v1 + le32_to_cpu(dom_ent->lcme_offset);
1798         CDEBUG(D_LAYOUT, "DoM component size %u was bigger than MDT limit %u, "
1799                "new size is %u\n", le32_to_cpu(lum->lmm_stripe_size),
1800                d->lod_dom_max_stripesize, stripe_size);
1801         lum->lmm_stripe_size = cpu_to_le32(stripe_size);
1802
1803         for_each_comp_entry_v1(comp_v1, ent) {
1804                 if (ent == dom_ent)
1805                         continue;
1806
1807                 mid = mirror_id_of(le32_to_cpu(ent->lcme_id));
1808                 if (mid != dom_mid)
1809                         continue;
1810
1811                 ext = &ent->lcme_extent;
1812                 if (ext->e_start != dom_ext->e_end)
1813                         continue;
1814
1815                 /* Found next component after the DoM one with the same
1816                  * mirror_id and adjust its start with DoM component end.
1817                  *
1818                  * NOTE: we are considering here that there can be only one
1819                  * DoM component in a file, all replicas are located on OSTs
1820                  * always and don't need adjustment since use own layouts.
1821                  */
1822                 ext->e_start = cpu_to_le64(stripe_size);
1823                 break;
1824         }
1825
1826         if (stripe_size == 0) {
1827                 /* DoM component size is zero due to server setting,
1828                  * remove it from the layout */
1829                 rc = lod_erase_dom_stripe(comp_v1);
1830         } else {
1831                 /* Update DoM extent end finally */
1832                 dom_ext->e_end = cpu_to_le64(stripe_size);
1833         }
1834
1835         return rc;
1836 }
1837
1838 /**
1839  * Verify LOV striping.
1840  *
1841  * \param[in] d                 LOD device
1842  * \param[in] buf               buffer with LOV EA to verify
1843  * \param[in] is_from_disk      0 - from user, allow some fields to be 0
1844  *                              1 - from disk, do not allow
1845  * \param[in] start             extent start for composite layout
1846  *
1847  * \retval                      0 if the striping is valid
1848  * \retval                      -EINVAL if striping is invalid
1849  */
1850 int lod_verify_striping(struct lod_device *d, struct lod_object *lo,
1851                         const struct lu_buf *buf, bool is_from_disk)
1852 {
1853         struct lov_desc *desc = &d->lod_desc;
1854         struct lov_user_md_v1   *lum;
1855         struct lov_comp_md_v1   *comp_v1;
1856         struct lov_comp_md_entry_v1     *ent;
1857         struct lu_extent        *ext;
1858         struct lu_buf   tmp;
1859         __u64   prev_end = 0;
1860         __u32   stripe_size = 0;
1861         __u16   prev_mid = -1, mirror_id = -1;
1862         __u32   mirror_count;
1863         __u32   magic;
1864         int     rc = 0;
1865         ENTRY;
1866
1867         if (buf->lb_len < sizeof(lum->lmm_magic)) {
1868                 CDEBUG(D_LAYOUT, "invalid buf len %zu\n", buf->lb_len);
1869                 RETURN(-EINVAL);
1870         }
1871
1872         lum = buf->lb_buf;
1873
1874         magic = le32_to_cpu(lum->lmm_magic) & ~LOV_MAGIC_DEFINED;
1875         /* treat foreign LOV EA/object case first
1876          * XXX is it expected to try setting again a foreign?
1877          * XXX should we care about different current vs new layouts ?
1878          */
1879         if (unlikely(magic == LOV_USER_MAGIC_FOREIGN)) {
1880                 struct lov_foreign_md *lfm = buf->lb_buf;
1881
1882                 if (buf->lb_len < offsetof(typeof(*lfm), lfm_value)) {
1883                         CDEBUG(D_LAYOUT,
1884                                "buf len %zu < min lov_foreign_md size (%zu)\n",
1885                                buf->lb_len, offsetof(typeof(*lfm),
1886                                lfm_value));
1887                         RETURN(-EINVAL);
1888                 }
1889
1890                 if (foreign_size_le(lfm) > buf->lb_len) {
1891                         CDEBUG(D_LAYOUT,
1892                                "buf len %zu < this lov_foreign_md size (%zu)\n",
1893                                buf->lb_len, foreign_size_le(lfm));
1894                         RETURN(-EINVAL);
1895                 }
1896                 /* Don't do anything with foreign layouts */
1897                 RETURN(0);
1898         }
1899
1900         /* normal LOV/layout cases */
1901
1902         if (buf->lb_len < sizeof(*lum)) {
1903                 CDEBUG(D_LAYOUT, "buf len %zu too small for lov_user_md\n",
1904                        buf->lb_len);
1905                 RETURN(-EINVAL);
1906         }
1907
1908         if (magic != LOV_USER_MAGIC_V1 &&
1909             magic != LOV_USER_MAGIC_V3 &&
1910             magic != LOV_USER_MAGIC_SPECIFIC &&
1911             magic != LOV_USER_MAGIC_COMP_V1) {
1912                 CDEBUG(D_LAYOUT, "bad userland LOV MAGIC: %#x\n",
1913                        le32_to_cpu(lum->lmm_magic));
1914                 RETURN(-EINVAL);
1915         }
1916
1917         if (magic != LOV_USER_MAGIC_COMP_V1)
1918                 RETURN(lod_verify_v1v3(d, buf, is_from_disk));
1919
1920         /* magic == LOV_USER_MAGIC_COMP_V1 */
1921         comp_v1 = buf->lb_buf;
1922         if (buf->lb_len < le32_to_cpu(comp_v1->lcm_size)) {
1923                 CDEBUG(D_LAYOUT, "buf len %zu is less than %u\n",
1924                        buf->lb_len, le32_to_cpu(comp_v1->lcm_size));
1925                 RETURN(-EINVAL);
1926         }
1927
1928 recheck:
1929         mirror_count = 0;
1930         if (le16_to_cpu(comp_v1->lcm_entry_count) == 0) {
1931                 CDEBUG(D_LAYOUT, "entry count is zero\n");
1932                 RETURN(-EINVAL);
1933         }
1934
1935         if (S_ISREG(lod2lu_obj(lo)->lo_header->loh_attr) &&
1936             lo->ldo_comp_cnt > 0) {
1937                 /* could be called from lustre.lov.add */
1938                 __u32 cnt = lo->ldo_comp_cnt;
1939
1940                 ext = &lo->ldo_comp_entries[cnt - 1].llc_extent;
1941                 prev_end = ext->e_end;
1942
1943                 ++mirror_count;
1944         }
1945
1946         for_each_comp_entry_v1(comp_v1, ent) {
1947                 ext = &ent->lcme_extent;
1948
1949                 if (le64_to_cpu(ext->e_start) >= le64_to_cpu(ext->e_end)) {
1950                         CDEBUG(D_LAYOUT, "invalid extent "DEXT"\n",
1951                                le64_to_cpu(ext->e_start),
1952                                le64_to_cpu(ext->e_end));
1953                         RETURN(-EINVAL);
1954                 }
1955
1956                 if (is_from_disk) {
1957                         /* lcme_id contains valid value */
1958                         if (le32_to_cpu(ent->lcme_id) == 0 ||
1959                             le32_to_cpu(ent->lcme_id) > LCME_ID_MAX) {
1960                                 CDEBUG(D_LAYOUT, "invalid id %u\n",
1961                                        le32_to_cpu(ent->lcme_id));
1962                                 RETURN(-EINVAL);
1963                         }
1964
1965                         if (le16_to_cpu(comp_v1->lcm_mirror_count) > 0) {
1966                                 mirror_id = mirror_id_of(
1967                                                 le32_to_cpu(ent->lcme_id));
1968
1969                                 /* first component must start with 0 */
1970                                 if (mirror_id != prev_mid &&
1971                                     le64_to_cpu(ext->e_start) != 0) {
1972                                         CDEBUG(D_LAYOUT,
1973                                                "invalid start:%llu, expect:0\n",
1974                                                le64_to_cpu(ext->e_start));
1975                                         RETURN(-EINVAL);
1976                                 }
1977
1978                                 prev_mid = mirror_id;
1979                         }
1980                 }
1981
1982                 if (le64_to_cpu(ext->e_start) == 0) {
1983                         ++mirror_count;
1984                         prev_end = 0;
1985                 }
1986
1987                 /* the next must be adjacent with the previous one */
1988                 if (le64_to_cpu(ext->e_start) != prev_end) {
1989                         CDEBUG(D_LAYOUT,
1990                                "invalid start actual:%llu, expect:%llu\n",
1991                                le64_to_cpu(ext->e_start), prev_end);
1992                         RETURN(-EINVAL);
1993                 }
1994
1995                 tmp.lb_buf = (char *)comp_v1 + le32_to_cpu(ent->lcme_offset);
1996                 tmp.lb_len = le32_to_cpu(ent->lcme_size);
1997
1998                 /* Check DoM entry is always the first one */
1999                 lum = tmp.lb_buf;
2000                 if (lov_pattern(le32_to_cpu(lum->lmm_pattern)) ==
2001                     LOV_PATTERN_MDT) {
2002                         /* DoM component can be only the first stripe */
2003                         if (le64_to_cpu(ext->e_start) > 0) {
2004                                 CDEBUG(D_LAYOUT, "invalid DoM component "
2005                                        "with %llu extent start\n",
2006                                        le64_to_cpu(ext->e_start));
2007                                 RETURN(-EINVAL);
2008                         }
2009                         stripe_size = le32_to_cpu(lum->lmm_stripe_size);
2010                         /* There is just one stripe on MDT and it must
2011                          * cover whole component size. */
2012                         if (stripe_size != le64_to_cpu(ext->e_end)) {
2013                                 CDEBUG(D_LAYOUT, "invalid DoM layout "
2014                                        "stripe size %u != %llu "
2015                                        "(component size)\n",
2016                                        stripe_size, prev_end);
2017                                 RETURN(-EINVAL);
2018                         }
2019                         /* Check stripe size againts per-MDT limit */
2020                         if (stripe_size > d->lod_dom_max_stripesize) {
2021                                 CDEBUG(D_LAYOUT, "DoM component size "
2022                                        "%u is bigger than MDT limit %u, check "
2023                                        "dom_max_stripesize parameter\n",
2024                                        stripe_size, d->lod_dom_max_stripesize);
2025                                 rc = lod_fix_dom_stripe(d, comp_v1);
2026                                 if (rc == -ERESTART) {
2027                                         /* DoM entry was removed, re-check
2028                                          * new layout from start */
2029                                         goto recheck;
2030                                 } else if (rc) {
2031                                         RETURN(rc);
2032                                 }
2033                         }
2034                 }
2035
2036                 prev_end = le64_to_cpu(ext->e_end);
2037
2038                 rc = lod_verify_v1v3(d, &tmp, is_from_disk);
2039                 if (rc)
2040                         RETURN(rc);
2041
2042                 if (prev_end == LUSTRE_EOF)
2043                         continue;
2044
2045                 /* extent end must be aligned with the stripe_size */
2046                 stripe_size = le32_to_cpu(lum->lmm_stripe_size);
2047                 if (stripe_size == 0)
2048                         stripe_size = desc->ld_default_stripe_size;
2049                 if (stripe_size == 0 || (prev_end & (stripe_size - 1))) {
2050                         CDEBUG(D_LAYOUT, "stripe size isn't aligned, "
2051                                "stripe_sz: %u, [%llu, %llu)\n",
2052                                stripe_size, ext->e_start, prev_end);
2053                         RETURN(-EINVAL);
2054                 }
2055         }
2056
2057         /* make sure that the mirror_count is telling the truth */
2058         if (mirror_count != le16_to_cpu(comp_v1->lcm_mirror_count) + 1)
2059                 RETURN(-EINVAL);
2060
2061         RETURN(0);
2062 }
2063
2064 /**
2065  * set the default stripe size, if unset.
2066  *
2067  * \param[in,out] val   number of bytes per OST stripe
2068  *
2069  * The minimum stripe size is 64KB to ensure that a single stripe is an
2070  * even multiple of a client PAGE_SIZE (IA64, PPC, etc).  Otherwise, it
2071  * is difficult to split dirty pages across OSCs during writes.
2072  */
2073 void lod_fix_desc_stripe_size(__u64 *val)
2074 {
2075         if (*val < LOV_MIN_STRIPE_SIZE) {
2076                 if (*val != 0)
2077                         LCONSOLE_INFO("Increasing default stripe size to "
2078                                       "minimum value %u\n",
2079                                       LOV_DESC_STRIPE_SIZE_DEFAULT);
2080                 *val = LOV_DESC_STRIPE_SIZE_DEFAULT;
2081         } else if (*val & (LOV_MIN_STRIPE_SIZE - 1)) {
2082                 *val &= ~(LOV_MIN_STRIPE_SIZE - 1);
2083                 LCONSOLE_WARN("Changing default stripe size to %llu (a "
2084                               "multiple of %u)\n",
2085                               *val, LOV_MIN_STRIPE_SIZE);
2086         }
2087 }
2088
2089 /**
2090  * set the filesystem default number of stripes, if unset.
2091  *
2092  * \param[in,out] val   number of stripes
2093  *
2094  * A value of "0" means "use the system-wide default stripe count", which
2095  * has either been inherited by now, or falls back to 1 stripe per file.
2096  * A value of "-1" (0xffffffff) means "stripe over all available OSTs",
2097  * and is a valid value, so is left unchanged here.
2098  */
2099 void lod_fix_desc_stripe_count(__u32 *val)
2100 {
2101         if (*val == 0)
2102                 *val = 1;
2103 }
2104
2105 /**
2106  * set the filesystem default layout pattern
2107  *
2108  * \param[in,out] val   LOV_PATTERN_* layout
2109  *
2110  * A value of "0" means "use the system-wide default layout type", which
2111  * has either been inherited by now, or falls back to plain RAID0 striping.
2112  */
2113 void lod_fix_desc_pattern(__u32 *val)
2114 {
2115         /* from lov_setstripe */
2116         if ((*val != 0) && !lov_pattern_supported_normal_comp(*val)) {
2117                 LCONSOLE_WARN("lod: Unknown stripe pattern: %#x\n", *val);
2118                 *val = 0;
2119         }
2120 }
2121
2122 void lod_fix_desc_qos_maxage(__u32 *val)
2123 {
2124         /* fix qos_maxage */
2125         if (*val == 0)
2126                 *val = LOV_DESC_QOS_MAXAGE_DEFAULT;
2127 }
2128
2129 /**
2130  * Used to fix insane default striping.
2131  *
2132  * \param[in] desc      striping description
2133  */
2134 void lod_fix_desc(struct lov_desc *desc)
2135 {
2136         lod_fix_desc_stripe_size(&desc->ld_default_stripe_size);
2137         lod_fix_desc_stripe_count(&desc->ld_default_stripe_count);
2138         lod_fix_desc_pattern(&desc->ld_pattern);
2139         lod_fix_desc_qos_maxage(&desc->ld_qos_maxage);
2140 }
2141
2142 /**
2143  * Initialize the structures used to store pools and default striping.
2144  *
2145  * \param[in] lod       LOD device
2146  * \param[in] lcfg      configuration structure storing default striping.
2147  *
2148  * \retval              0 if initialization succeeds
2149  * \retval              negative error number on failure
2150  */
2151 int lod_pools_init(struct lod_device *lod, struct lustre_cfg *lcfg)
2152 {
2153         struct obd_device          *obd;
2154         struct lov_desc            *desc;
2155         int                         rc;
2156         ENTRY;
2157
2158         obd = class_name2obd(lustre_cfg_string(lcfg, 0));
2159         LASSERT(obd != NULL);
2160         obd->obd_lu_dev = &lod->lod_dt_dev.dd_lu_dev;
2161
2162         if (LUSTRE_CFG_BUFLEN(lcfg, 1) < 1) {
2163                 CERROR("LOD setup requires a descriptor\n");
2164                 RETURN(-EINVAL);
2165         }
2166
2167         desc = (struct lov_desc *)lustre_cfg_buf(lcfg, 1);
2168
2169         if (sizeof(*desc) > LUSTRE_CFG_BUFLEN(lcfg, 1)) {
2170                 CERROR("descriptor size wrong: %d > %d\n",
2171                        (int)sizeof(*desc), LUSTRE_CFG_BUFLEN(lcfg, 1));
2172                 RETURN(-EINVAL);
2173         }
2174
2175         if (desc->ld_magic != LOV_DESC_MAGIC) {
2176                 if (desc->ld_magic == __swab32(LOV_DESC_MAGIC)) {
2177                         CDEBUG(D_OTHER, "%s: Swabbing lov desc %p\n",
2178                                obd->obd_name, desc);
2179                         lustre_swab_lov_desc(desc);
2180                 } else {
2181                         CERROR("%s: Bad lov desc magic: %#x\n",
2182                                obd->obd_name, desc->ld_magic);
2183                         RETURN(-EINVAL);
2184                 }
2185         }
2186
2187         lod_fix_desc(desc);
2188
2189         desc->ld_active_tgt_count = 0;
2190         lod->lod_desc = *desc;
2191
2192         lod->lod_sp_me = LUSTRE_SP_CLI;
2193
2194         /* Set up allocation policy (QoS and RR) */
2195         INIT_LIST_HEAD(&lod->lod_qos.lq_oss_list);
2196         init_rwsem(&lod->lod_qos.lq_rw_sem);
2197         lod->lod_qos.lq_dirty = 1;
2198         lod->lod_qos.lq_rr.lqr_dirty = 1;
2199         lod->lod_qos.lq_reset = 1;
2200         /* Default priority is toward free space balance */
2201         lod->lod_qos.lq_prio_free = 232;
2202         /* Default threshold for rr (roughly 17%) */
2203         lod->lod_qos.lq_threshold_rr = 43;
2204
2205         /* Set up OST pool environment */
2206         lod->lod_pools_hash_body = cfs_hash_create("POOLS", HASH_POOLS_CUR_BITS,
2207                                                    HASH_POOLS_MAX_BITS,
2208                                                    HASH_POOLS_BKT_BITS, 0,
2209                                                    CFS_HASH_MIN_THETA,
2210                                                    CFS_HASH_MAX_THETA,
2211                                                    &pool_hash_operations,
2212                                                    CFS_HASH_DEFAULT);
2213         if (lod->lod_pools_hash_body == NULL)
2214                 RETURN(-ENOMEM);
2215
2216         INIT_LIST_HEAD(&lod->lod_pool_list);
2217         lod->lod_pool_count = 0;
2218         rc = lod_ost_pool_init(&lod->lod_pool_info, 0);
2219         if (rc)
2220                 GOTO(out_hash, rc);
2221         lod_qos_rr_init(&lod->lod_qos.lq_rr);
2222         rc = lod_ost_pool_init(&lod->lod_qos.lq_rr.lqr_pool, 0);
2223         if (rc)
2224                 GOTO(out_pool_info, rc);
2225
2226         RETURN(0);
2227
2228 out_pool_info:
2229         lod_ost_pool_free(&lod->lod_pool_info);
2230 out_hash:
2231         cfs_hash_putref(lod->lod_pools_hash_body);
2232
2233         return rc;
2234 }
2235
2236 /**
2237  * Release the structures describing the pools.
2238  *
2239  * \param[in] lod       LOD device from which we release the structures
2240  *
2241  * \retval              0 always
2242  */
2243 int lod_pools_fini(struct lod_device *lod)
2244 {
2245         struct obd_device   *obd = lod2obd(lod);
2246         struct pool_desc    *pool, *tmp;
2247         ENTRY;
2248
2249         list_for_each_entry_safe(pool, tmp, &lod->lod_pool_list, pool_list) {
2250                 /* free pool structs */
2251                 CDEBUG(D_INFO, "delete pool %p\n", pool);
2252                 /* In the function below, .hs_keycmp resolves to
2253                  * pool_hashkey_keycmp() */
2254                 /* coverity[overrun-buffer-val] */
2255                 lod_pool_del(obd, pool->pool_name);
2256         }
2257
2258         cfs_hash_putref(lod->lod_pools_hash_body);
2259         lod_ost_pool_free(&(lod->lod_qos.lq_rr.lqr_pool));
2260         lod_ost_pool_free(&lod->lod_pool_info);
2261
2262         RETURN(0);
2263 }