Whamcloud - gitweb
LU-9859 libcfs: replace cfs_rand() with prandom_u32_max()
[fs/lustre-release.git] / lustre / lod / lod_qos.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  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/lod/lod_qos.c
33  *
34  * Implementation of different allocation algorithm used
35  * to distribute objects and data among OSTs.
36  */
37
38 #define DEBUG_SUBSYSTEM S_LOV
39
40 #include <asm/div64.h>
41 #include <linux/random.h>
42
43 #include <libcfs/libcfs.h>
44 #include <uapi/linux/lustre/lustre_idl.h>
45 #include <lustre_swab.h>
46 #include <obd_class.h>
47
48 #include "lod_internal.h"
49
50 /*
51  * force QoS policy (not RR) to be used for testing purposes
52  */
53 #define FORCE_QOS_
54
55 #define D_QOS   D_OTHER
56
57 #define QOS_DEBUG(fmt, ...)     CDEBUG(D_QOS, fmt, ## __VA_ARGS__)
58 #define QOS_CONSOLE(fmt, ...)   LCONSOLE(D_QOS, fmt, ## __VA_ARGS__)
59
60 #define TGT_BAVAIL(i) (OST_TGT(lod,i)->ltd_statfs.os_bavail * \
61                        OST_TGT(lod,i)->ltd_statfs.os_bsize)
62
63 /**
64  * Check whether the target is available for new OST objects.
65  *
66  * Request statfs data from the given target and verify it's active and not
67  * read-only. If so, then it can be used to place new OST objects. This
68  * function also maintains the number of active/inactive targets and sets
69  * dirty flags if those numbers change so others can run re-balance procedures.
70  * No external locking is required.
71  *
72  * \param[in] env       execution environment for this thread
73  * \param[in] d         LOD device
74  * \param[in] index     index of OST target to check
75  * \param[out] sfs      buffer for statfs data
76  *
77  * \retval 0            if the target is good
78  * \retval negative     negated errno on error
79
80  */
81 static int lod_statfs_and_check(const struct lu_env *env, struct lod_device *d,
82                                 int index, struct obd_statfs *sfs)
83 {
84         struct lod_tgt_desc *ost;
85         int                  rc;
86         ENTRY;
87
88         LASSERT(d);
89         ost = OST_TGT(d,index);
90         LASSERT(ost);
91
92         rc = dt_statfs(env, ost->ltd_ost, sfs);
93
94         if (rc == 0 && ((sfs->os_state & OS_STATE_ENOSPC) ||
95             (sfs->os_state & OS_STATE_ENOINO && sfs->os_fprecreated == 0)))
96                 RETURN(-ENOSPC);
97
98         if (rc && rc != -ENOTCONN)
99                 CERROR("%s: statfs: rc = %d\n", lod2obd(d)->obd_name, rc);
100
101         /* If the OST is readonly then we can't allocate objects there */
102         if (sfs->os_state & OS_STATE_READONLY)
103                 rc = -EROFS;
104
105         /* object precreation is skipped on the OST with max_create_count=0 */
106         if (sfs->os_state & OS_STATE_NOPRECREATE)
107                 rc = -ENOBUFS;
108
109         /* check whether device has changed state (active, inactive) */
110         if (rc != 0 && ost->ltd_active) {
111                 /* turned inactive? */
112                 spin_lock(&d->lod_lock);
113                 if (ost->ltd_active) {
114                         ost->ltd_active = 0;
115                         if (rc == -ENOTCONN)
116                                 ost->ltd_connecting = 1;
117
118                         LASSERT(d->lod_desc.ld_active_tgt_count > 0);
119                         d->lod_desc.ld_active_tgt_count--;
120                         d->lod_qos.lq_dirty = 1;
121                         d->lod_qos.lq_rr.lqr_dirty = 1;
122                         CDEBUG(D_CONFIG, "%s: turns inactive\n",
123                                ost->ltd_exp->exp_obd->obd_name);
124                 }
125                 spin_unlock(&d->lod_lock);
126         } else if (rc == 0 && ost->ltd_active == 0) {
127                 /* turned active? */
128                 LASSERTF(d->lod_desc.ld_active_tgt_count < d->lod_ostnr,
129                          "active tgt count %d, ost nr %d\n",
130                          d->lod_desc.ld_active_tgt_count, d->lod_ostnr);
131                 spin_lock(&d->lod_lock);
132                 if (ost->ltd_active == 0) {
133                         ost->ltd_active = 1;
134                         ost->ltd_connecting = 0;
135                         d->lod_desc.ld_active_tgt_count++;
136                         d->lod_qos.lq_dirty = 1;
137                         d->lod_qos.lq_rr.lqr_dirty = 1;
138                         CDEBUG(D_CONFIG, "%s: turns active\n",
139                                ost->ltd_exp->exp_obd->obd_name);
140                 }
141                 spin_unlock(&d->lod_lock);
142         }
143
144         RETURN(rc);
145 }
146
147 /**
148  * Maintain per-target statfs data.
149  *
150  * The function refreshes statfs data for all the targets every N seconds.
151  * The actual N is controlled via procfs and set to LOV_DESC_QOS_MAXAGE_DEFAULT
152  * initially.
153  *
154  * \param[in] env       execution environment for this thread
155  * \param[in] lod       LOD device
156  */
157 void lod_qos_statfs_update(const struct lu_env *env, struct lod_device *lod)
158 {
159         struct obd_device *obd = lod2obd(lod);
160         struct ost_pool *osts = &(lod->lod_pool_info);
161         time64_t max_age;
162         unsigned int i;
163         u64 avail;
164         int idx;
165         ENTRY;
166
167         max_age = ktime_get_seconds() - 2 * lod->lod_desc.ld_qos_maxage;
168
169         if (obd->obd_osfs_age > max_age)
170                 /* statfs data are quite recent, don't need to refresh it */
171                 RETURN_EXIT;
172
173         down_write(&lod->lod_qos.lq_rw_sem);
174
175         if (obd->obd_osfs_age > max_age)
176                 goto out;
177
178         for (i = 0; i < osts->op_count; i++) {
179                 idx = osts->op_array[i];
180                 avail = OST_TGT(lod,idx)->ltd_statfs.os_bavail;
181                 if (lod_statfs_and_check(env, lod, idx,
182                                          &OST_TGT(lod, idx)->ltd_statfs))
183                         continue;
184                 if (OST_TGT(lod,idx)->ltd_statfs.os_bavail != avail)
185                         /* recalculate weigths */
186                         lod->lod_qos.lq_dirty = 1;
187         }
188         obd->obd_osfs_age = ktime_get_seconds();
189
190 out:
191         up_write(&lod->lod_qos.lq_rw_sem);
192         EXIT;
193 }
194
195 /**
196  * Calculate per-OST and per-OSS penalties
197  *
198  * Re-calculate penalties when the configuration changes, active targets
199  * change and after statfs refresh (all these are reflected by lq_dirty flag).
200  * On every OST and OSS: decay the penalty by half for every 8x the update
201  * interval that the device has been idle. That gives lots of time for the
202  * statfs information to be updated (which the penalty is only a proxy for),
203  * and avoids penalizing OSS/OSTs under light load.
204  * See lod_qos_calc_weight() for how penalties are factored into the weight.
205  *
206  * \param[in] lod       LOD device
207  *
208  * \retval 0            on success
209  * \retval -EAGAIN      the number of OSTs isn't enough
210  */
211 static int lod_qos_calc_ppo(struct lod_device *lod)
212 {
213         struct lu_svr_qos *oss;
214         __u64 ba_max, ba_min, temp;
215         __u32 num_active;
216         unsigned int i;
217         int rc, prio_wide;
218         time64_t now, age;
219
220         ENTRY;
221
222         if (!lod->lod_qos.lq_dirty)
223                 GOTO(out, rc = 0);
224
225         num_active = lod->lod_desc.ld_active_tgt_count - 1;
226         if (num_active < 1)
227                 GOTO(out, rc = -EAGAIN);
228
229         /* find bavail on each OSS */
230         list_for_each_entry(oss, &lod->lod_qos.lq_svr_list, lsq_svr_list)
231                 oss->lsq_bavail = 0;
232         lod->lod_qos.lq_active_svr_count = 0;
233
234         /*
235          * How badly user wants to select OSTs "widely" (not recently chosen
236          * and not on recent OSS's).  As opposed to "freely" (free space
237          * avail.) 0-256
238          */
239         prio_wide = 256 - lod->lod_qos.lq_prio_free;
240
241         ba_min = (__u64)(-1);
242         ba_max = 0;
243         now = ktime_get_real_seconds();
244         /* Calculate OST penalty per object
245          * (lod ref taken in lod_qos_prep_create())
246          */
247         cfs_foreach_bit(lod->lod_ost_bitmap, i) {
248                 LASSERT(OST_TGT(lod,i));
249                 temp = TGT_BAVAIL(i);
250                 if (!temp)
251                         continue;
252                 ba_min = min(temp, ba_min);
253                 ba_max = max(temp, ba_max);
254
255                 /* Count the number of usable OSS's */
256                 if (OST_TGT(lod, i)->ltd_qos.ltq_svr->lsq_bavail == 0)
257                         lod->lod_qos.lq_active_svr_count++;
258                 OST_TGT(lod, i)->ltd_qos.ltq_svr->lsq_bavail += temp;
259
260                 /* per-OST penalty is prio * TGT_bavail / (num_ost - 1) / 2 */
261                 temp >>= 1;
262                 do_div(temp, num_active);
263                 OST_TGT(lod,i)->ltd_qos.ltq_penalty_per_obj =
264                         (temp * prio_wide) >> 8;
265
266                 age = (now - OST_TGT(lod,i)->ltd_qos.ltq_used) >> 3;
267                 if (lod->lod_qos.lq_reset ||
268                     age > 32 * lod->lod_desc.ld_qos_maxage)
269                         OST_TGT(lod,i)->ltd_qos.ltq_penalty = 0;
270                 else if (age > lod->lod_desc.ld_qos_maxage)
271                         /* Decay OST penalty. */
272                         OST_TGT(lod,i)->ltd_qos.ltq_penalty >>=
273                                 (age / lod->lod_desc.ld_qos_maxage);
274         }
275
276         num_active = lod->lod_qos.lq_active_svr_count - 1;
277         if (num_active < 1) {
278                 /* If there's only 1 OSS, we can't penalize it, so instead
279                    we have to double the OST penalty */
280                 num_active = 1;
281                 cfs_foreach_bit(lod->lod_ost_bitmap, i)
282                         OST_TGT(lod,i)->ltd_qos.ltq_penalty_per_obj <<= 1;
283         }
284
285         /* Per-OSS penalty is prio * oss_avail / oss_osts / (num_oss - 1) / 2 */
286         list_for_each_entry(oss, &lod->lod_qos.lq_svr_list, lsq_svr_list) {
287                 temp = oss->lsq_bavail >> 1;
288                 do_div(temp, oss->lsq_tgt_count * num_active);
289                 oss->lsq_penalty_per_obj = (temp * prio_wide) >> 8;
290
291                 age = (now - oss->lsq_used) >> 3;
292                 if (lod->lod_qos.lq_reset ||
293                     age > 32 * lod->lod_desc.ld_qos_maxage)
294                         oss->lsq_penalty = 0;
295                 else if (age > lod->lod_desc.ld_qos_maxage)
296                         /* Decay OSS penalty. */
297                         oss->lsq_penalty >>= age / lod->lod_desc.ld_qos_maxage;
298         }
299
300         lod->lod_qos.lq_dirty = 0;
301         lod->lod_qos.lq_reset = 0;
302
303         /* If each ost has almost same free space,
304          * do rr allocation for better creation performance */
305         lod->lod_qos.lq_same_space = 0;
306         if ((ba_max * (256 - lod->lod_qos.lq_threshold_rr)) >> 8 < ba_min) {
307                 lod->lod_qos.lq_same_space = 1;
308                 /* Reset weights for the next time we enter qos mode */
309                 lod->lod_qos.lq_reset = 1;
310         }
311         rc = 0;
312
313 out:
314 #ifndef FORCE_QOS
315         if (!rc && lod->lod_qos.lq_same_space)
316                 RETURN(-EAGAIN);
317 #endif
318         RETURN(rc);
319 }
320
321 /**
322  * Calculate weight for a given OST target.
323  *
324  * The final OST weight is the number of bytes available minus the OST and
325  * OSS penalties.  See lod_qos_calc_ppo() for how penalties are calculated.
326  *
327  * \param[in] lod       LOD device, where OST targets are listed
328  * \param[in] i         OST target index
329  *
330  * \retval              0
331  */
332 static int lod_qos_calc_weight(struct lod_device *lod, int i)
333 {
334         __u64 temp, temp2;
335
336         temp = TGT_BAVAIL(i);
337         temp2 = OST_TGT(lod, i)->ltd_qos.ltq_penalty +
338                 OST_TGT(lod, i)->ltd_qos.ltq_svr->lsq_penalty;
339         if (temp < temp2)
340                 OST_TGT(lod, i)->ltd_qos.ltq_weight = 0;
341         else
342                 OST_TGT(lod, i)->ltd_qos.ltq_weight = temp - temp2;
343         return 0;
344 }
345
346 /**
347  * Re-calculate weights.
348  *
349  * The function is called when some OST target was used for a new object. In
350  * this case we should re-calculate all the weights to keep new allocations
351  * balanced well.
352  *
353  * \param[in] lod       LOD device
354  * \param[in] osts      OST pool where a new object was placed
355  * \param[in] index     OST target where a new object was placed
356  * \param[out] total_wt new total weight for the pool
357  *
358  * \retval              0
359  */
360 static int lod_qos_used(struct lod_device *lod, struct ost_pool *osts,
361                         __u32 index, __u64 *total_wt)
362 {
363         struct lod_tgt_desc *ost;
364         struct lu_svr_qos  *oss;
365         unsigned int j;
366         ENTRY;
367
368         ost = OST_TGT(lod,index);
369         LASSERT(ost);
370
371         /* Don't allocate on this devuce anymore, until the next alloc_qos */
372         ost->ltd_qos.ltq_usable = 0;
373
374         oss = ost->ltd_qos.ltq_svr;
375
376         /* Decay old penalty by half (we're adding max penalty, and don't
377            want it to run away.) */
378         ost->ltd_qos.ltq_penalty >>= 1;
379         oss->lsq_penalty >>= 1;
380
381         /* mark the OSS and OST as recently used */
382         ost->ltd_qos.ltq_used = oss->lsq_used = ktime_get_real_seconds();
383
384         /* Set max penalties for this OST and OSS */
385         ost->ltd_qos.ltq_penalty +=
386                 ost->ltd_qos.ltq_penalty_per_obj * lod->lod_ostnr;
387         oss->lsq_penalty += oss->lsq_penalty_per_obj *
388                 lod->lod_qos.lq_active_svr_count;
389
390         /* Decrease all OSS penalties */
391         list_for_each_entry(oss, &lod->lod_qos.lq_svr_list, lsq_svr_list) {
392                 if (oss->lsq_penalty < oss->lsq_penalty_per_obj)
393                         oss->lsq_penalty = 0;
394                 else
395                         oss->lsq_penalty -= oss->lsq_penalty_per_obj;
396         }
397
398         *total_wt = 0;
399         /* Decrease all OST penalties */
400         for (j = 0; j < osts->op_count; j++) {
401                 int i;
402
403                 i = osts->op_array[j];
404                 if (!cfs_bitmap_check(lod->lod_ost_bitmap, i))
405                         continue;
406
407                 ost = OST_TGT(lod,i);
408                 LASSERT(ost);
409
410                 if (ost->ltd_qos.ltq_penalty <
411                                 ost->ltd_qos.ltq_penalty_per_obj)
412                         ost->ltd_qos.ltq_penalty = 0;
413                 else
414                         ost->ltd_qos.ltq_penalty -=
415                                 ost->ltd_qos.ltq_penalty_per_obj;
416
417                 lod_qos_calc_weight(lod, i);
418
419                 /* Recalc the total weight of usable osts */
420                 if (ost->ltd_qos.ltq_usable)
421                         *total_wt += ost->ltd_qos.ltq_weight;
422
423                 QOS_DEBUG("recalc tgt %d usable=%d avail=%llu"
424                           " ostppo=%llu ostp=%llu ossppo=%llu"
425                           " ossp=%llu wt=%llu\n",
426                           i, ost->ltd_qos.ltq_usable, TGT_BAVAIL(i) >> 10,
427                           ost->ltd_qos.ltq_penalty_per_obj >> 10,
428                           ost->ltd_qos.ltq_penalty >> 10,
429                           ost->ltd_qos.ltq_svr->lsq_penalty_per_obj >> 10,
430                           ost->ltd_qos.ltq_svr->lsq_penalty >> 10,
431                           ost->ltd_qos.ltq_weight >> 10);
432         }
433
434         RETURN(0);
435 }
436
437 void lod_qos_rr_init(struct lu_qos_rr *lqr)
438 {
439         spin_lock_init(&lqr->lqr_alloc);
440         lqr->lqr_dirty = 1;
441 }
442
443 #define LOV_QOS_EMPTY ((__u32)-1)
444
445 /**
446  * Calculate optimal round-robin order with regard to OSSes.
447  *
448  * Place all the OSTs from pool \a src_pool in a special array to be used for
449  * round-robin (RR) stripe allocation.  The placement algorithm interleaves
450  * OSTs from the different OSSs so that RR allocation can balance OSSs evenly.
451  * Resorts the targets when the number of active targets changes (because of
452  * a new target or activation/deactivation).
453  *
454  * \param[in] lod       LOD device
455  * \param[in] src_pool  OST pool
456  * \param[in] lqr       round-robin list
457  *
458  * \retval 0            on success
459  * \retval -ENOMEM      fails to allocate the array
460  */
461 static int lod_qos_calc_rr(struct lod_device *lod, struct ost_pool *src_pool,
462                            struct lu_qos_rr *lqr)
463 {
464         struct lu_svr_qos  *oss;
465         struct lod_tgt_desc *ost;
466         unsigned placed, real_count;
467         unsigned int i;
468         int rc;
469         ENTRY;
470
471         if (!lqr->lqr_dirty) {
472                 LASSERT(lqr->lqr_pool.op_size);
473                 RETURN(0);
474         }
475
476         /* Do actual allocation. */
477         down_write(&lod->lod_qos.lq_rw_sem);
478
479         /*
480          * Check again. While we were sleeping on @lq_rw_sem something could
481          * change.
482          */
483         if (!lqr->lqr_dirty) {
484                 LASSERT(lqr->lqr_pool.op_size);
485                 up_write(&lod->lod_qos.lq_rw_sem);
486                 RETURN(0);
487         }
488
489         real_count = src_pool->op_count;
490
491         /* Zero the pool array */
492         /* alloc_rr is holding a read lock on the pool, so nobody is adding/
493            deleting from the pool. The lq_rw_sem insures that nobody else
494            is reading. */
495         lqr->lqr_pool.op_count = real_count;
496         rc = lod_ost_pool_extend(&lqr->lqr_pool, real_count);
497         if (rc) {
498                 up_write(&lod->lod_qos.lq_rw_sem);
499                 RETURN(rc);
500         }
501         for (i = 0; i < lqr->lqr_pool.op_count; i++)
502                 lqr->lqr_pool.op_array[i] = LOV_QOS_EMPTY;
503
504         /* Place all the OSTs from 1 OSS at the same time. */
505         placed = 0;
506         list_for_each_entry(oss, &lod->lod_qos.lq_svr_list, lsq_svr_list) {
507                 int j = 0;
508
509                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
510                         int next;
511
512                         if (!cfs_bitmap_check(lod->lod_ost_bitmap,
513                                                 src_pool->op_array[i]))
514                                 continue;
515
516                         ost = OST_TGT(lod,src_pool->op_array[i]);
517                         LASSERT(ost && ost->ltd_ost);
518                         if (ost->ltd_qos.ltq_svr != oss)
519                                 continue;
520
521                         /* Evenly space these OSTs across arrayspace */
522                         next = j * lqr->lqr_pool.op_count / oss->lsq_tgt_count;
523                         while (lqr->lqr_pool.op_array[next] != LOV_QOS_EMPTY)
524                                 next = (next + 1) % lqr->lqr_pool.op_count;
525
526                         lqr->lqr_pool.op_array[next] = src_pool->op_array[i];
527                         j++;
528                         placed++;
529                 }
530         }
531
532         lqr->lqr_dirty = 0;
533         up_write(&lod->lod_qos.lq_rw_sem);
534
535         if (placed != real_count) {
536                 /* This should never happen */
537                 LCONSOLE_ERROR_MSG(0x14e, "Failed to place all OSTs in the "
538                                    "round-robin list (%d of %d).\n",
539                                    placed, real_count);
540                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
541                         LCONSOLE(D_WARNING, "rr #%d ost idx=%d\n", i,
542                                  lqr->lqr_pool.op_array[i]);
543                 }
544                 lqr->lqr_dirty = 1;
545                 RETURN(-EAGAIN);
546         }
547
548 #if 0
549         for (i = 0; i < lqr->lqr_pool.op_count; i++)
550                 QOS_CONSOLE("rr #%d ost idx=%d\n", i, lqr->lqr_pool.op_array[i]);
551 #endif
552
553         RETURN(0);
554 }
555
556 /**
557  * Instantiate and declare creation of a new object.
558  *
559  * The function instantiates LU representation for a new object on the
560  * specified device. Also it declares an intention to create that
561  * object on the storage target.
562  *
563  * Note lu_object_anon() is used which is a trick with regard to LU/OSD
564  * infrastructure - in the existing precreation framework we can't assign FID
565  * at this moment, we do this later once a transaction is started. So the
566  * special method instantiates FID-less object in the cache and later it
567  * will get a FID and proper placement in LU cache.
568  *
569  * \param[in] env       execution environment for this thread
570  * \param[in] d         LOD device
571  * \param[in] ost_idx   OST target index where the object is being created
572  * \param[in] th        transaction handle
573  *
574  * \retval              object ptr on success, ERR_PTR() otherwise
575  */
576 static struct dt_object *lod_qos_declare_object_on(const struct lu_env *env,
577                                                    struct lod_device *d,
578                                                    __u32 ost_idx,
579                                                    struct thandle *th)
580 {
581         struct lod_tgt_desc *ost;
582         struct lu_object *o, *n;
583         struct lu_device *nd;
584         struct dt_object *dt;
585         int               rc;
586         ENTRY;
587
588         LASSERT(d);
589         LASSERT(ost_idx < d->lod_osts_size);
590         ost = OST_TGT(d,ost_idx);
591         LASSERT(ost);
592         LASSERT(ost->ltd_ost);
593
594         nd = &ost->ltd_ost->dd_lu_dev;
595
596         /*
597          * allocate anonymous object with zero fid, real fid
598          * will be assigned by OSP within transaction
599          * XXX: to be fixed with fully-functional OST fids
600          */
601         o = lu_object_anon(env, nd, NULL);
602         if (IS_ERR(o))
603                 GOTO(out, dt = ERR_PTR(PTR_ERR(o)));
604
605         n = lu_object_locate(o->lo_header, nd->ld_type);
606         if (unlikely(n == NULL)) {
607                 CERROR("can't find slice\n");
608                 lu_object_put(env, o);
609                 GOTO(out, dt = ERR_PTR(-EINVAL));
610         }
611
612         dt = container_of(n, struct dt_object, do_lu);
613
614         rc = lod_sub_declare_create(env, dt, NULL, NULL, NULL, th);
615         if (rc < 0) {
616                 CDEBUG(D_OTHER, "can't declare creation on #%u: %d\n",
617                        ost_idx, rc);
618                 lu_object_put(env, o);
619                 dt = ERR_PTR(rc);
620         }
621
622 out:
623         RETURN(dt);
624 }
625
626 /**
627  * Calculate a minimum acceptable stripe count.
628  *
629  * Return an acceptable stripe count depending on flag LOV_USES_DEFAULT_STRIPE:
630  * all stripes or 3/4 of stripes.
631  *
632  * \param[in] stripe_count      number of stripes requested
633  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
634  *
635  * \retval                      acceptable stripecount
636  */
637 static int min_stripe_count(__u32 stripe_count, int flags)
638 {
639         return (flags & LOV_USES_DEFAULT_STRIPE ?
640                 stripe_count - (stripe_count / 4) : stripe_count);
641 }
642
643 #define LOV_CREATE_RESEED_MULT 30
644 #define LOV_CREATE_RESEED_MIN  2000
645
646 /**
647  * Initialize temporary OST-in-use array.
648  *
649  * Allocate or extend the array used to mark targets already assigned to a new
650  * striping so they are not used more than once.
651  *
652  * \param[in] env       execution environment for this thread
653  * \param[in] stripes   number of items needed in the array
654  *
655  * \retval 0            on success
656  * \retval -ENOMEM      on error
657  */
658 static inline int lod_qos_ost_in_use_clear(const struct lu_env *env,
659                                            __u32 stripes)
660 {
661         struct lod_thread_info *info = lod_env_info(env);
662
663         if (info->lti_ea_store_size < sizeof(int) * stripes)
664                 lod_ea_store_resize(info, stripes * sizeof(int));
665         if (info->lti_ea_store_size < sizeof(int) * stripes) {
666                 CERROR("can't allocate memory for ost-in-use array\n");
667                 return -ENOMEM;
668         }
669         memset(info->lti_ea_store, -1, sizeof(int) * stripes);
670         return 0;
671 }
672
673 /**
674  * Remember a target in the array of used targets.
675  *
676  * Mark the given target as used for a new striping being created. The status
677  * of an OST in a striping can be checked with lod_qos_is_ost_used().
678  *
679  * \param[in] env       execution environment for this thread
680  * \param[in] idx       index in the array
681  * \param[in] ost       OST target index to mark as used
682  */
683 static inline void lod_qos_ost_in_use(const struct lu_env *env,
684                                       int idx, int ost)
685 {
686         struct lod_thread_info *info = lod_env_info(env);
687         int *osts = info->lti_ea_store;
688
689         LASSERT(info->lti_ea_store_size >= idx * sizeof(int));
690         osts[idx] = ost;
691 }
692
693 /**
694  * Check is OST used in a striping.
695  *
696  * Checks whether OST with the given index is marked as used in the temporary
697  * array (see lod_qos_ost_in_use()).
698  *
699  * \param[in] env       execution environment for this thread
700  * \param[in] ost       OST target index to check
701  * \param[in] stripes   the number of items used in the array already
702  *
703  * \retval 0            not used
704  * \retval 1            used
705  */
706 static int lod_qos_is_ost_used(const struct lu_env *env, int ost, __u32 stripes)
707 {
708         struct lod_thread_info *info = lod_env_info(env);
709         int *osts = info->lti_ea_store;
710         __u32 j;
711
712         for (j = 0; j < stripes; j++) {
713                 if (osts[j] == ost)
714                         return 1;
715         }
716         return 0;
717 }
718
719 static inline bool
720 lod_obj_is_ost_use_skip_cb(const struct lu_env *env, struct lod_object *lo,
721                            int comp_idx, struct lod_obj_stripe_cb_data *data)
722 {
723         struct lod_layout_component *comp = &lo->ldo_comp_entries[comp_idx];
724
725         return comp->llc_ost_indices == NULL;
726 }
727
728 static inline int
729 lod_obj_is_ost_use_cb(const struct lu_env *env, struct lod_object *lo,
730                       int comp_idx, struct lod_obj_stripe_cb_data *data)
731 {
732         struct lod_layout_component *comp = &lo->ldo_comp_entries[comp_idx];
733         int i;
734
735         for (i = 0; i < comp->llc_stripe_count; i++) {
736                 if (comp->llc_ost_indices[i] == data->locd_ost_index) {
737                         data->locd_ost_index = -1;
738                         return -EEXIST;
739                 }
740         }
741
742         return 0;
743 }
744
745 /**
746  * Check is OST used in a composite layout
747  *
748  * \param[in] lo        lod object
749  * \param[in] ost       OST target index to check
750  *
751  * \retval false        not used
752  * \retval true         used
753  */
754 static inline bool lod_comp_is_ost_used(const struct lu_env *env,
755                                        struct lod_object *lo, int ost)
756 {
757         struct lod_obj_stripe_cb_data data = { { 0 } };
758
759         data.locd_ost_index = ost;
760         data.locd_comp_skip_cb = lod_obj_is_ost_use_skip_cb;
761         data.locd_comp_cb = lod_obj_is_ost_use_cb;
762
763         (void)lod_obj_for_each_stripe(env, lo, NULL, &data);
764
765         return data.locd_ost_index == -1;
766 }
767
768 static inline void lod_avoid_update(struct lod_object *lo,
769                                     struct lod_avoid_guide *lag)
770 {
771         if (!lod_is_flr(lo))
772                 return;
773
774         lag->lag_ost_avail--;
775 }
776
777 static inline bool lod_should_avoid_ost(struct lod_object *lo,
778                                         struct lod_avoid_guide *lag,
779                                         __u32 index)
780 {
781         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
782         struct lod_tgt_desc *ost = OST_TGT(lod, index);
783         struct lu_svr_qos *lsq = ost->ltd_qos.ltq_svr;
784         bool used = false;
785         int i;
786
787         if (!cfs_bitmap_check(lod->lod_ost_bitmap, index)) {
788                 QOS_DEBUG("OST%d: been used in conflicting mirror component\n",
789                           index);
790                 return true;
791         }
792
793         /**
794          * we've tried our best, all available OSTs have been used in
795          * overlapped components in the other mirror
796          */
797         if (lag->lag_ost_avail == 0)
798                 return false;
799
800         /* check OSS use */
801         for (i = 0; i < lag->lag_oaa_count; i++) {
802                 if (lag->lag_oss_avoid_array[i] == lsq->lsq_id) {
803                         used = true;
804                         break;
805                 }
806         }
807         /**
808          * if the OSS which OST[index] resides has not been used, we'd like to
809          * use it
810          */
811         if (!used)
812                 return false;
813
814         /* if the OSS has been used, check whether the OST has been used */
815         if (!cfs_bitmap_check(lag->lag_ost_avoid_bitmap, index))
816                 used = false;
817         else
818                 QOS_DEBUG("OST%d: been used in conflicting mirror component\n",
819                           index);
820         return used;
821 }
822
823 static int lod_check_and_reserve_ost(const struct lu_env *env,
824                                      struct lod_object *lo,
825                                      struct lod_layout_component *lod_comp,
826                                      struct obd_statfs *sfs, __u32 ost_idx,
827                                      __u32 speed, __u32 *s_idx,
828                                      struct dt_object **stripe,
829                                      __u32 *ost_indices,
830                                      struct thandle *th,
831                                      bool *overstriped)
832 {
833         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
834         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
835         struct dt_object   *o;
836         __u32 stripe_idx = *s_idx;
837         int rc;
838         ENTRY;
839
840         rc = lod_statfs_and_check(env, lod, ost_idx, sfs);
841         if (rc)
842                 RETURN(rc);
843
844         /*
845          * We expect number of precreated objects in f_ffree at
846          * the first iteration, skip OSPs with no objects ready
847          */
848         if (sfs->os_fprecreated == 0 && speed == 0) {
849                 QOS_DEBUG("#%d: precreation is empty\n", ost_idx);
850                 RETURN(rc);
851         }
852
853         /*
854          * try to use another OSP if this one is degraded
855          */
856         if (sfs->os_state & OS_STATE_DEGRADED && speed < 2) {
857                 QOS_DEBUG("#%d: degraded\n", ost_idx);
858                 RETURN(rc);
859         }
860
861         /*
862          * try not allocate on OST which has been used by other
863          * component
864          */
865         if (speed == 0 && lod_comp_is_ost_used(env, lo, ost_idx)) {
866                 QOS_DEBUG("iter %d: OST%d used by other component\n",
867                           speed, ost_idx);
868                 RETURN(rc);
869         }
870
871         /**
872          * try not allocate OSTs used by conflicting component of other mirrors
873          * for the first and second time.
874          */
875         if (speed < 2 && lod_should_avoid_ost(lo, lag, ost_idx)) {
876                 QOS_DEBUG("iter %d: OST%d used by conflicting mirror "
877                           "component\n", speed, ost_idx);
878                 RETURN(rc);
879         }
880
881         /* do not put >1 objects on a single OST, except for overstriping */
882         if (lod_qos_is_ost_used(env, ost_idx, stripe_idx)) {
883                 if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
884                         *overstriped = true;
885                 else
886                         RETURN(rc);
887         }
888
889         o = lod_qos_declare_object_on(env, lod, ost_idx, th);
890         if (IS_ERR(o)) {
891                 CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
892                        ost_idx, (int) PTR_ERR(o));
893                 rc = PTR_ERR(o);
894                 RETURN(rc);
895         }
896
897         /*
898          * We've successfully declared (reserved) an object
899          */
900         lod_avoid_update(lo, lag);
901         lod_qos_ost_in_use(env, stripe_idx, ost_idx);
902         stripe[stripe_idx] = o;
903         ost_indices[stripe_idx] = ost_idx;
904         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_LOV_CREATE_RACE, 2);
905         stripe_idx++;
906         *s_idx = stripe_idx;
907
908         RETURN(rc);
909 }
910
911 /**
912  * Allocate a striping using round-robin algorithm.
913  *
914  * Allocates a new striping using round-robin algorithm. The function refreshes
915  * all the internal structures (statfs cache, array of available OSTs sorted
916  * with regard to OSS, etc). The number of stripes required is taken from the
917  * object (must be prepared by the caller), but can change if the flag
918  * LOV_USES_DEFAULT_STRIPE is supplied. The caller should ensure nobody else
919  * is trying to create a striping on the object in parallel. All the internal
920  * structures (like pools, etc) are protected and no additional locking is
921  * required. The function succeeds even if a single stripe is allocated. To save
922  * time we give priority to targets which already have objects precreated.
923  * Full OSTs are skipped (see lod_qos_dev_is_full() for the details).
924  *
925  * \param[in] env               execution environment for this thread
926  * \param[in] lo                LOD object
927  * \param[out] stripe           striping created
928  * \param[out] ost_indices      ost indices of striping created
929  * \param[in] flags             allocation flags (0 or LOV_USES_DEFAULT_STRIPE)
930  * \param[in] th                transaction handle
931  * \param[in] comp_idx          index of ldo_comp_entries
932  *
933  * \retval 0            on success
934  * \retval -ENOSPC      if not enough OSTs are found
935  * \retval negative     negated errno for other failures
936  */
937 static int lod_alloc_rr(const struct lu_env *env, struct lod_object *lo,
938                         struct dt_object **stripe, __u32 *ost_indices,
939                         int flags, struct thandle *th, int comp_idx)
940 {
941         struct lod_layout_component *lod_comp;
942         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
943         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
944         struct pool_desc  *pool = NULL;
945         struct ost_pool   *osts;
946         struct lu_qos_rr *lqr;
947         unsigned int    i, array_idx;
948         __u32 ost_start_idx_temp;
949         __u32 stripe_idx = 0;
950         __u32 stripe_count, stripe_count_min, ost_idx;
951         int rc, speed = 0, ost_connecting = 0;
952         int stripes_per_ost = 1;
953         bool overstriped = false;
954         ENTRY;
955
956         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
957         lod_comp = &lo->ldo_comp_entries[comp_idx];
958         stripe_count = lod_comp->llc_stripe_count;
959         stripe_count_min = min_stripe_count(stripe_count, flags);
960
961         if (lod_comp->llc_pool != NULL)
962                 pool = lod_find_pool(m, lod_comp->llc_pool);
963
964         if (pool != NULL) {
965                 down_read(&pool_tgt_rw_sem(pool));
966                 osts = &(pool->pool_obds);
967                 lqr = &(pool->pool_rr);
968         } else {
969                 osts = &(m->lod_pool_info);
970                 lqr = &(m->lod_qos.lq_rr);
971         }
972
973         rc = lod_qos_calc_rr(m, osts, lqr);
974         if (rc)
975                 GOTO(out, rc);
976
977         rc = lod_qos_ost_in_use_clear(env, stripe_count);
978         if (rc)
979                 GOTO(out, rc);
980
981         down_read(&m->lod_qos.lq_rw_sem);
982         spin_lock(&lqr->lqr_alloc);
983         if (--lqr->lqr_start_count <= 0) {
984                 lqr->lqr_start_idx = prandom_u32_max(osts->op_count);
985                 lqr->lqr_start_count =
986                         (LOV_CREATE_RESEED_MIN / max(osts->op_count, 1U) +
987                          LOV_CREATE_RESEED_MULT) * max(osts->op_count, 1U);
988         } else if (stripe_count_min >= osts->op_count ||
989                         lqr->lqr_start_idx > osts->op_count) {
990                 /* If we have allocated from all of the OSTs, slowly
991                  * precess the next start if the OST/stripe count isn't
992                  * already doing this for us. */
993                 lqr->lqr_start_idx %= osts->op_count;
994                 if (stripe_count > 1 && (osts->op_count % stripe_count) != 1)
995                         ++lqr->lqr_offset_idx;
996         }
997         ost_start_idx_temp = lqr->lqr_start_idx;
998
999 repeat_find:
1000
1001         QOS_DEBUG("pool '%s' want %d start_idx %d start_count %d offset %d "
1002                   "active %d count %d\n",
1003                   lod_comp->llc_pool ? lod_comp->llc_pool : "",
1004                   stripe_count, lqr->lqr_start_idx, lqr->lqr_start_count,
1005                   lqr->lqr_offset_idx, osts->op_count, osts->op_count);
1006
1007         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1008                 stripes_per_ost =
1009                         (lod_comp->llc_stripe_count - 1)/osts->op_count + 1;
1010
1011         for (i = 0; i < osts->op_count * stripes_per_ost
1012              && stripe_idx < stripe_count; i++) {
1013                 array_idx = (lqr->lqr_start_idx + lqr->lqr_offset_idx) %
1014                                 osts->op_count;
1015                 ++lqr->lqr_start_idx;
1016                 ost_idx = lqr->lqr_pool.op_array[array_idx];
1017
1018                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
1019                           i, lqr->lqr_start_idx, /* XXX: active*/ 0,
1020                           stripe_idx, array_idx, ost_idx);
1021
1022                 if ((ost_idx == LOV_QOS_EMPTY) ||
1023                     !cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
1024                         continue;
1025
1026                 /* Fail Check before osc_precreate() is called
1027                    so we can only 'fail' single OSC. */
1028                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1029                         continue;
1030
1031                 spin_unlock(&lqr->lqr_alloc);
1032                 rc = lod_check_and_reserve_ost(env, lo, lod_comp, sfs, ost_idx,
1033                                                speed, &stripe_idx, stripe,
1034                                                ost_indices, th, &overstriped);
1035                 spin_lock(&lqr->lqr_alloc);
1036
1037                 if (rc != 0 && OST_TGT(m, ost_idx)->ltd_connecting)
1038                         ost_connecting = 1;
1039         }
1040         if ((speed < 2) && (stripe_idx < stripe_count_min)) {
1041                 /* Try again, allowing slower OSCs */
1042                 speed++;
1043                 lqr->lqr_start_idx = ost_start_idx_temp;
1044
1045                 ost_connecting = 0;
1046                 goto repeat_find;
1047         }
1048
1049         spin_unlock(&lqr->lqr_alloc);
1050         up_read(&m->lod_qos.lq_rw_sem);
1051
1052         /* If there are enough OSTs, a component with overstriping requested
1053          * will not actually end up overstriped.  The comp should reflect this.
1054          */
1055         if (!overstriped)
1056                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1057
1058         if (stripe_idx) {
1059                 lod_comp->llc_stripe_count = stripe_idx;
1060                 /* at least one stripe is allocated */
1061                 rc = 0;
1062         } else {
1063                 /* nobody provided us with a single object */
1064                 if (ost_connecting)
1065                         rc = -EINPROGRESS;
1066                 else
1067                         rc = -ENOSPC;
1068         }
1069
1070 out:
1071         if (pool != NULL) {
1072                 up_read(&pool_tgt_rw_sem(pool));
1073                 /* put back ref got by lod_find_pool() */
1074                 lod_pool_putref(pool);
1075         }
1076
1077         RETURN(rc);
1078 }
1079
1080 /**
1081  * Allocate a specific striping layout on a user defined set of OSTs.
1082  *
1083  * Allocates new striping using the OST index range provided by the data from
1084  * the lmm_obejcts contained in the lov_user_md passed to this method. Full
1085  * OSTs are not considered. The exact order of OSTs requested by the user
1086  * is respected as much as possible depending on OST status. The number of
1087  * stripes needed and stripe offset are taken from the object. If that number
1088  * can not be met, then the function returns a failure and then it's the
1089  * caller's responsibility to release the stripes allocated. All the internal
1090  * structures are protected, but no concurrent allocation is allowed on the
1091  * same objects.
1092  *
1093  * \param[in] env               execution environment for this thread
1094  * \param[in] lo                LOD object
1095  * \param[out] stripe           striping created
1096  * \param[out] ost_indices      ost indices of striping created
1097  * \param[in] th                transaction handle
1098  * \param[in] comp_idx          index of ldo_comp_entries
1099  *
1100  * \retval 0            on success
1101  * \retval -ENODEV      OST index does not exist on file system
1102  * \retval -EINVAL      requested OST index is invalid
1103  * \retval negative     negated errno on error
1104  */
1105 static int lod_alloc_ost_list(const struct lu_env *env, struct lod_object *lo,
1106                               struct dt_object **stripe, __u32 *ost_indices,
1107                               struct thandle *th, int comp_idx)
1108 {
1109         struct lod_layout_component *lod_comp;
1110         struct lod_device       *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1111         struct obd_statfs       *sfs = &lod_env_info(env)->lti_osfs;
1112         struct dt_object        *o;
1113         unsigned int            array_idx = 0;
1114         int                     stripe_count = 0;
1115         int                     i;
1116         int                     rc = -EINVAL;
1117         ENTRY;
1118
1119         /* for specific OSTs layout */
1120         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1121         lod_comp = &lo->ldo_comp_entries[comp_idx];
1122         LASSERT(lod_comp->llc_ostlist.op_array);
1123         LASSERT(lod_comp->llc_ostlist.op_count);
1124
1125         rc = lod_qos_ost_in_use_clear(env, lod_comp->llc_stripe_count);
1126         if (rc < 0)
1127                 RETURN(rc);
1128
1129         if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT)
1130                 lod_comp->llc_stripe_offset =
1131                                 lod_comp->llc_ostlist.op_array[0];
1132
1133         for (i = 0; i < lod_comp->llc_stripe_count; i++) {
1134                 if (lod_comp->llc_ostlist.op_array[i] ==
1135                     lod_comp->llc_stripe_offset) {
1136                         array_idx = i;
1137                         break;
1138                 }
1139         }
1140         if (i == lod_comp->llc_stripe_count) {
1141                 CDEBUG(D_OTHER,
1142                        "%s: start index %d not in the specified list of OSTs\n",
1143                        lod2obd(m)->obd_name, lod_comp->llc_stripe_offset);
1144                 RETURN(-EINVAL);
1145         }
1146
1147         for (i = 0; i < lod_comp->llc_stripe_count;
1148              i++, array_idx = (array_idx + 1) % lod_comp->llc_stripe_count) {
1149                 __u32 ost_idx = lod_comp->llc_ostlist.op_array[array_idx];
1150
1151                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx)) {
1152                         rc = -ENODEV;
1153                         break;
1154                 }
1155
1156                 /* do not put >1 objects on a single OST, except for
1157                  * overstriping
1158                  */
1159                 if (lod_qos_is_ost_used(env, ost_idx, stripe_count) &&
1160                     !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)) {
1161                         rc = -EINVAL;
1162                         break;
1163                 }
1164
1165                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
1166                 if (rc < 0) /* this OSP doesn't feel well */
1167                         break;
1168
1169                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1170                 if (IS_ERR(o)) {
1171                         rc = PTR_ERR(o);
1172                         CDEBUG(D_OTHER,
1173                                "%s: can't declare new object on #%u: %d\n",
1174                                lod2obd(m)->obd_name, ost_idx, rc);
1175                         break;
1176                 }
1177
1178                 /*
1179                  * We've successfully declared (reserved) an object
1180                  */
1181                 lod_qos_ost_in_use(env, stripe_count, ost_idx);
1182                 stripe[stripe_count] = o;
1183                 ost_indices[stripe_count] = ost_idx;
1184                 stripe_count++;
1185         }
1186
1187         RETURN(rc);
1188 }
1189
1190 /**
1191  * Allocate a striping on a predefined set of OSTs.
1192  *
1193  * Allocates new layout starting from OST index in lo->ldo_stripe_offset.
1194  * Full OSTs are not considered. The exact order of OSTs is not important and
1195  * varies depending on OST status. The allocation procedure prefers the targets
1196  * with precreated objects ready. The number of stripes needed and stripe
1197  * offset are taken from the object. If that number cannot be met, then the
1198  * function returns an error and then it's the caller's responsibility to
1199  * release the stripes allocated. All the internal structures are protected,
1200  * but no concurrent allocation is allowed on the same objects.
1201  *
1202  * \param[in] env               execution environment for this thread
1203  * \param[in] lo                LOD object
1204  * \param[out] stripe           striping created
1205  * \param[out] ost_indices      ost indices of striping created
1206  * \param[in] flags             not used
1207  * \param[in] th                transaction handle
1208  * \param[in] comp_idx          index of ldo_comp_entries
1209  *
1210  * \retval 0            on success
1211  * \retval -ENOSPC      if no OST objects are available at all
1212  * \retval -EFBIG       if not enough OST objects are found
1213  * \retval -EINVAL      requested offset is invalid
1214  * \retval negative     errno on failure
1215  */
1216 static int lod_alloc_specific(const struct lu_env *env, struct lod_object *lo,
1217                               struct dt_object **stripe, __u32 *ost_indices,
1218                               int flags, struct thandle *th, int comp_idx)
1219 {
1220         struct lod_layout_component *lod_comp;
1221         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1222         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
1223         struct dt_object *o;
1224         __u32 ost_idx;
1225         unsigned int i, array_idx, ost_count;
1226         int rc, stripe_num = 0;
1227         int speed = 0;
1228         struct pool_desc  *pool = NULL;
1229         struct ost_pool   *osts;
1230         int stripes_per_ost = 1;
1231         bool overstriped = false;
1232         ENTRY;
1233
1234         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1235         lod_comp = &lo->ldo_comp_entries[comp_idx];
1236
1237         rc = lod_qos_ost_in_use_clear(env, lod_comp->llc_stripe_count);
1238         if (rc)
1239                 GOTO(out, rc);
1240
1241         if (lod_comp->llc_pool != NULL)
1242                 pool = lod_find_pool(m, lod_comp->llc_pool);
1243
1244         if (pool != NULL) {
1245                 down_read(&pool_tgt_rw_sem(pool));
1246                 osts = &(pool->pool_obds);
1247         } else {
1248                 osts = &(m->lod_pool_info);
1249         }
1250
1251         ost_count = osts->op_count;
1252
1253 repeat_find:
1254         /* search loi_ost_idx in ost array */
1255         array_idx = 0;
1256         for (i = 0; i < ost_count; i++) {
1257                 if (osts->op_array[i] == lod_comp->llc_stripe_offset) {
1258                         array_idx = i;
1259                         break;
1260                 }
1261         }
1262         if (i == ost_count) {
1263                 CERROR("Start index %d not found in pool '%s'\n",
1264                        lod_comp->llc_stripe_offset,
1265                        lod_comp->llc_pool ? lod_comp->llc_pool : "");
1266                 GOTO(out, rc = -EINVAL);
1267         }
1268
1269         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1270                 stripes_per_ost =
1271                         (lod_comp->llc_stripe_count - 1)/ost_count + 1;
1272
1273         for (i = 0; i < ost_count * stripes_per_ost;
1274                         i++, array_idx = (array_idx + 1) % ost_count) {
1275                 ost_idx = osts->op_array[array_idx];
1276
1277                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
1278                         continue;
1279
1280                 /* Fail Check before osc_precreate() is called
1281                    so we can only 'fail' single OSC. */
1282                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1283                         continue;
1284
1285                 /*
1286                  * do not put >1 objects on a single OST, except for
1287                  * overstriping, where it is intended
1288                  */
1289                 if (lod_qos_is_ost_used(env, ost_idx, stripe_num)) {
1290                         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1291                                 overstriped = true;
1292                         else
1293                                 continue;
1294                 }
1295
1296                 /*
1297                  * try not allocate on the OST used by other component
1298                  */
1299                 if (speed == 0 && i != 0 &&
1300                     lod_comp_is_ost_used(env, lo, ost_idx))
1301                         continue;
1302
1303                 /* Drop slow OSCs if we can, but not for requested start idx.
1304                  *
1305                  * This means "if OSC is slow and it is not the requested
1306                  * start OST, then it can be skipped, otherwise skip it only
1307                  * if it is inactive/recovering/out-of-space." */
1308
1309                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
1310                 if (rc) {
1311                         /* this OSP doesn't feel well */
1312                         continue;
1313                 }
1314
1315                 /*
1316                  * We expect number of precreated objects at the first
1317                  * iteration.  Skip OSPs with no objects ready.  Don't apply
1318                  * this logic to OST specified with stripe_offset.
1319                  */
1320                 if (i != 0 && sfs->os_fprecreated == 0 && speed == 0)
1321                         continue;
1322
1323                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1324                 if (IS_ERR(o)) {
1325                         CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
1326                                ost_idx, (int) PTR_ERR(o));
1327                         continue;
1328                 }
1329
1330                 /*
1331                  * We've successfully declared (reserved) an object
1332                  */
1333                 lod_qos_ost_in_use(env, stripe_num, ost_idx);
1334                 stripe[stripe_num] = o;
1335                 ost_indices[stripe_num] = ost_idx;
1336                 stripe_num++;
1337
1338                 /* We have enough stripes */
1339                 if (stripe_num == lod_comp->llc_stripe_count)
1340                         GOTO(out, rc = 0);
1341         }
1342         if (speed < 2) {
1343                 /* Try again, allowing slower OSCs */
1344                 speed++;
1345                 goto repeat_find;
1346         }
1347
1348         /* If we were passed specific striping params, then a failure to
1349          * meet those requirements is an error, since we can't reallocate
1350          * that memory (it might be part of a larger array or something).
1351          */
1352         CERROR("can't lstripe objid "DFID": have %d want %u\n",
1353                PFID(lu_object_fid(lod2lu_obj(lo))), stripe_num,
1354                lod_comp->llc_stripe_count);
1355         rc = stripe_num == 0 ? -ENOSPC : -EFBIG;
1356
1357         /* If there are enough OSTs, a component with overstriping requessted
1358          * will not actually end up overstriped.  The comp should reflect this.
1359          */
1360         if (rc == 0 && !overstriped)
1361                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1362
1363 out:
1364         if (pool != NULL) {
1365                 up_read(&pool_tgt_rw_sem(pool));
1366                 /* put back ref got by lod_find_pool() */
1367                 lod_pool_putref(pool);
1368         }
1369
1370         RETURN(rc);
1371 }
1372
1373 /**
1374  * Check whether QoS allocation should be used.
1375  *
1376  * A simple helper to decide when QoS allocation should be used:
1377  * if it's just a single available target or the used space is
1378  * evenly distributed among the targets at the moment, then QoS
1379  * allocation algorithm should not be used.
1380  *
1381  * \param[in] lod       LOD device
1382  *
1383  * \retval 0            should not be used
1384  * \retval 1            should be used
1385  */
1386 static inline int lod_qos_is_usable(struct lod_device *lod)
1387 {
1388 #ifdef FORCE_QOS
1389         /* to be able to debug QoS code */
1390         return 1;
1391 #endif
1392
1393         /* Detect -EAGAIN early, before expensive lock is taken. */
1394         if (!lod->lod_qos.lq_dirty && lod->lod_qos.lq_same_space)
1395                 return 0;
1396
1397         if (lod->lod_desc.ld_active_tgt_count < 2)
1398                 return 0;
1399
1400         return 1;
1401 }
1402
1403 /**
1404  * Allocate a striping using an algorithm with weights.
1405  *
1406  * The function allocates OST objects to create a striping. The algorithm
1407  * used is based on weights (currently only using the free space), and it's
1408  * trying to ensure the space is used evenly by OSTs and OSSs. The striping
1409  * configuration (# of stripes, offset, pool) is taken from the object and
1410  * is prepared by the caller.
1411  *
1412  * If LOV_USES_DEFAULT_STRIPE is not passed and prepared configuration can't
1413  * be met due to too few OSTs, then allocation fails. If the flag is passed
1414  * fewer than 3/4 of the requested number of stripes can be allocated, then
1415  * allocation fails.
1416  *
1417  * No concurrent allocation is allowed on the object and this must be ensured
1418  * by the caller. All the internal structures are protected by the function.
1419  *
1420  * The algorithm has two steps: find available OSTs and calculate their
1421  * weights, then select the OSTs with their weights used as the probability.
1422  * An OST with a higher weight is proportionately more likely to be selected
1423  * than one with a lower weight.
1424  *
1425  * \param[in] env               execution environment for this thread
1426  * \param[in] lo                LOD object
1427  * \param[out] stripe           striping created
1428  * \param[out] ost_indices      ost indices of striping created
1429  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
1430  * \param[in] th                transaction handle
1431  * \param[in] comp_idx          index of ldo_comp_entries
1432  *
1433  * \retval 0            on success
1434  * \retval -EAGAIN      not enough OSTs are found for specified stripe count
1435  * \retval -EINVAL      requested OST index is invalid
1436  * \retval negative     errno on failure
1437  */
1438 static int lod_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1439                          struct dt_object **stripe, __u32 *ost_indices,
1440                          int flags, struct thandle *th, int comp_idx)
1441 {
1442         struct lod_layout_component *lod_comp;
1443         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1444         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
1445         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
1446         struct lod_tgt_desc *ost;
1447         struct dt_object *o;
1448         __u64 total_weight = 0;
1449         struct pool_desc *pool = NULL;
1450         struct ost_pool *osts;
1451         unsigned int i;
1452         __u32 nfound, good_osts, stripe_count, stripe_count_min;
1453         bool overstriped = false;
1454         int stripes_per_ost = 1;
1455         int rc = 0;
1456         ENTRY;
1457
1458         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1459         lod_comp = &lo->ldo_comp_entries[comp_idx];
1460         stripe_count = lod_comp->llc_stripe_count;
1461         stripe_count_min = min_stripe_count(stripe_count, flags);
1462         if (stripe_count_min < 1)
1463                 RETURN(-EINVAL);
1464
1465         if (lod_comp->llc_pool != NULL)
1466                 pool = lod_find_pool(lod, lod_comp->llc_pool);
1467
1468         if (pool != NULL) {
1469                 down_read(&pool_tgt_rw_sem(pool));
1470                 osts = &(pool->pool_obds);
1471         } else {
1472                 osts = &(lod->lod_pool_info);
1473         }
1474
1475         /* Detect -EAGAIN early, before expensive lock is taken. */
1476         if (!lod_qos_is_usable(lod))
1477                 GOTO(out_nolock, rc = -EAGAIN);
1478
1479         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1480                 stripes_per_ost =
1481                         (lod_comp->llc_stripe_count - 1)/osts->op_count + 1;
1482
1483         /* Do actual allocation, use write lock here. */
1484         down_write(&lod->lod_qos.lq_rw_sem);
1485
1486         /*
1487          * Check again, while we were sleeping on @lq_rw_sem things could
1488          * change.
1489          */
1490         if (!lod_qos_is_usable(lod))
1491                 GOTO(out, rc = -EAGAIN);
1492
1493         rc = lod_qos_calc_ppo(lod);
1494         if (rc)
1495                 GOTO(out, rc);
1496
1497         rc = lod_qos_ost_in_use_clear(env, lod_comp->llc_stripe_count);
1498         if (rc)
1499                 GOTO(out, rc);
1500
1501         good_osts = 0;
1502         /* Find all the OSTs that are valid stripe candidates */
1503         for (i = 0; i < osts->op_count; i++) {
1504                 if (!cfs_bitmap_check(lod->lod_ost_bitmap, osts->op_array[i]))
1505                         continue;
1506
1507                 ost = OST_TGT(lod, osts->op_array[i]);
1508                 ost->ltd_qos.ltq_usable = 0;
1509
1510                 rc = lod_statfs_and_check(env, lod, osts->op_array[i], sfs);
1511                 if (rc) {
1512                         /* this OSP doesn't feel well */
1513                         continue;
1514                 }
1515
1516                 if (sfs->os_state & OS_STATE_DEGRADED)
1517                         continue;
1518
1519                 /* Fail Check before osc_precreate() is called
1520                    so we can only 'fail' single OSC. */
1521                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) &&
1522                                    osts->op_array[i] == 0)
1523                         continue;
1524
1525                 ost->ltd_qos.ltq_usable = 1;
1526                 lod_qos_calc_weight(lod, osts->op_array[i]);
1527                 total_weight += ost->ltd_qos.ltq_weight;
1528
1529                 good_osts++;
1530         }
1531
1532         QOS_DEBUG("found %d good osts\n", good_osts);
1533
1534         if (good_osts < stripe_count_min)
1535                 GOTO(out, rc = -EAGAIN);
1536
1537         /* If we do not have enough OSTs for the requested stripe count, do not
1538          * put more stripes per OST than requested.
1539          */
1540         if (stripe_count / stripes_per_ost > good_osts)
1541                 stripe_count = good_osts * stripes_per_ost;
1542
1543         /* Find enough OSTs with weighted random allocation. */
1544         nfound = 0;
1545         while (nfound < stripe_count) {
1546                 u64 rand, cur_weight;
1547
1548                 cur_weight = 0;
1549                 rc = -ENOSPC;
1550
1551                 if (total_weight) {
1552 #if BITS_PER_LONG == 32
1553                         rand = prandom_u32_max((u32)total_weight);
1554                         /* If total_weight > 32-bit, first generate the high
1555                          * 32 bits of the random number, then add in the low
1556                          * 32 bits (truncated to the upper limit, if needed)
1557                          */
1558                         if (total_weight > 0xffffffffULL)
1559                                 rand = prandom_u32_max((u32)(total_weight >> 32)) << 32;
1560                         else
1561                                 rand = 0;
1562
1563                         if (rand == (total_weight & 0xffffffff00000000ULL))
1564                                 rand |= prandom_u32_max((u32)total_weight);
1565                         else
1566                                 rand |= prandom_u32();
1567
1568 #else
1569                         rand = prandom_u32() | prandom_u32_max((u32)total_weight);
1570 #endif
1571                 } else {
1572                         rand = 0;
1573                 }
1574
1575                 /* On average, this will hit larger-weighted OSTs more often.
1576                  * 0-weight OSTs will always get used last (only when rand=0) */
1577                 for (i = 0; i < osts->op_count; i++) {
1578                         __u32 idx = osts->op_array[i];
1579
1580                         if (lod_should_avoid_ost(lo, lag, idx))
1581                                 continue;
1582
1583                         ost = OST_TGT(lod, idx);
1584
1585                         if (!ost->ltd_qos.ltq_usable)
1586                                 continue;
1587
1588                         cur_weight += ost->ltd_qos.ltq_weight;
1589                         QOS_DEBUG("stripe_count=%d nfound=%d cur_weight=%llu "
1590                                   "rand=%llu total_weight=%llu\n",
1591                                   stripe_count, nfound, cur_weight, rand,
1592                                   total_weight);
1593
1594                         if (cur_weight < rand)
1595                                 continue;
1596
1597                         QOS_DEBUG("stripe=%d to idx=%d\n", nfound, idx);
1598                         /*
1599                          * do not put >1 objects on a single OST, except for
1600                          * overstriping
1601                          */
1602                         if ((lod_comp_is_ost_used(env, lo, idx)) &&
1603                             !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING))
1604                                 continue;
1605
1606                         if (lod_qos_is_ost_used(env, idx, nfound)) {
1607                                 if (lod_comp->llc_pattern &
1608                                     LOV_PATTERN_OVERSTRIPING)
1609                                         overstriped = true;
1610                                 else
1611                                         continue;
1612                         }
1613
1614                         o = lod_qos_declare_object_on(env, lod, idx, th);
1615                         if (IS_ERR(o)) {
1616                                 QOS_DEBUG("can't declare object on #%u: %d\n",
1617                                           idx, (int) PTR_ERR(o));
1618                                 continue;
1619                         }
1620
1621                         lod_avoid_update(lo, lag);
1622                         lod_qos_ost_in_use(env, nfound, idx);
1623                         stripe[nfound] = o;
1624                         ost_indices[nfound] = idx;
1625                         lod_qos_used(lod, osts, idx, &total_weight);
1626                         nfound++;
1627                         rc = 0;
1628                         break;
1629                 }
1630
1631                 if (rc) {
1632                         /* no OST found on this iteration, give up */
1633                         break;
1634                 }
1635         }
1636
1637         if (unlikely(nfound != stripe_count)) {
1638                 /*
1639                  * when the decision to use weighted algorithm was made
1640                  * we had enough appropriate OSPs, but this state can
1641                  * change anytime (no space on OST, broken connection, etc)
1642                  * so it's possible OSP won't be able to provide us with
1643                  * an object due to just changed state
1644                  */
1645                 QOS_DEBUG("%s: wanted %d objects, found only %d\n",
1646                           lod2obd(lod)->obd_name, stripe_count, nfound);
1647                 for (i = 0; i < nfound; i++) {
1648                         LASSERT(stripe[i] != NULL);
1649                         dt_object_put(env, stripe[i]);
1650                         stripe[i] = NULL;
1651                 }
1652
1653                 /* makes sense to rebalance next time */
1654                 lod->lod_qos.lq_dirty = 1;
1655                 lod->lod_qos.lq_same_space = 0;
1656
1657                 rc = -EAGAIN;
1658         }
1659
1660         /* If there are enough OSTs, a component with overstriping requessted
1661          * will not actually end up overstriped.  The comp should reflect this.
1662          */
1663         if (rc == 0 && !overstriped)
1664                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1665
1666 out:
1667         up_write(&lod->lod_qos.lq_rw_sem);
1668
1669 out_nolock:
1670         if (pool != NULL) {
1671                 up_read(&pool_tgt_rw_sem(pool));
1672                 /* put back ref got by lod_find_pool() */
1673                 lod_pool_putref(pool);
1674         }
1675
1676         RETURN(rc);
1677 }
1678
1679 /**
1680  * Check stripe count the caller can use.
1681  *
1682  * For new layouts (no initialized components), check the total size of the
1683  * layout against the maximum EA size from the backing file system.  This
1684  * stops us from creating a layout which will be too large once initialized.
1685  *
1686  * For existing layouts (with initialized components):
1687  * Find the maximal possible stripe count not greater than \a stripe_count.
1688  * If the provided stripe count is 0, then the filesystem's default is used.
1689  *
1690  * \param[in] lod       LOD device
1691  * \param[in] lo        The lod_object
1692  * \param[in] stripe_count      count the caller would like to use
1693  *
1694  * \retval              the maximum usable stripe count
1695  */
1696 __u16 lod_get_stripe_count(struct lod_device *lod, struct lod_object *lo,
1697                            __u16 stripe_count, bool overstriping)
1698 {
1699         __u32 max_stripes = LOV_MAX_STRIPE_COUNT_OLD;
1700         /* max stripe count is based on OSD ea size */
1701         unsigned int easize = lod->lod_osd_max_easize;
1702         int i;
1703
1704
1705         if (!stripe_count)
1706                 stripe_count = lod->lod_desc.ld_default_stripe_count;
1707         if (!stripe_count)
1708                 stripe_count = 1;
1709         /* Overstriping allows more stripes than targets */
1710         if (stripe_count > lod->lod_desc.ld_active_tgt_count && !overstriping)
1711                 stripe_count = lod->lod_desc.ld_active_tgt_count;
1712
1713         if (lo->ldo_is_composite) {
1714                 struct lod_layout_component *lod_comp;
1715                 unsigned int header_sz = sizeof(struct lov_comp_md_v1);
1716                 unsigned int init_comp_sz = 0;
1717                 unsigned int total_comp_sz = 0;
1718                 unsigned int comp_sz;
1719
1720                 header_sz += sizeof(struct lov_comp_md_entry_v1) *
1721                                 lo->ldo_comp_cnt;
1722
1723                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
1724                         lod_comp = &lo->ldo_comp_entries[i];
1725                         comp_sz = lov_mds_md_size(lod_comp->llc_stripe_count,
1726                                                   LOV_MAGIC_V3);
1727                         total_comp_sz += comp_sz;
1728                         if (lod_comp->llc_flags & LCME_FL_INIT)
1729                                 init_comp_sz += comp_sz;
1730                 }
1731
1732                 if (init_comp_sz > 0)
1733                         total_comp_sz = init_comp_sz;
1734
1735                 header_sz += total_comp_sz;
1736
1737                 if (easize > header_sz)
1738                         easize -= header_sz;
1739                 else
1740                         easize = 0;
1741         }
1742
1743         max_stripes = lov_mds_md_max_stripe_count(easize, LOV_MAGIC_V3);
1744
1745         return (stripe_count < max_stripes) ? stripe_count : max_stripes;
1746 }
1747
1748 /**
1749  * Create in-core respresentation for a fully-defined striping
1750  *
1751  * When the caller passes a fully-defined striping (i.e. everything including
1752  * OST object FIDs are defined), then we still need to instantiate LU-cache
1753  * with the objects representing the stripes defined. This function completes
1754  * that task.
1755  *
1756  * \param[in] env       execution environment for this thread
1757  * \param[in] mo        LOD object
1758  * \param[in] buf       buffer containing the striping
1759  *
1760  * \retval 0            on success
1761  * \retval negative     negated errno on error
1762  */
1763 int lod_use_defined_striping(const struct lu_env *env,
1764                              struct lod_object *mo,
1765                              const struct lu_buf *buf)
1766 {
1767         struct lod_layout_component *lod_comp;
1768         struct lov_mds_md_v1   *v1 = buf->lb_buf;
1769         struct lov_mds_md_v3   *v3 = buf->lb_buf;
1770         struct lov_comp_md_v1  *comp_v1 = NULL;
1771         struct lov_ost_data_v1 *objs;
1772         __u32   magic;
1773         __u16   comp_cnt;
1774         __u16   mirror_cnt;
1775         int     rc = 0, i;
1776         ENTRY;
1777
1778         mutex_lock(&mo->ldo_layout_mutex);
1779         lod_striping_free_nolock(env, mo);
1780
1781         magic = le32_to_cpu(v1->lmm_magic) & ~LOV_MAGIC_DEFINED;
1782
1783         if (magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3 &&
1784             magic != LOV_MAGIC_COMP_V1 && magic != LOV_MAGIC_FOREIGN)
1785                 GOTO(unlock, rc = -EINVAL);
1786
1787         if (magic == LOV_MAGIC_COMP_V1) {
1788                 comp_v1 = buf->lb_buf;
1789                 comp_cnt = le16_to_cpu(comp_v1->lcm_entry_count);
1790                 if (comp_cnt == 0)
1791                         GOTO(unlock, rc = -EINVAL);
1792                 mirror_cnt = le16_to_cpu(comp_v1->lcm_mirror_count) + 1;
1793                 mo->ldo_flr_state = le16_to_cpu(comp_v1->lcm_flags) &
1794                                         LCM_FL_FLR_MASK;
1795                 mo->ldo_is_composite = 1;
1796         } else if (magic == LOV_MAGIC_FOREIGN) {
1797                 struct lov_foreign_md *foreign;
1798                 size_t length;
1799
1800                 if (buf->lb_len < offsetof(typeof(*foreign), lfm_value)) {
1801                         CDEBUG(D_LAYOUT,
1802                                "buf len %zu < min lov_foreign_md size (%zu)\n",
1803                                buf->lb_len,
1804                                offsetof(typeof(*foreign), lfm_value));
1805                         GOTO(out, rc = -EINVAL);
1806                 }
1807                 foreign = (struct lov_foreign_md *)buf->lb_buf;
1808                 length = foreign_size_le(foreign);
1809                 if (buf->lb_len < length) {
1810                         CDEBUG(D_LAYOUT,
1811                                "buf len %zu < this lov_foreign_md size (%zu)\n",
1812                                buf->lb_len, length);
1813                         GOTO(out, rc = -EINVAL);
1814                 }
1815
1816                 /* just cache foreign LOV EA raw */
1817                 rc = lod_alloc_foreign_lov(mo, length);
1818                 if (rc)
1819                         GOTO(out, rc);
1820                 memcpy(mo->ldo_foreign_lov, buf->lb_buf, length);
1821                 GOTO(out, rc);
1822         } else {
1823                 mo->ldo_is_composite = 0;
1824                 comp_cnt = 1;
1825                 mirror_cnt = 0;
1826         }
1827         mo->ldo_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
1828
1829         rc = lod_alloc_comp_entries(mo, mirror_cnt, comp_cnt);
1830         if (rc)
1831                 GOTO(unlock, rc);
1832
1833         for (i = 0; i < comp_cnt; i++) {
1834                 struct lu_extent *ext;
1835                 char    *pool_name;
1836                 __u32   offs;
1837
1838                 lod_comp = &mo->ldo_comp_entries[i];
1839
1840                 if (mo->ldo_is_composite) {
1841                         offs = le32_to_cpu(comp_v1->lcm_entries[i].lcme_offset);
1842                         v1 = (struct lov_mds_md_v1 *)((char *)comp_v1 + offs);
1843                         v3 = (struct lov_mds_md_v3 *)v1;
1844                         magic = le32_to_cpu(v1->lmm_magic);
1845
1846                         ext = &comp_v1->lcm_entries[i].lcme_extent;
1847                         lod_comp->llc_extent.e_start =
1848                                 le64_to_cpu(ext->e_start);
1849                         lod_comp->llc_extent.e_end = le64_to_cpu(ext->e_end);
1850                         lod_comp->llc_flags =
1851                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_flags);
1852                         if (lod_comp->llc_flags & LCME_FL_NOSYNC)
1853                                 lod_comp->llc_timestamp = le64_to_cpu(
1854                                         comp_v1->lcm_entries[i].lcme_timestamp);
1855                         lod_comp->llc_id =
1856                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_id);
1857                         if (lod_comp->llc_id == LCME_ID_INVAL)
1858                                 GOTO(out, rc = -EINVAL);
1859                 }
1860
1861                 pool_name = NULL;
1862                 if (magic == LOV_MAGIC_V1) {
1863                         objs = &v1->lmm_objects[0];
1864                 } else if (magic == LOV_MAGIC_V3) {
1865                         objs = &v3->lmm_objects[0];
1866                         if (v3->lmm_pool_name[0] != '\0')
1867                                 pool_name = v3->lmm_pool_name;
1868                 } else {
1869                         CDEBUG(D_LAYOUT, "Invalid magic %x\n", magic);
1870                         GOTO(out, rc = -EINVAL);
1871                 }
1872
1873                 lod_comp->llc_pattern = le32_to_cpu(v1->lmm_pattern);
1874                 lod_comp->llc_stripe_size = le32_to_cpu(v1->lmm_stripe_size);
1875                 lod_comp->llc_stripe_count = le16_to_cpu(v1->lmm_stripe_count);
1876                 lod_comp->llc_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
1877                 /**
1878                  * The stripe_offset of an uninit-ed component is stored in
1879                  * the lmm_layout_gen
1880                  */
1881                 if (mo->ldo_is_composite && !lod_comp_inited(lod_comp))
1882                         lod_comp->llc_stripe_offset = lod_comp->llc_layout_gen;
1883                 lod_obj_set_pool(mo, i, pool_name);
1884
1885                 if ((!mo->ldo_is_composite || lod_comp_inited(lod_comp)) &&
1886                     !(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
1887                     !(lod_comp->llc_pattern & LOV_PATTERN_MDT)) {
1888                         rc = lod_initialize_objects(env, mo, objs, i);
1889                         if (rc)
1890                                 GOTO(out, rc);
1891                 }
1892         }
1893
1894         rc = lod_fill_mirrors(mo);
1895         GOTO(out, rc);
1896 out:
1897         if (rc)
1898                 lod_striping_free_nolock(env, mo);
1899 unlock:
1900         mutex_unlock(&mo->ldo_layout_mutex);
1901
1902         RETURN(rc);
1903 }
1904
1905 /**
1906  * Parse suggested striping configuration.
1907  *
1908  * The caller gets a suggested striping configuration from a number of sources
1909  * including per-directory default and applications. Then it needs to verify
1910  * the suggested striping is valid, apply missing bits and store the resulting
1911  * configuration in the object to be used by the allocator later. Must not be
1912  * called concurrently against the same object. It's OK to provide a
1913  * fully-defined striping.
1914  *
1915  * \param[in] env       execution environment for this thread
1916  * \param[in] lo        LOD object
1917  * \param[in] buf       buffer containing the striping
1918  *
1919  * \retval 0            on success
1920  * \retval negative     negated errno on error
1921  */
1922 int lod_qos_parse_config(const struct lu_env *env, struct lod_object *lo,
1923                          const struct lu_buf *buf)
1924 {
1925         struct lod_layout_component *lod_comp;
1926         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
1927         struct lov_desc *desc = &d->lod_desc;
1928         struct lov_user_md_v1 *v1 = NULL;
1929         struct lov_user_md_v3 *v3 = NULL;
1930         struct lov_comp_md_v1 *comp_v1 = NULL;
1931         struct lov_foreign_md *lfm = NULL;
1932         char def_pool[LOV_MAXPOOLNAME + 1];
1933         __u32 magic;
1934         __u16 comp_cnt;
1935         __u16 mirror_cnt;
1936         int i, rc;
1937         ENTRY;
1938
1939         if (buf == NULL || buf->lb_buf == NULL || buf->lb_len == 0)
1940                 RETURN(0);
1941
1942         memset(def_pool, 0, sizeof(def_pool));
1943         if (lo->ldo_comp_entries != NULL)
1944                 lod_layout_get_pool(lo->ldo_comp_entries, lo->ldo_comp_cnt,
1945                                     def_pool, sizeof(def_pool));
1946
1947         /* free default striping info */
1948         if (lo->ldo_is_foreign)
1949                 lod_free_foreign_lov(lo);
1950         else
1951                 lod_free_comp_entries(lo);
1952
1953         rc = lod_verify_striping(d, lo, buf, false);
1954         if (rc)
1955                 RETURN(-EINVAL);
1956
1957         v3 = buf->lb_buf;
1958         v1 = buf->lb_buf;
1959         comp_v1 = buf->lb_buf;
1960         /* {lmm,lfm}_magic position/length work for all LOV formats */
1961         magic = v1->lmm_magic;
1962
1963         if (unlikely(le32_to_cpu(magic) & LOV_MAGIC_DEFINED)) {
1964                 /* try to use as fully defined striping */
1965                 rc = lod_use_defined_striping(env, lo, buf);
1966                 RETURN(rc);
1967         }
1968
1969         switch (magic) {
1970         case __swab32(LOV_USER_MAGIC_V1):
1971                 lustre_swab_lov_user_md_v1(v1);
1972                 magic = v1->lmm_magic;
1973                 /* fall through */
1974         case LOV_USER_MAGIC_V1:
1975                 break;
1976         case __swab32(LOV_USER_MAGIC_V3):
1977                 lustre_swab_lov_user_md_v3(v3);
1978                 magic = v3->lmm_magic;
1979                 /* fall through */
1980         case LOV_USER_MAGIC_V3:
1981                 break;
1982         case __swab32(LOV_USER_MAGIC_SPECIFIC):
1983                 lustre_swab_lov_user_md_v3(v3);
1984                 lustre_swab_lov_user_md_objects(v3->lmm_objects,
1985                                                 v3->lmm_stripe_count);
1986                 magic = v3->lmm_magic;
1987                 /* fall through */
1988         case LOV_USER_MAGIC_SPECIFIC:
1989                 break;
1990         case __swab32(LOV_USER_MAGIC_COMP_V1):
1991                 lustre_swab_lov_comp_md_v1(comp_v1);
1992                 magic = comp_v1->lcm_magic;
1993                 /* fall trhough */
1994         case LOV_USER_MAGIC_COMP_V1:
1995                 break;
1996         case __swab32(LOV_USER_MAGIC_FOREIGN):
1997                 lfm = buf->lb_buf;
1998                 __swab32s(&lfm->lfm_magic);
1999                 __swab32s(&lfm->lfm_length);
2000                 __swab32s(&lfm->lfm_type);
2001                 __swab32s(&lfm->lfm_flags);
2002                 magic = lfm->lfm_magic;
2003                 /* fall through */
2004         case LOV_USER_MAGIC_FOREIGN:
2005                 if (!lfm)
2006                         lfm = buf->lb_buf;
2007                 rc = lod_alloc_foreign_lov(lo, foreign_size(lfm));
2008                 if (rc)
2009                         RETURN(rc);
2010                 memcpy(lo->ldo_foreign_lov, buf->lb_buf, foreign_size(lfm));
2011                 RETURN(0);
2012         default:
2013                 CERROR("%s: unrecognized magic %X\n",
2014                        lod2obd(d)->obd_name, magic);
2015                 RETURN(-EINVAL);
2016         }
2017
2018         lustre_print_user_md(D_OTHER, v1, "parse config");
2019
2020         if (magic == LOV_USER_MAGIC_COMP_V1) {
2021                 comp_cnt = comp_v1->lcm_entry_count;
2022                 if (comp_cnt == 0)
2023                         RETURN(-EINVAL);
2024                 mirror_cnt =  comp_v1->lcm_mirror_count + 1;
2025                 if (mirror_cnt > 1)
2026                         lo->ldo_flr_state = LCM_FL_RDONLY;
2027                 lo->ldo_is_composite = 1;
2028         } else {
2029                 comp_cnt = 1;
2030                 mirror_cnt = 0;
2031                 lo->ldo_is_composite = 0;
2032         }
2033
2034         rc = lod_alloc_comp_entries(lo, mirror_cnt, comp_cnt);
2035         if (rc)
2036                 RETURN(rc);
2037
2038         LASSERT(lo->ldo_comp_entries);
2039
2040         for (i = 0; i < comp_cnt; i++) {
2041                 struct pool_desc        *pool;
2042                 struct lu_extent        *ext;
2043                 char    *pool_name;
2044
2045                 lod_comp = &lo->ldo_comp_entries[i];
2046
2047                 if (lo->ldo_is_composite) {
2048                         v1 = (struct lov_user_md *)((char *)comp_v1 +
2049                                         comp_v1->lcm_entries[i].lcme_offset);
2050                         ext = &comp_v1->lcm_entries[i].lcme_extent;
2051                         lod_comp->llc_extent = *ext;
2052                         lod_comp->llc_flags =
2053                                 comp_v1->lcm_entries[i].lcme_flags &
2054                                         LCME_USER_FLAGS;
2055                 }
2056
2057                 pool_name = NULL;
2058                 if (v1->lmm_magic == LOV_USER_MAGIC_V3 ||
2059                     v1->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2060                         v3 = (struct lov_user_md_v3 *)v1;
2061                         if (v3->lmm_pool_name[0] != '\0')
2062                                 pool_name = v3->lmm_pool_name;
2063
2064                         if (v3->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2065                                 rc = lod_comp_copy_ost_lists(lod_comp, v3);
2066                                 if (rc)
2067                                         GOTO(free_comp, rc);
2068                         }
2069                 }
2070
2071                 if (pool_name == NULL && def_pool[0] != '\0')
2072                         pool_name = def_pool;
2073
2074                 if (v1->lmm_pattern == 0)
2075                         v1->lmm_pattern = LOV_PATTERN_RAID0;
2076                 if (lov_pattern(v1->lmm_pattern) != LOV_PATTERN_RAID0 &&
2077                     lov_pattern(v1->lmm_pattern) != LOV_PATTERN_MDT &&
2078                     lov_pattern(v1->lmm_pattern) !=
2079                         (LOV_PATTERN_RAID0 | LOV_PATTERN_OVERSTRIPING)) {
2080                         CDEBUG(D_LAYOUT, "%s: invalid pattern: %x\n",
2081                                lod2obd(d)->obd_name, v1->lmm_pattern);
2082                         GOTO(free_comp, rc = -EINVAL);
2083                 }
2084
2085                 lod_comp->llc_pattern = v1->lmm_pattern;
2086                 lod_comp->llc_stripe_size = desc->ld_default_stripe_size;
2087                 if (v1->lmm_stripe_size)
2088                         lod_comp->llc_stripe_size = v1->lmm_stripe_size;
2089
2090                 lod_comp->llc_stripe_count = desc->ld_default_stripe_count;
2091                 if (v1->lmm_stripe_count ||
2092                     lov_pattern(v1->lmm_pattern) == LOV_PATTERN_MDT)
2093                         lod_comp->llc_stripe_count = v1->lmm_stripe_count;
2094
2095                 lod_comp->llc_stripe_offset = v1->lmm_stripe_offset;
2096                 lod_obj_set_pool(lo, i, pool_name);
2097
2098                 LASSERT(ergo(lov_pattern(lod_comp->llc_pattern) ==
2099                              LOV_PATTERN_MDT, lod_comp->llc_stripe_count == 0));
2100
2101                 if (pool_name == NULL)
2102                         continue;
2103
2104                 /* In the function below, .hs_keycmp resolves to
2105                  * pool_hashkey_keycmp() */
2106                 /* coverity[overrun-buffer-val] */
2107                 pool = lod_find_pool(d, pool_name);
2108                 if (pool == NULL)
2109                         continue;
2110
2111                 if (lod_comp->llc_stripe_offset != LOV_OFFSET_DEFAULT) {
2112                         rc = lod_check_index_in_pool(
2113                                         lod_comp->llc_stripe_offset, pool);
2114                         if (rc < 0) {
2115                                 lod_pool_putref(pool);
2116                                 CDEBUG(D_LAYOUT, "%s: invalid offset, %u\n",
2117                                        lod2obd(d)->obd_name,
2118                                        lod_comp->llc_stripe_offset);
2119                                 GOTO(free_comp, rc = -EINVAL);
2120                         }
2121                 }
2122
2123                 if (lod_comp->llc_stripe_count > pool_tgt_count(pool) &&
2124                     !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING))
2125                         lod_comp->llc_stripe_count = pool_tgt_count(pool);
2126
2127                 lod_pool_putref(pool);
2128         }
2129
2130         RETURN(0);
2131
2132 free_comp:
2133         lod_free_comp_entries(lo);
2134         RETURN(rc);
2135 }
2136
2137 /**
2138  * prepare enough OST avoidance bitmap space
2139  */
2140 int lod_prepare_avoidance(const struct lu_env *env, struct lod_object *lo)
2141 {
2142         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2143         struct lod_tgt_descs *ltds = &lod->lod_ost_descs;
2144         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
2145         struct cfs_bitmap *bitmap = NULL;
2146         __u32 *new_oss = NULL;
2147
2148         lag->lag_ost_avail = ltds->ltd_tgtnr;
2149
2150         /* reset OSS avoid guide array */
2151         lag->lag_oaa_count = 0;
2152         if (lag->lag_oss_avoid_array && lag->lag_oaa_size < ltds->ltd_tgtnr) {
2153                 OBD_FREE(lag->lag_oss_avoid_array,
2154                          sizeof(__u32) * lag->lag_oaa_size);
2155                 lag->lag_oss_avoid_array = NULL;
2156                 lag->lag_oaa_size = 0;
2157         }
2158
2159         /* init OST avoid guide bitmap */
2160         if (lag->lag_ost_avoid_bitmap) {
2161                 if (ltds->ltd_tgtnr <= lag->lag_ost_avoid_bitmap->size) {
2162                         CFS_RESET_BITMAP(lag->lag_ost_avoid_bitmap);
2163                 } else {
2164                         CFS_FREE_BITMAP(lag->lag_ost_avoid_bitmap);
2165                         lag->lag_ost_avoid_bitmap = NULL;
2166                 }
2167         }
2168
2169         if (!lag->lag_ost_avoid_bitmap) {
2170                 bitmap = CFS_ALLOCATE_BITMAP(ltds->ltd_tgtnr);
2171                 if (!bitmap)
2172                         return -ENOMEM;
2173         }
2174
2175         if (!lag->lag_oss_avoid_array) {
2176                 /**
2177                  * usually there are multiple OSTs in one OSS, but we don't
2178                  * know the exact OSS number, so we choose a safe option,
2179                  * using OST count to allocate the array to store the OSS
2180                  * id.
2181                  */
2182                 OBD_ALLOC(new_oss, sizeof(*new_oss) * ltds->ltd_tgtnr);
2183                 if (!new_oss) {
2184                         CFS_FREE_BITMAP(bitmap);
2185                         return -ENOMEM;
2186                 }
2187         }
2188
2189         if (new_oss) {
2190                 lag->lag_oss_avoid_array = new_oss;
2191                 lag->lag_oaa_size = ltds->ltd_tgtnr;
2192         }
2193         if (bitmap)
2194                 lag->lag_ost_avoid_bitmap = bitmap;
2195
2196         return 0;
2197 }
2198
2199 /**
2200  * Collect information of used OSTs and OSSs in the overlapped components
2201  * of other mirrors
2202  */
2203 void lod_collect_avoidance(struct lod_object *lo, struct lod_avoid_guide *lag,
2204                            int comp_idx)
2205 {
2206         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2207         struct lod_layout_component *lod_comp = &lo->ldo_comp_entries[comp_idx];
2208         struct cfs_bitmap *bitmap = lag->lag_ost_avoid_bitmap;
2209         int i, j;
2210
2211         /* iterate mirrors */
2212         for (i = 0; i < lo->ldo_mirror_count; i++) {
2213                 struct lod_layout_component *comp;
2214
2215                 /**
2216                  * skip mirror containing component[comp_idx], we only
2217                  * collect OSTs info of conflicting component in other mirrors,
2218                  * so that during read, if OSTs of a mirror's component are
2219                  * not available, we still have other mirror with different
2220                  * OSTs to read the data.
2221                  */
2222                 comp = &lo->ldo_comp_entries[lo->ldo_mirrors[i].lme_start];
2223                 if (comp->llc_id != LCME_ID_INVAL &&
2224                     mirror_id_of(comp->llc_id) ==
2225                                                 mirror_id_of(lod_comp->llc_id))
2226                         continue;
2227
2228                 /* iterate components of a mirror */
2229                 lod_foreach_mirror_comp(comp, lo, i) {
2230                         /**
2231                          * skip non-overlapped or un-instantiated components,
2232                          * NOTE: don't use lod_comp_inited(comp) to judge
2233                          * whether @comp has been inited, since during
2234                          * declare phase, comp->llc_stripe has been allocated
2235                          * while it's init flag not been set until the exec
2236                          * phase.
2237                          */
2238                         if (!lu_extent_is_overlapped(&comp->llc_extent,
2239                                                      &lod_comp->llc_extent) ||
2240                             !comp->llc_stripe)
2241                                 continue;
2242
2243                         /**
2244                          * collect used OSTs index and OSS info from a
2245                          * component
2246                          */
2247                         for (j = 0; j < comp->llc_stripe_count; j++) {
2248                                 struct lod_tgt_desc *ost;
2249                                 struct lu_svr_qos *lsq;
2250                                 int k;
2251
2252                                 ost = OST_TGT(lod, comp->llc_ost_indices[j]);
2253                                 lsq = ost->ltd_qos.ltq_svr;
2254
2255                                 if (cfs_bitmap_check(bitmap, ost->ltd_index))
2256                                         continue;
2257
2258                                 QOS_DEBUG("OST%d used in conflicting mirror "
2259                                           "component\n", ost->ltd_index);
2260                                 cfs_bitmap_set(bitmap, ost->ltd_index);
2261                                 lag->lag_ost_avail--;
2262
2263                                 for (k = 0; k < lag->lag_oaa_count; k++) {
2264                                         if (lag->lag_oss_avoid_array[k] ==
2265                                             lsq->lsq_id)
2266                                                 break;
2267                                 }
2268                                 if (k == lag->lag_oaa_count) {
2269                                         lag->lag_oss_avoid_array[k] =
2270                                                                 lsq->lsq_id;
2271                                         lag->lag_oaa_count++;
2272                                 }
2273                         }
2274                 }
2275         }
2276 }
2277
2278 /**
2279  * Create a striping for an obejct.
2280  *
2281  * The function creates a new striping for the object. The function tries QoS
2282  * algorithm first unless free space is distributed evenly among OSTs, but
2283  * by default RR algorithm is preferred due to internal concurrency (QoS is
2284  * serialized). The caller must ensure no concurrent calls to the function
2285  * are made against the same object.
2286  *
2287  * \param[in] env       execution environment for this thread
2288  * \param[in] lo        LOD object
2289  * \param[in] attr      attributes OST objects will be declared with
2290  * \param[in] th        transaction handle
2291  * \param[in] comp_idx  index of ldo_comp_entries
2292  *
2293  * \retval 0            on success
2294  * \retval negative     negated errno on error
2295  */
2296 int lod_qos_prep_create(const struct lu_env *env, struct lod_object *lo,
2297                         struct lu_attr *attr, struct thandle *th,
2298                         int comp_idx)
2299 {
2300         struct lod_layout_component *lod_comp;
2301         struct lod_device      *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2302         int                     stripe_len;
2303         int                     flag = LOV_USES_ASSIGNED_STRIPE;
2304         int                     i, rc = 0;
2305         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
2306         struct dt_object **stripe = NULL;
2307         __u32 *ost_indices = NULL;
2308         ENTRY;
2309
2310         LASSERT(lo);
2311         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
2312         lod_comp = &lo->ldo_comp_entries[comp_idx];
2313
2314         /* A released component is being created */
2315         if (lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
2316                 RETURN(0);
2317
2318         /* A Data-on-MDT component is being created */
2319         if (lov_pattern(lod_comp->llc_pattern) == LOV_PATTERN_MDT)
2320                 RETURN(0);
2321
2322         if (likely(lod_comp->llc_stripe == NULL)) {
2323                 /*
2324                  * no striping has been created so far
2325                  */
2326                 LASSERT(lod_comp->llc_stripe_count);
2327                 /*
2328                  * statfs and check OST targets now, since ld_active_tgt_count
2329                  * could be changed if some OSTs are [de]activated manually.
2330                  */
2331                 lod_qos_statfs_update(env, d);
2332                 stripe_len = lod_get_stripe_count(d, lo,
2333                                                   lod_comp->llc_stripe_count,
2334                                                   lod_comp->llc_pattern &
2335                                                   LOV_PATTERN_OVERSTRIPING);
2336
2337                 if (stripe_len == 0)
2338                         GOTO(out, rc = -ERANGE);
2339                 lod_comp->llc_stripe_count = stripe_len;
2340                 OBD_ALLOC(stripe, sizeof(stripe[0]) * stripe_len);
2341                 if (stripe == NULL)
2342                         GOTO(out, rc = -ENOMEM);
2343                 OBD_ALLOC(ost_indices, sizeof(*ost_indices) * stripe_len);
2344                 if (!ost_indices)
2345                         GOTO(out, rc = -ENOMEM);
2346
2347                 lod_getref(&d->lod_ost_descs);
2348                 /* XXX: support for non-0 files w/o objects */
2349                 CDEBUG(D_OTHER, "tgt_count %d stripe_count %d\n",
2350                                 d->lod_desc.ld_tgt_count, stripe_len);
2351
2352                 if (lod_comp->llc_ostlist.op_array &&
2353                     lod_comp->llc_ostlist.op_count) {
2354                         rc = lod_alloc_ost_list(env, lo, stripe, ost_indices,
2355                                                 th, comp_idx);
2356                 } else if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT) {
2357                         /**
2358                          * collect OSTs and OSSs used in other mirrors whose
2359                          * components cross the ldo_comp_entries[comp_idx]
2360                          */
2361                         rc = lod_prepare_avoidance(env, lo);
2362                         if (rc)
2363                                 GOTO(put_ldts, rc);
2364
2365                         QOS_DEBUG("collecting conflict osts for comp[%d]\n",
2366                                   comp_idx);
2367                         lod_collect_avoidance(lo, lag, comp_idx);
2368
2369                         rc = lod_alloc_qos(env, lo, stripe, ost_indices, flag,
2370                                            th, comp_idx);
2371                         if (rc == -EAGAIN)
2372                                 rc = lod_alloc_rr(env, lo, stripe, ost_indices,
2373                                                   flag, th, comp_idx);
2374                 } else {
2375                         rc = lod_alloc_specific(env, lo, stripe, ost_indices,
2376                                                 flag, th, comp_idx);
2377                 }
2378 put_ldts:
2379                 lod_putref(d, &d->lod_ost_descs);
2380                 if (rc < 0) {
2381                         for (i = 0; i < stripe_len; i++)
2382                                 if (stripe[i] != NULL)
2383                                         dt_object_put(env, stripe[i]);
2384                         lod_comp->llc_stripe_count = 0;
2385                 } else {
2386                         lod_comp->llc_stripe = stripe;
2387                         lod_comp->llc_ost_indices = ost_indices;
2388                         lod_comp->llc_stripes_allocated = stripe_len;
2389                 }
2390         } else {
2391                 /*
2392                  * lod_qos_parse_config() found supplied buf as a predefined
2393                  * striping (not a hint), so it allocated all the object
2394                  * now we need to create them
2395                  */
2396                 for (i = 0; i < lod_comp->llc_stripe_count; i++) {
2397                         struct dt_object  *o;
2398
2399                         o = lod_comp->llc_stripe[i];
2400                         LASSERT(o);
2401
2402                         rc = lod_sub_declare_create(env, o, attr, NULL,
2403                                                     NULL, th);
2404                         if (rc < 0) {
2405                                 CERROR("can't declare create: %d\n", rc);
2406                                 break;
2407                         }
2408                 }
2409                 /**
2410                  * Clear LCME_FL_INIT for the component so that
2411                  * lod_striping_create() can create the striping objects
2412                  * in replay.
2413                  */
2414                 lod_comp_unset_init(lod_comp);
2415         }
2416
2417 out:
2418         if (rc < 0) {
2419                 if (stripe)
2420                         OBD_FREE(stripe, sizeof(stripe[0]) * stripe_len);
2421                 if (ost_indices)
2422                         OBD_FREE(ost_indices,
2423                                  sizeof(*ost_indices) * stripe_len);
2424         }
2425         RETURN(rc);
2426 }
2427
2428 int lod_prepare_create(const struct lu_env *env, struct lod_object *lo,
2429                        struct lu_attr *attr, const struct lu_buf *buf,
2430                        struct thandle *th)
2431
2432 {
2433         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2434         uint64_t size = 0;
2435         int i;
2436         int rc;
2437         ENTRY;
2438
2439         LASSERT(lo);
2440
2441         /* no OST available */
2442         /* XXX: should we be waiting a bit to prevent failures during
2443          * cluster initialization? */
2444         if (d->lod_ostnr == 0)
2445                 RETURN(-EIO);
2446
2447         /*
2448          * by this time, the object's ldo_stripe_count and ldo_stripe_size
2449          * contain default value for striping: taken from the parent
2450          * or from filesystem defaults
2451          *
2452          * in case the caller is passing lovea with new striping config,
2453          * we may need to parse lovea and apply new configuration
2454          */
2455         rc = lod_qos_parse_config(env, lo, buf);
2456         if (rc)
2457                 RETURN(rc);
2458
2459         if (attr->la_valid & LA_SIZE)
2460                 size = attr->la_size;
2461
2462         /**
2463          * prepare OST object creation for the component covering file's
2464          * size, the 1st component (including plain layout file) is always
2465          * instantiated.
2466          */
2467         for (i = 0; i < lo->ldo_comp_cnt; i++) {
2468                 struct lod_layout_component *lod_comp;
2469                 struct lu_extent *extent;
2470
2471                 lod_comp = &lo->ldo_comp_entries[i];
2472                 extent = &lod_comp->llc_extent;
2473                 QOS_DEBUG("comp[%d] %lld "DEXT"\n", i, size, PEXT(extent));
2474                 if (!lo->ldo_is_composite || size >= extent->e_start) {
2475                         rc = lod_qos_prep_create(env, lo, attr, th, i);
2476                         if (rc)
2477                                 break;
2478                 }
2479         }
2480
2481         RETURN(rc);
2482 }