Whamcloud - gitweb
LU-4665 utils: lfs setstripe to specify OSTs
[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, 2013, 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 <libcfs/libcfs.h>
42 #include <obd_class.h>
43 #include <lustre/lustre_idl.h>
44 #include "lod_internal.h"
45
46 /*
47  * force QoS policy (not RR) to be used for testing purposes
48  */
49 #define FORCE_QOS_
50
51 #define D_QOS   D_OTHER
52
53 #if 0
54 #define QOS_DEBUG(fmt, ...)     CDEBUG(D_OTHER, fmt, ## __VA_ARGS__)
55 #define QOS_CONSOLE(fmt, ...)   LCONSOLE(D_OTHER, fmt, ## __VA_ARGS__)
56 #else
57 #define QOS_DEBUG(fmt, ...)
58 #define QOS_CONSOLE(fmt, ...)
59 #endif
60
61 #define TGT_BAVAIL(i) (OST_TGT(lod,i)->ltd_statfs.os_bavail * \
62                        OST_TGT(lod,i)->ltd_statfs.os_bsize)
63
64 /**
65  * Add a new target to Quality of Service (QoS) target table.
66  *
67  * Add a new OST target to the structure representing an OSS. Resort the list
68  * of known OSSs by the number of OSTs attached to each OSS. The OSS list is
69  * protected internally and no external locking is required.
70  *
71  * \param[in] lod               LOD device
72  * \param[in] ost_desc          OST description
73  *
74  * \retval 0                    on success
75  * \retval -ENOMEM              on error
76  */
77 int qos_add_tgt(struct lod_device *lod, struct lod_tgt_desc *ost_desc)
78 {
79         struct lod_qos_oss *oss = NULL, *temposs;
80         struct obd_export  *exp = ost_desc->ltd_exp;
81         int                 rc = 0, found = 0;
82         struct list_head   *list;
83         ENTRY;
84
85         down_write(&lod->lod_qos.lq_rw_sem);
86         /*
87          * a bit hacky approach to learn NID of corresponding connection
88          * but there is no official API to access information like this
89          * with OSD API.
90          */
91         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
92                 if (obd_uuid_equals(&oss->lqo_uuid,
93                                     &exp->exp_connection->c_remote_uuid)) {
94                         found++;
95                         break;
96                 }
97         }
98
99         if (!found) {
100                 OBD_ALLOC_PTR(oss);
101                 if (!oss)
102                         GOTO(out, rc = -ENOMEM);
103                 memcpy(&oss->lqo_uuid, &exp->exp_connection->c_remote_uuid,
104                        sizeof(oss->lqo_uuid));
105         } else {
106                 /* Assume we have to move this one */
107                 list_del(&oss->lqo_oss_list);
108         }
109
110         oss->lqo_ost_count++;
111         ost_desc->ltd_qos.ltq_oss = oss;
112
113         CDEBUG(D_QOS, "add tgt %s to OSS %s (%d OSTs)\n",
114                obd_uuid2str(&ost_desc->ltd_uuid), obd_uuid2str(&oss->lqo_uuid),
115                oss->lqo_ost_count);
116
117         /* Add sorted by # of OSTs.  Find the first entry that we're
118            bigger than... */
119         list = &lod->lod_qos.lq_oss_list;
120         list_for_each_entry(temposs, list, lqo_oss_list) {
121                 if (oss->lqo_ost_count > temposs->lqo_ost_count)
122                         break;
123         }
124         /* ...and add before it.  If we're the first or smallest, temposs
125            points to the list head, and we add to the end. */
126         list_add_tail(&oss->lqo_oss_list, &temposs->lqo_oss_list);
127
128         lod->lod_qos.lq_dirty = 1;
129         lod->lod_qos.lq_rr.lqr_dirty = 1;
130
131 out:
132         up_write(&lod->lod_qos.lq_rw_sem);
133         RETURN(rc);
134 }
135
136 /**
137  * Remove OST target from QoS table.
138  *
139  * Removes given OST target from QoS table and releases related OSS structure
140  * if no OSTs remain on the OSS.
141  *
142  * \param[in] lod               LOD device
143  * \param[in] ost_desc          OST description
144  *
145  * \retval 0                    on success
146  * \retval -ENOENT              if no OSS was found
147  */
148 int qos_del_tgt(struct lod_device *lod, struct lod_tgt_desc *ost_desc)
149 {
150         struct lod_qos_oss *oss;
151         int                 rc = 0;
152         ENTRY;
153
154         down_write(&lod->lod_qos.lq_rw_sem);
155         oss = ost_desc->ltd_qos.ltq_oss;
156         if (!oss)
157                 GOTO(out, rc = -ENOENT);
158
159         oss->lqo_ost_count--;
160         if (oss->lqo_ost_count == 0) {
161                 CDEBUG(D_QOS, "removing OSS %s\n",
162                        obd_uuid2str(&oss->lqo_uuid));
163                 list_del(&oss->lqo_oss_list);
164                 ost_desc->ltd_qos.ltq_oss = NULL;
165                 OBD_FREE_PTR(oss);
166         }
167
168         lod->lod_qos.lq_dirty = 1;
169         lod->lod_qos.lq_rr.lqr_dirty = 1;
170 out:
171         up_write(&lod->lod_qos.lq_rw_sem);
172         RETURN(rc);
173 }
174
175 /**
176  * Check whether the target is available for new OST objects.
177  *
178  * Request statfs data from the given target and verify it's active and not
179  * read-only. If so, then it can be used to place new OST objects. This
180  * function also maintains the number of active/inactive targets and sets
181  * dirty flags if those numbers change so others can run re-balance procedures.
182  * No external locking is required.
183  *
184  * \param[in] env       execution environment for this thread
185  * \param[in] d         LOD device
186  * \param[in] index     index of OST target to check
187  * \param[out] sfs      buffer for statfs data
188  *
189  * \retval 0            if the target is good
190  * \retval negative     negated errno on error
191
192  */
193 static int lod_statfs_and_check(const struct lu_env *env, struct lod_device *d,
194                                 int index, struct obd_statfs *sfs)
195 {
196         struct lod_tgt_desc *ost;
197         int                  rc;
198
199         LASSERT(d);
200         ost = OST_TGT(d,index);
201         LASSERT(ost);
202
203         rc = dt_statfs(env, ost->ltd_ost, sfs);
204         if (rc && rc != -ENOTCONN)
205                 CERROR("%s: statfs: rc = %d\n", lod2obd(d)->obd_name, rc);
206
207         /* If the OST is readonly then we can't allocate objects there */
208         if (sfs->os_state & OS_STATE_READONLY)
209                 rc = -EROFS;
210
211         /* check whether device has changed state (active, inactive) */
212         if (rc != 0 && ost->ltd_active) {
213                 /* turned inactive? */
214                 spin_lock(&d->lod_desc_lock);
215                 if (ost->ltd_active) {
216                         ost->ltd_active = 0;
217                         LASSERT(d->lod_desc.ld_active_tgt_count > 0);
218                         d->lod_desc.ld_active_tgt_count--;
219                         d->lod_qos.lq_dirty = 1;
220                         d->lod_qos.lq_rr.lqr_dirty = 1;
221                         CDEBUG(D_CONFIG, "%s: turns inactive\n",
222                                ost->ltd_exp->exp_obd->obd_name);
223                 }
224                 spin_unlock(&d->lod_desc_lock);
225         } else if (rc == 0 && ost->ltd_active == 0) {
226                 /* turned active? */
227                 LASSERTF(d->lod_desc.ld_active_tgt_count < d->lod_ostnr,
228                          "active tgt count %d, ost nr %d\n",
229                          d->lod_desc.ld_active_tgt_count, d->lod_ostnr);
230                 spin_lock(&d->lod_desc_lock);
231                 if (ost->ltd_active == 0) {
232                         ost->ltd_active = 1;
233                         d->lod_desc.ld_active_tgt_count++;
234                         d->lod_qos.lq_dirty = 1;
235                         d->lod_qos.lq_rr.lqr_dirty = 1;
236                         CDEBUG(D_CONFIG, "%s: turns active\n",
237                                ost->ltd_exp->exp_obd->obd_name);
238                 }
239                 spin_unlock(&d->lod_desc_lock);
240         }
241
242         RETURN(rc);
243 }
244
245 /**
246  * Maintain per-target statfs data.
247  *
248  * The function refreshes statfs data for all the targets every N seconds.
249  * The actual N is controlled via procfs and set to LOV_DESC_QOS_MAXAGE_DEFAULT
250  * initially.
251  *
252  * \param[in] env       execution environment for this thread
253  * \param[in] lod       LOD device
254  */
255 static void lod_qos_statfs_update(const struct lu_env *env,
256                                   struct lod_device *lod)
257 {
258         struct obd_device *obd = lod2obd(lod);
259         struct ost_pool   *osts = &(lod->lod_pool_info);
260         unsigned int       i;
261         int                idx, rc = 0;
262         __u64              max_age, avail;
263         ENTRY;
264
265         max_age = cfs_time_shift_64(-2 * lod->lod_desc.ld_qos_maxage);
266
267         if (cfs_time_beforeq_64(max_age, obd->obd_osfs_age))
268                 /* statfs data are quite recent, don't need to refresh it */
269                 RETURN_EXIT;
270
271         down_write(&lod->lod_qos.lq_rw_sem);
272         if (cfs_time_beforeq_64(max_age, obd->obd_osfs_age))
273                 GOTO(out, rc = 0);
274
275         for (i = 0; i < osts->op_count; i++) {
276                 idx = osts->op_array[i];
277                 avail = OST_TGT(lod,idx)->ltd_statfs.os_bavail;
278                 rc = lod_statfs_and_check(env, lod, idx,
279                                           &OST_TGT(lod,idx)->ltd_statfs);
280                 if (rc)
281                         break;
282                 if (OST_TGT(lod,idx)->ltd_statfs.os_bavail != avail)
283                         /* recalculate weigths */
284                         lod->lod_qos.lq_dirty = 1;
285         }
286         obd->obd_osfs_age = cfs_time_current_64();
287
288 out:
289         up_write(&lod->lod_qos.lq_rw_sem);
290         EXIT;
291 }
292
293 /**
294  * Calculate per-OST and per-OSS penalties
295  *
296  * Re-calculate penalties when the configuration changes, active targets
297  * change and after statfs refresh (all these are reflected by lq_dirty flag).
298  * On every OST and OSS: decay the penalty by half for every 8x the update
299  * interval that the device has been idle. That gives lots of time for the
300  * statfs information to be updated (which the penalty is only a proxy for),
301  * and avoids penalizing OSS/OSTs under light load.
302  * See lod_qos_calc_weight() for how penalties are factored into the weight.
303  *
304  * \param[in] lod       LOD device
305  *
306  * \retval 0            on success
307  * \retval -EAGAIN      the number of OSTs isn't enough
308  */
309 static int lod_qos_calc_ppo(struct lod_device *lod)
310 {
311         struct lod_qos_oss *oss;
312         __u64               ba_max, ba_min, temp;
313         __u32               num_active;
314         unsigned int        i;
315         int                 rc, prio_wide;
316         time_t              now, age;
317         ENTRY;
318
319         if (!lod->lod_qos.lq_dirty)
320                 GOTO(out, rc = 0);
321
322         num_active = lod->lod_desc.ld_active_tgt_count - 1;
323         if (num_active < 1)
324                 GOTO(out, rc = -EAGAIN);
325
326         /* find bavail on each OSS */
327         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list)
328                             oss->lqo_bavail = 0;
329         lod->lod_qos.lq_active_oss_count = 0;
330
331         /*
332          * How badly user wants to select OSTs "widely" (not recently chosen
333          * and not on recent OSS's).  As opposed to "freely" (free space
334          * avail.) 0-256
335          */
336         prio_wide = 256 - lod->lod_qos.lq_prio_free;
337
338         ba_min = (__u64)(-1);
339         ba_max = 0;
340         now = cfs_time_current_sec();
341         /* Calculate OST penalty per object
342          * (lod ref taken in lod_qos_prep_create()) */
343         cfs_foreach_bit(lod->lod_ost_bitmap, i) {
344                 LASSERT(OST_TGT(lod,i));
345                 temp = TGT_BAVAIL(i);
346                 if (!temp)
347                         continue;
348                 ba_min = min(temp, ba_min);
349                 ba_max = max(temp, ba_max);
350
351                 /* Count the number of usable OSS's */
352                 if (OST_TGT(lod,i)->ltd_qos.ltq_oss->lqo_bavail == 0)
353                         lod->lod_qos.lq_active_oss_count++;
354                 OST_TGT(lod,i)->ltd_qos.ltq_oss->lqo_bavail += temp;
355
356                 /* per-OST penalty is prio * TGT_bavail / (num_ost - 1) / 2 */
357                 temp >>= 1;
358                 do_div(temp, num_active);
359                 OST_TGT(lod,i)->ltd_qos.ltq_penalty_per_obj =
360                         (temp * prio_wide) >> 8;
361
362                 age = (now - OST_TGT(lod,i)->ltd_qos.ltq_used) >> 3;
363                 if (lod->lod_qos.lq_reset ||
364                     age > 32 * lod->lod_desc.ld_qos_maxage)
365                         OST_TGT(lod,i)->ltd_qos.ltq_penalty = 0;
366                 else if (age > lod->lod_desc.ld_qos_maxage)
367                         /* Decay OST penalty. */
368                         OST_TGT(lod,i)->ltd_qos.ltq_penalty >>=
369                                 (age / lod->lod_desc.ld_qos_maxage);
370         }
371
372         num_active = lod->lod_qos.lq_active_oss_count - 1;
373         if (num_active < 1) {
374                 /* If there's only 1 OSS, we can't penalize it, so instead
375                    we have to double the OST penalty */
376                 num_active = 1;
377                 cfs_foreach_bit(lod->lod_ost_bitmap, i)
378                         OST_TGT(lod,i)->ltd_qos.ltq_penalty_per_obj <<= 1;
379         }
380
381         /* Per-OSS penalty is prio * oss_avail / oss_osts / (num_oss - 1) / 2 */
382         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
383                 temp = oss->lqo_bavail >> 1;
384                 do_div(temp, oss->lqo_ost_count * num_active);
385                 oss->lqo_penalty_per_obj = (temp * prio_wide) >> 8;
386
387                 age = (now - oss->lqo_used) >> 3;
388                 if (lod->lod_qos.lq_reset ||
389                     age > 32 * lod->lod_desc.ld_qos_maxage)
390                         oss->lqo_penalty = 0;
391                 else if (age > lod->lod_desc.ld_qos_maxage)
392                         /* Decay OSS penalty. */
393                         oss->lqo_penalty >>= age / lod->lod_desc.ld_qos_maxage;
394         }
395
396         lod->lod_qos.lq_dirty = 0;
397         lod->lod_qos.lq_reset = 0;
398
399         /* If each ost has almost same free space,
400          * do rr allocation for better creation performance */
401         lod->lod_qos.lq_same_space = 0;
402         if ((ba_max * (256 - lod->lod_qos.lq_threshold_rr)) >> 8 < ba_min) {
403                 lod->lod_qos.lq_same_space = 1;
404                 /* Reset weights for the next time we enter qos mode */
405                 lod->lod_qos.lq_reset = 1;
406         }
407         rc = 0;
408
409 out:
410 #ifndef FORCE_QOS
411         if (!rc && lod->lod_qos.lq_same_space)
412                 RETURN(-EAGAIN);
413 #endif
414         RETURN(rc);
415 }
416
417 /**
418  * Calculate weight for a given OST target.
419  *
420  * The final OST weight is the number of bytes available minus the OST and
421  * OSS penalties.  See lod_qos_calc_ppo() for how penalties are calculated.
422  *
423  * \param[in] lod       LOD device, where OST targets are listed
424  * \param[in] i         OST target index
425  *
426  * \retval              0
427  */
428 static int lod_qos_calc_weight(struct lod_device *lod, int i)
429 {
430         __u64 temp, temp2;
431
432         temp = TGT_BAVAIL(i);
433         temp2 = OST_TGT(lod,i)->ltd_qos.ltq_penalty +
434                 OST_TGT(lod,i)->ltd_qos.ltq_oss->lqo_penalty;
435         if (temp < temp2)
436                 OST_TGT(lod,i)->ltd_qos.ltq_weight = 0;
437         else
438                 OST_TGT(lod,i)->ltd_qos.ltq_weight = temp - temp2;
439         return 0;
440 }
441
442 /**
443  * Re-calculate weights.
444  *
445  * The function is called when some OST target was used for a new object. In
446  * this case we should re-calculate all the weights to keep new allocations
447  * balanced well.
448  *
449  * \param[in] lod       LOD device
450  * \param[in] osts      OST pool where a new object was placed
451  * \param[in] index     OST target where a new object was placed
452  * \param[out] total_wt new total weight for the pool
453  *
454  * \retval              0
455  */
456 static int lod_qos_used(struct lod_device *lod, struct ost_pool *osts,
457                         __u32 index, __u64 *total_wt)
458 {
459         struct lod_tgt_desc *ost;
460         struct lod_qos_oss  *oss;
461         unsigned int j;
462         ENTRY;
463
464         ost = OST_TGT(lod,index);
465         LASSERT(ost);
466
467         /* Don't allocate on this devuce anymore, until the next alloc_qos */
468         ost->ltd_qos.ltq_usable = 0;
469
470         oss = ost->ltd_qos.ltq_oss;
471
472         /* Decay old penalty by half (we're adding max penalty, and don't
473            want it to run away.) */
474         ost->ltd_qos.ltq_penalty >>= 1;
475         oss->lqo_penalty >>= 1;
476
477         /* mark the OSS and OST as recently used */
478         ost->ltd_qos.ltq_used = oss->lqo_used = cfs_time_current_sec();
479
480         /* Set max penalties for this OST and OSS */
481         ost->ltd_qos.ltq_penalty +=
482                 ost->ltd_qos.ltq_penalty_per_obj * lod->lod_ostnr;
483         oss->lqo_penalty += oss->lqo_penalty_per_obj *
484                 lod->lod_qos.lq_active_oss_count;
485
486         /* Decrease all OSS penalties */
487         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
488                 if (oss->lqo_penalty < oss->lqo_penalty_per_obj)
489                         oss->lqo_penalty = 0;
490                 else
491                         oss->lqo_penalty -= oss->lqo_penalty_per_obj;
492         }
493
494         *total_wt = 0;
495         /* Decrease all OST penalties */
496         for (j = 0; j < osts->op_count; j++) {
497                 int i;
498
499                 i = osts->op_array[j];
500                 if (!cfs_bitmap_check(lod->lod_ost_bitmap, i))
501                         continue;
502
503                 ost = OST_TGT(lod,i);
504                 LASSERT(ost);
505
506                 if (ost->ltd_qos.ltq_penalty <
507                                 ost->ltd_qos.ltq_penalty_per_obj)
508                         ost->ltd_qos.ltq_penalty = 0;
509                 else
510                         ost->ltd_qos.ltq_penalty -=
511                                 ost->ltd_qos.ltq_penalty_per_obj;
512
513                 lod_qos_calc_weight(lod, i);
514
515                 /* Recalc the total weight of usable osts */
516                 if (ost->ltd_qos.ltq_usable)
517                         *total_wt += ost->ltd_qos.ltq_weight;
518
519                 QOS_DEBUG("recalc tgt %d usable=%d avail="LPU64
520                           " ostppo="LPU64" ostp="LPU64" ossppo="LPU64
521                           " ossp="LPU64" wt="LPU64"\n",
522                           i, ost->ltd_qos.ltq_usable, TGT_BAVAIL(i) >> 10,
523                           ost->ltd_qos.ltq_penalty_per_obj >> 10,
524                           ost->ltd_qos.ltq_penalty >> 10,
525                           ost->ltd_qos.ltq_oss->lqo_penalty_per_obj >> 10,
526                           ost->ltd_qos.ltq_oss->lqo_penalty >> 10,
527                           ost->ltd_qos.ltq_weight >> 10);
528         }
529
530         RETURN(0);
531 }
532
533 #define LOV_QOS_EMPTY ((__u32)-1)
534
535 /**
536  * Calculate optimal round-robin order with regard to OSSes.
537  *
538  * Place all the OSTs from pool \a src_pool in a special array to be used for
539  * round-robin (RR) stripe allocation.  The placement algorithm interleaves
540  * OSTs from the different OSSs so that RR allocation can balance OSSs evenly.
541  * Resorts the targets when the number of active targets changes (because of
542  * a new target or activation/deactivation).
543  *
544  * \param[in] lod       LOD device
545  * \param[in] src_pool  OST pool
546  * \param[in] lqr       round-robin list
547  *
548  * \retval 0            on success
549  * \retval -ENOMEM      fails to allocate the array
550  */
551 static int lod_qos_calc_rr(struct lod_device *lod, struct ost_pool *src_pool,
552                            struct lod_qos_rr *lqr)
553 {
554         struct lod_qos_oss  *oss;
555         struct lod_tgt_desc *ost;
556         unsigned placed, real_count;
557         unsigned int i;
558         int rc;
559         ENTRY;
560
561         if (!lqr->lqr_dirty) {
562                 LASSERT(lqr->lqr_pool.op_size);
563                 RETURN(0);
564         }
565
566         /* Do actual allocation. */
567         down_write(&lod->lod_qos.lq_rw_sem);
568
569         /*
570          * Check again. While we were sleeping on @lq_rw_sem something could
571          * change.
572          */
573         if (!lqr->lqr_dirty) {
574                 LASSERT(lqr->lqr_pool.op_size);
575                 up_write(&lod->lod_qos.lq_rw_sem);
576                 RETURN(0);
577         }
578
579         real_count = src_pool->op_count;
580
581         /* Zero the pool array */
582         /* alloc_rr is holding a read lock on the pool, so nobody is adding/
583            deleting from the pool. The lq_rw_sem insures that nobody else
584            is reading. */
585         lqr->lqr_pool.op_count = real_count;
586         rc = lod_ost_pool_extend(&lqr->lqr_pool, real_count);
587         if (rc) {
588                 up_write(&lod->lod_qos.lq_rw_sem);
589                 RETURN(rc);
590         }
591         for (i = 0; i < lqr->lqr_pool.op_count; i++)
592                 lqr->lqr_pool.op_array[i] = LOV_QOS_EMPTY;
593
594         /* Place all the OSTs from 1 OSS at the same time. */
595         placed = 0;
596         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
597                 int j = 0;
598
599                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
600                         int next;
601
602                         if (!cfs_bitmap_check(lod->lod_ost_bitmap,
603                                                 src_pool->op_array[i]))
604                                 continue;
605
606                         ost = OST_TGT(lod,src_pool->op_array[i]);
607                         LASSERT(ost && ost->ltd_ost);
608                         if (ost->ltd_qos.ltq_oss != oss)
609                                 continue;
610
611                         /* Evenly space these OSTs across arrayspace */
612                         next = j * lqr->lqr_pool.op_count / oss->lqo_ost_count;
613                         while (lqr->lqr_pool.op_array[next] != LOV_QOS_EMPTY)
614                                 next = (next + 1) % lqr->lqr_pool.op_count;
615
616                         lqr->lqr_pool.op_array[next] = src_pool->op_array[i];
617                         j++;
618                         placed++;
619                 }
620         }
621
622         lqr->lqr_dirty = 0;
623         up_write(&lod->lod_qos.lq_rw_sem);
624
625         if (placed != real_count) {
626                 /* This should never happen */
627                 LCONSOLE_ERROR_MSG(0x14e, "Failed to place all OSTs in the "
628                                    "round-robin list (%d of %d).\n",
629                                    placed, real_count);
630                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
631                         LCONSOLE(D_WARNING, "rr #%d ost idx=%d\n", i,
632                                  lqr->lqr_pool.op_array[i]);
633                 }
634                 lqr->lqr_dirty = 1;
635                 RETURN(-EAGAIN);
636         }
637
638 #if 0
639         for (i = 0; i < lqr->lqr_pool.op_count; i++)
640                 QOS_CONSOLE("rr #%d ost idx=%d\n", i, lqr->lqr_pool.op_array[i]);
641 #endif
642
643         RETURN(0);
644 }
645
646 /**
647  * Instantiate and declare creation of a new object.
648  *
649  * The function instantiates LU representation for a new object on the
650  * specified device. Also it declares an intention to create that
651  * object on the storage target.
652  *
653  * Note lu_object_anon() is used which is a trick with regard to LU/OSD
654  * infrastructure - in the existing precreation framework we can't assign FID
655  * at this moment, we do this later once a transaction is started. So the
656  * special method instantiates FID-less object in the cache and later it
657  * will get a FID and proper placement in LU cache.
658  *
659  * \param[in] env       execution environment for this thread
660  * \param[in] d         LOD device
661  * \param[in] ost_idx   OST target index where the object is being created
662  * \param[in] th        transaction handle
663  *
664  * \retval              object ptr on success, ERR_PTR() otherwise
665  */
666 static struct dt_object *lod_qos_declare_object_on(const struct lu_env *env,
667                                                    struct lod_device *d,
668                                                    __u32 ost_idx,
669                                                    struct thandle *th)
670 {
671         struct lod_tgt_desc *ost;
672         struct lu_object *o, *n;
673         struct lu_device *nd;
674         struct dt_object *dt;
675         int               rc;
676         ENTRY;
677
678         LASSERT(d);
679         LASSERT(ost_idx < d->lod_osts_size);
680         ost = OST_TGT(d,ost_idx);
681         LASSERT(ost);
682         LASSERT(ost->ltd_ost);
683
684         nd = &ost->ltd_ost->dd_lu_dev;
685
686         /*
687          * allocate anonymous object with zero fid, real fid
688          * will be assigned by OSP within transaction
689          * XXX: to be fixed with fully-functional OST fids
690          */
691         o = lu_object_anon(env, nd, NULL);
692         if (IS_ERR(o))
693                 GOTO(out, dt = ERR_PTR(PTR_ERR(o)));
694
695         n = lu_object_locate(o->lo_header, nd->ld_type);
696         if (unlikely(n == NULL)) {
697                 CERROR("can't find slice\n");
698                 lu_object_put(env, o);
699                 GOTO(out, dt = ERR_PTR(-EINVAL));
700         }
701
702         dt = container_of(n, struct dt_object, do_lu);
703
704         rc = dt_declare_create(env, dt, NULL, NULL, NULL, th);
705         if (rc) {
706                 CDEBUG(D_OTHER, "can't declare creation on #%u: %d\n",
707                        ost_idx, rc);
708                 lu_object_put(env, o);
709                 dt = ERR_PTR(rc);
710         }
711
712 out:
713         RETURN(dt);
714 }
715
716 /**
717  * Calculate a minimum acceptable stripe count.
718  *
719  * Return an acceptable stripe count depending on flag LOV_USES_DEFAULT_STRIPE:
720  * all stripes or 3/4 of stripes.
721  *
722  * \param[in] stripe_cnt        number of stripes requested
723  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
724  *
725  * \retval                      acceptable stripecount
726  */
727 static int min_stripe_count(__u32 stripe_cnt, int flags)
728 {
729         return (flags & LOV_USES_DEFAULT_STRIPE ?
730                         stripe_cnt - (stripe_cnt / 4) : stripe_cnt);
731 }
732
733 #define LOV_CREATE_RESEED_MULT 30
734 #define LOV_CREATE_RESEED_MIN  2000
735
736 /**
737  * Check if an OST is full.
738  *
739  * Check whether an OST should be considered full based
740  * on the given statfs data.
741  *
742  * \param[in] msfs      statfs data
743  *
744  * \retval false        not full
745  * \retval true         full
746  */
747 static int inline lod_qos_dev_is_full(struct obd_statfs *msfs)
748 {
749         __u64 used;
750         int   bs = msfs->os_bsize;
751
752         LASSERT(((bs - 1) & bs) == 0);
753
754         /* the minimum of 0.1% used blocks and 1GB bytes. */
755         used = min_t(__u64, (msfs->os_blocks - msfs->os_bfree) >> 10,
756                         1 << (31 - ffs(bs)));
757         return (msfs->os_bavail < used);
758 }
759
760 /**
761  * Initialize temporary OST-in-use array.
762  *
763  * Allocate or extend the array used to mark targets already assigned to a new
764  * striping so they are not used more than once.
765  *
766  * \param[in] env       execution environment for this thread
767  * \param[in] stripes   number of items needed in the array
768  *
769  * \retval 0            on success
770  * \retval -ENOMEM      on error
771  */
772 static inline int lod_qos_ost_in_use_clear(const struct lu_env *env,
773                                            __u32 stripes)
774 {
775         struct lod_thread_info *info = lod_env_info(env);
776
777         if (info->lti_ea_store_size < sizeof(int) * stripes)
778                 lod_ea_store_resize(info, stripes * sizeof(int));
779         if (info->lti_ea_store_size < sizeof(int) * stripes) {
780                 CERROR("can't allocate memory for ost-in-use array\n");
781                 return -ENOMEM;
782         }
783         memset(info->lti_ea_store, -1, sizeof(int) * stripes);
784         return 0;
785 }
786
787 /**
788  * Remember a target in the array of used targets.
789  *
790  * Mark the given target as used for a new striping being created. The status
791  * of an OST in a striping can be checked with lod_qos_is_ost_used().
792  *
793  * \param[in] env       execution environment for this thread
794  * \param[in] idx       index in the array
795  * \param[in] ost       OST target index to mark as used
796  */
797 static inline void lod_qos_ost_in_use(const struct lu_env *env,
798                                       int idx, int ost)
799 {
800         struct lod_thread_info *info = lod_env_info(env);
801         int *osts = info->lti_ea_store;
802
803         LASSERT(info->lti_ea_store_size >= idx * sizeof(int));
804         osts[idx] = ost;
805 }
806
807 /**
808  * Check is OST used in a striping.
809  *
810  * Checks whether OST with the given index is marked as used in the temporary
811  * array (see lod_qos_ost_in_use()).
812  *
813  * \param[in] env       execution environment for this thread
814  * \param[in] ost       OST target index to check
815  * \param[in] stripes   the number of items used in the array already
816  *
817  * \retval 0            not used
818  * \retval 1            used
819  */
820 static int lod_qos_is_ost_used(const struct lu_env *env, int ost, __u32 stripes)
821 {
822         struct lod_thread_info *info = lod_env_info(env);
823         int *osts = info->lti_ea_store;
824         __u32 j;
825
826         for (j = 0; j < stripes; j++) {
827                 if (osts[j] == ost)
828                         return 1;
829         }
830         return 0;
831 }
832
833 /**
834  * Allocate a striping using round-robin algorigthm.
835  *
836  * Allocates a new striping using round-robin algorithm. The function refreshes
837  * all the internal structures (statfs cache, array of available OSTs sorted
838  * with regard to OSS, etc). The number of stripes required is taken from the
839  * object (must be prepared by the caller), but can change if the flag
840  * LOV_USES_DEFAULT_STRIPE is supplied. The caller should ensure nobody else
841  * is trying to create a striping on the object in parallel. All the internal
842  * structures (like pools, etc) are protected and no additional locking is
843  * required. The function succeeds even if a single stripe is allocated. To save
844  * time we give priority to targets which already have objects precreated.
845  * Full OSTs are skipped (see lod_qos_dev_is_full() for the details).
846  *
847  * \param[in] env       execution environment for this thread
848  * \param[in] lo        LOD object
849  * \param[out] stripe   striping created
850  * \param[in] flags     allocation flags (0 or LOV_USES_DEFAULT_STRIPE)
851  * \param[in] th        transaction handle
852  *
853  * \retval 0            on success
854  * \retval -ENOSPC      if not enough OSTs are found
855  * \retval negative     negated errno for other failures
856  */
857 static int lod_alloc_rr(const struct lu_env *env, struct lod_object *lo,
858                         struct dt_object **stripe, int flags,
859                         struct thandle *th)
860 {
861         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
862         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
863         struct pool_desc  *pool = NULL;
864         struct ost_pool   *osts;
865         struct lod_qos_rr *lqr;
866         struct dt_object  *o;
867         unsigned int       i, array_idx;
868         int                rc;
869         __u32              ost_start_idx_temp;
870         int                speed = 0;
871         __u32              stripe_idx = 0;
872         __u32              stripe_cnt = lo->ldo_stripenr;
873         __u32              stripe_cnt_min = min_stripe_count(stripe_cnt, flags);
874         __u32              ost_idx;
875         ENTRY;
876
877         if (lo->ldo_pool)
878                 pool = lod_find_pool(m, lo->ldo_pool);
879
880         if (pool != NULL) {
881                 down_read(&pool_tgt_rw_sem(pool));
882                 osts = &(pool->pool_obds);
883                 lqr = &(pool->pool_rr);
884         } else {
885                 osts = &(m->lod_pool_info);
886                 lqr = &(m->lod_qos.lq_rr);
887         }
888
889         rc = lod_qos_calc_rr(m, osts, lqr);
890         if (rc)
891                 GOTO(out, rc);
892
893         rc = lod_qos_ost_in_use_clear(env, lo->ldo_stripenr);
894         if (rc)
895                 GOTO(out, rc);
896
897         if (--lqr->lqr_start_count <= 0) {
898                 lqr->lqr_start_idx = cfs_rand() % osts->op_count;
899                 lqr->lqr_start_count =
900                         (LOV_CREATE_RESEED_MIN / max(osts->op_count, 1U) +
901                          LOV_CREATE_RESEED_MULT) * max(osts->op_count, 1U);
902         } else if (stripe_cnt_min >= osts->op_count ||
903                         lqr->lqr_start_idx > osts->op_count) {
904                 /* If we have allocated from all of the OSTs, slowly
905                  * precess the next start if the OST/stripe count isn't
906                  * already doing this for us. */
907                 lqr->lqr_start_idx %= osts->op_count;
908                 if (stripe_cnt > 1 && (osts->op_count % stripe_cnt) != 1)
909                         ++lqr->lqr_offset_idx;
910         }
911         down_read(&m->lod_qos.lq_rw_sem);
912         ost_start_idx_temp = lqr->lqr_start_idx;
913
914 repeat_find:
915         array_idx = (lqr->lqr_start_idx + lqr->lqr_offset_idx) %
916                         osts->op_count;
917
918         QOS_DEBUG("pool '%s' want %d startidx %d startcnt %d offset %d "
919                   "active %d count %d arrayidx %d\n",
920                   lo->ldo_pool ? lo->ldo_pool : "",
921                   stripe_cnt, lqr->lqr_start_idx, lqr->lqr_start_count,
922                   lqr->lqr_offset_idx, osts->op_count, osts->op_count,
923                   array_idx);
924
925         for (i = 0; i < osts->op_count && stripe_idx < lo->ldo_stripenr;
926              i++, array_idx = (array_idx + 1) % osts->op_count) {
927                 ++lqr->lqr_start_idx;
928                 ost_idx = lqr->lqr_pool.op_array[array_idx];
929
930                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
931                           i, lqr->lqr_start_idx, /* XXX: active*/ 0,
932                           stripe_idx, array_idx, ost_idx);
933
934                 if ((ost_idx == LOV_QOS_EMPTY) ||
935                     !cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
936                         continue;
937
938                 /* Fail Check before osc_precreate() is called
939                    so we can only 'fail' single OSC. */
940                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
941                         continue;
942
943                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
944                 if (rc) {
945                         /* this OSP doesn't feel well */
946                         continue;
947                 }
948
949                 /*
950                  * skip full devices
951                  */
952                 if (lod_qos_dev_is_full(sfs)) {
953                         QOS_DEBUG("#%d is full\n", ost_idx);
954                         continue;
955                 }
956
957                 /*
958                  * We expect number of precreated objects in f_ffree at
959                  * the first iteration, skip OSPs with no objects ready
960                  */
961                 if (sfs->os_fprecreated == 0 && speed == 0) {
962                         QOS_DEBUG("#%d: precreation is empty\n", ost_idx);
963                         continue;
964                 }
965
966                 /*
967                  * try to use another OSP if this one is degraded
968                  */
969                 if (sfs->os_state & OS_STATE_DEGRADED && speed < 2) {
970                         QOS_DEBUG("#%d: degraded\n", ost_idx);
971                         continue;
972                 }
973
974                 /*
975                  * do not put >1 objects on a single OST
976                  */
977                 if (speed && lod_qos_is_ost_used(env, ost_idx, stripe_idx))
978                         continue;
979
980                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
981                 if (IS_ERR(o)) {
982                         CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
983                                ost_idx, (int) PTR_ERR(o));
984                         rc = PTR_ERR(o);
985                         continue;
986                 }
987
988                 /*
989                  * We've successfuly declared (reserved) an object
990                  */
991                 lod_qos_ost_in_use(env, stripe_idx, ost_idx);
992                 stripe[stripe_idx] = o;
993                 stripe_idx++;
994
995         }
996         if ((speed < 2) && (stripe_idx < stripe_cnt_min)) {
997                 /* Try again, allowing slower OSCs */
998                 speed++;
999                 lqr->lqr_start_idx = ost_start_idx_temp;
1000                 goto repeat_find;
1001         }
1002
1003         up_read(&m->lod_qos.lq_rw_sem);
1004
1005         if (stripe_idx) {
1006                 lo->ldo_stripenr = stripe_idx;
1007                 /* at least one stripe is allocated */
1008                 rc = 0;
1009         } else {
1010                 /* nobody provided us with a single object */
1011                 rc = -ENOSPC;
1012         }
1013
1014 out:
1015         if (pool != NULL) {
1016                 up_read(&pool_tgt_rw_sem(pool));
1017                 /* put back ref got by lod_find_pool() */
1018                 lod_pool_putref(pool);
1019         }
1020
1021         RETURN(rc);
1022 }
1023
1024 /**
1025  * Allocate a specific striping layout on a user defined set of OSTs.
1026  *
1027  * Allocates new striping using the OST index range provided by the data from
1028  * the lmm_obejcts contained in the lov_user_md passed to this method. Full
1029  * OSTs are not considered. The exact order of OSTs requested by the user
1030  * is respected as much as possible depending on OST status. The number of
1031  * stripes needed and stripe offset are taken from the object. If that number
1032  * can not be met, then the function returns a failure and then it's the
1033  * caller's responsibility to release the stripes allocated. All the internal
1034  * structures are protected, but no concurrent allocation is allowed on the
1035  * same objects.
1036  *
1037  * \param[in] env       execution environment for this thread
1038  * \param[in] lo        LOD object
1039  * \param[out] stripe   striping created
1040  * \param[in] lum       stripe md to specify list of OSTs
1041  * \param[in] th        transaction handle
1042  *
1043  * \retval 0            on success
1044  * \retval -ENODEV      OST index does not exist on file system
1045  * \retval -EINVAL      requested OST index is invalid
1046  * \retval negative     negated errno on error
1047  */
1048 static int lod_alloc_ost_list(const struct lu_env *env,
1049                               struct lod_object *lo, struct dt_object **stripe,
1050                               struct lov_user_md *lum, struct thandle *th)
1051 {
1052         struct lod_device       *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1053         struct obd_statfs       *sfs = &lod_env_info(env)->lti_osfs;
1054         struct dt_object        *o;
1055         struct lov_user_md_v3   *v3;
1056         unsigned int            array_idx = 0;
1057         int                     stripe_count = 0;
1058         int                     i;
1059         int                     rc;
1060         ENTRY;
1061
1062         /* for specific OSTs layout */
1063         LASSERT(lum != NULL && lum->lmm_magic == LOV_USER_MAGIC_SPECIFIC);
1064         lustre_print_user_md(D_OTHER, lum, __func__);
1065
1066         rc = lod_qos_ost_in_use_clear(env, lo->ldo_stripenr);
1067         if (rc < 0)
1068                 RETURN(rc);
1069
1070         v3 = (struct lov_user_md_v3 *)lum;
1071         for (i = 0; i < lo->ldo_stripenr; i++) {
1072                 if (v3->lmm_objects[i].l_ost_idx == lo->ldo_def_stripe_offset) {
1073                         array_idx = i;
1074                         break;
1075                 }
1076         }
1077         if (i == lo->ldo_stripenr) {
1078                 CDEBUG(D_OTHER,
1079                        "%s: start index %d not in the specified list of OSTs\n",
1080                        lod2obd(m)->obd_name, lo->ldo_def_stripe_offset);
1081                 RETURN(-EINVAL);
1082         }
1083
1084         for (i = 0; i < lo->ldo_stripenr;
1085              i++, array_idx = (array_idx + 1) % lo->ldo_stripenr) {
1086                 __u32 ost_idx = v3->lmm_objects[array_idx].l_ost_idx;
1087
1088                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx)) {
1089                         rc = -ENODEV;
1090                         break;
1091                 }
1092
1093                 /*
1094                  * do not put >1 objects on a single OST
1095                  */
1096                 if (lod_qos_is_ost_used(env, ost_idx, stripe_count)) {
1097                         rc = -EINVAL;
1098                         break;
1099                 }
1100
1101                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
1102                 if (rc < 0) /* this OSP doesn't feel well */
1103                         break;
1104
1105                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1106                 if (IS_ERR(o)) {
1107                         rc = PTR_ERR(o);
1108                         CDEBUG(D_OTHER,
1109                                "%s: can't declare new object on #%u: %d\n",
1110                                lod2obd(m)->obd_name, ost_idx, rc);
1111                         break;
1112                 }
1113
1114                 /*
1115                  * We've successfuly declared (reserved) an object
1116                  */
1117                 lod_qos_ost_in_use(env, stripe_count, ost_idx);
1118                 stripe[stripe_count] = o;
1119                 stripe_count++;
1120         }
1121
1122         RETURN(rc);
1123 }
1124
1125 /**
1126  * Allocate a striping on a predefined set of OSTs.
1127  *
1128  * Allocates new striping starting from OST provided lo->ldo_def_stripe_offset.
1129  * Full OSTs are not considered. The exact order of OSTs is not important and
1130  * varies depending on OST status. The allocation procedure prefers the targets
1131  * with precreated objects ready. The number of stripes needed and stripe
1132  * offset are taken from the object. If that number can not be met, then the
1133  * function returns a failure and then it's the caller's responsibility to
1134  * release the stripes allocated. All the internal structures are protected,
1135  * but no concurrent allocation is allowed on the same objects.
1136  *
1137  * \param[in] env       execution environment for this thread
1138  * \param[in] lo        LOD object
1139  * \param[out] stripe   striping created
1140  * \param[in] flags     not used
1141  * \param[in] th        transaction handle
1142  *
1143  * \retval 0            on success
1144  * \retval -E2BIG       if no enough OSTs are found
1145  * \retval -EINVAL      requested offset is invalid
1146  * \retval negative     negated errno on error
1147  */
1148 static int lod_alloc_specific(const struct lu_env *env, struct lod_object *lo,
1149                               struct dt_object **stripe, int flags,
1150                               struct thandle *th)
1151 {
1152         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1153         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
1154         struct dt_object  *o;
1155         __u32              ost_idx;
1156         unsigned int       i, array_idx, ost_count;
1157         int                rc, stripe_num = 0;
1158         int                speed = 0;
1159         struct pool_desc  *pool = NULL;
1160         struct ost_pool   *osts;
1161         ENTRY;
1162
1163         rc = lod_qos_ost_in_use_clear(env, lo->ldo_stripenr);
1164         if (rc)
1165                 GOTO(out, rc);
1166
1167         if (lo->ldo_pool)
1168                 pool = lod_find_pool(m, lo->ldo_pool);
1169
1170         if (pool != NULL) {
1171                 down_read(&pool_tgt_rw_sem(pool));
1172                 osts = &(pool->pool_obds);
1173         } else {
1174                 osts = &(m->lod_pool_info);
1175         }
1176
1177         ost_count = osts->op_count;
1178
1179 repeat_find:
1180         /* search loi_ost_idx in ost array */
1181         array_idx = 0;
1182         for (i = 0; i < ost_count; i++) {
1183                 if (osts->op_array[i] == lo->ldo_def_stripe_offset) {
1184                         array_idx = i;
1185                         break;
1186                 }
1187         }
1188         if (i == ost_count) {
1189                 CERROR("Start index %d not found in pool '%s'\n",
1190                        lo->ldo_def_stripe_offset,
1191                        lo->ldo_pool ? lo->ldo_pool : "");
1192                 GOTO(out, rc = -EINVAL);
1193         }
1194
1195         for (i = 0; i < ost_count;
1196                         i++, array_idx = (array_idx + 1) % ost_count) {
1197                 ost_idx = osts->op_array[array_idx];
1198
1199                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
1200                         continue;
1201
1202                 /* Fail Check before osc_precreate() is called
1203                    so we can only 'fail' single OSC. */
1204                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1205                         continue;
1206
1207                 /*
1208                  * do not put >1 objects on a single OST
1209                  */
1210                 if (lod_qos_is_ost_used(env, ost_idx, stripe_num))
1211                         continue;
1212
1213                 /* Drop slow OSCs if we can, but not for requested start idx.
1214                  *
1215                  * This means "if OSC is slow and it is not the requested
1216                  * start OST, then it can be skipped, otherwise skip it only
1217                  * if it is inactive/recovering/out-of-space." */
1218
1219                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
1220                 if (rc) {
1221                         /* this OSP doesn't feel well */
1222                         continue;
1223                 }
1224
1225                 /*
1226                  * We expect number of precreated objects in f_ffree at
1227                  * the first iteration, skip OSPs with no objects ready
1228                  * don't apply this logic to OST specified with stripe_offset
1229                  */
1230                 if (i != 0 && sfs->os_fprecreated == 0 && speed == 0)
1231                         continue;
1232
1233                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1234                 if (IS_ERR(o)) {
1235                         CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
1236                                ost_idx, (int) PTR_ERR(o));
1237                         continue;
1238                 }
1239
1240                 /*
1241                  * We've successfuly declared (reserved) an object
1242                  */
1243                 lod_qos_ost_in_use(env, stripe_num, ost_idx);
1244                 stripe[stripe_num] = o;
1245                 stripe_num++;
1246
1247                 /* We have enough stripes */
1248                 if (stripe_num == lo->ldo_stripenr)
1249                         GOTO(out, rc = 0);
1250         }
1251         if (speed < 2) {
1252                 /* Try again, allowing slower OSCs */
1253                 speed++;
1254                 goto repeat_find;
1255         }
1256
1257         /* If we were passed specific striping params, then a failure to
1258          * meet those requirements is an error, since we can't reallocate
1259          * that memory (it might be part of a larger array or something).
1260          *
1261          * We can only get here if lsm_stripe_count was originally > 1.
1262          */
1263         CERROR("can't lstripe objid "DFID": have %d want %u\n",
1264                PFID(lu_object_fid(lod2lu_obj(lo))), stripe_num,
1265                lo->ldo_stripenr);
1266         rc = -EFBIG;
1267 out:
1268         if (pool != NULL) {
1269                 up_read(&pool_tgt_rw_sem(pool));
1270                 /* put back ref got by lod_find_pool() */
1271                 lod_pool_putref(pool);
1272         }
1273
1274         RETURN(rc);
1275 }
1276
1277 /**
1278  * Check whether QoS allocation should be used.
1279  *
1280  * A simple helper to decide when QoS allocation should be used:
1281  * if it's just a single available target or the used space is
1282  * evenly distributed among the targets at the moment, then QoS
1283  * allocation algorithm should not be used.
1284  *
1285  * \param[in] lod       LOD device
1286  *
1287  * \retval 0            should not be used
1288  * \retval 1            should be used
1289  */
1290 static inline int lod_qos_is_usable(struct lod_device *lod)
1291 {
1292 #ifdef FORCE_QOS
1293         /* to be able to debug QoS code */
1294         return 1;
1295 #endif
1296
1297         /* Detect -EAGAIN early, before expensive lock is taken. */
1298         if (!lod->lod_qos.lq_dirty && lod->lod_qos.lq_same_space)
1299                 return 0;
1300
1301         if (lod->lod_desc.ld_active_tgt_count < 2)
1302                 return 0;
1303
1304         return 1;
1305 }
1306
1307 /**
1308  * Allocate a striping using an algorithm with weights.
1309  *
1310  * The function allocates OST objects to create a striping. The algorithm
1311  * used is based on weights (currently only using the free space), and it's
1312  * trying to ensure the space is used evenly by OSTs and OSSs. The striping
1313  * configuration (# of stripes, offset,
1314  * pool) is taken from the object and is prepared by the caller.
1315  * If LOV_USES_DEFAULT_STRIPE is not passed and prepared configuration can't
1316  * be met due to too few OSTs, then allocation fails. If the flag is
1317  * passed and less than 75% of the requested number of stripes can be
1318  * allocated, then allocation fails.
1319  * No concurrent allocation is allowed on the object and this must be
1320  * ensured by the caller. All the internal structures are protected by the
1321  * function.
1322  * The algorithm has two steps: find available OSTs and calucate their weights,
1323  * then select the OSTs the weights used as the probability. An OST with a
1324  * higher weight is proportionately more likely to be selected than one with
1325  * a lower weight.
1326  *
1327  * \param[in] env       execution environment for this thread
1328  * \param[in] lo        LOD object
1329  * \param[out] stripe   striping created
1330  * \param[in] flags     0 or LOV_USES_DEFAULT_STRIPE
1331  * \param[in] th        transaction handle
1332  *
1333  * \retval 0            on success
1334  * \retval -E2BIG       if no enough OSTs are found
1335  * \retval -EINVAL      requested offset is invalid
1336  * \retval negative     negated errno on error
1337  */
1338 static int lod_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1339                          struct dt_object **stripe, int flags,
1340                          struct thandle *th)
1341 {
1342         struct lod_device   *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1343         struct obd_statfs   *sfs = &lod_env_info(env)->lti_osfs;
1344         struct lod_tgt_desc *ost;
1345         struct dt_object    *o;
1346         __u64                total_weight = 0;
1347         unsigned int         i;
1348         int                  rc = 0;
1349         __u32                nfound, good_osts;
1350         __u32                stripe_cnt = lo->ldo_stripenr;
1351         __u32                stripe_cnt_min;
1352         struct pool_desc    *pool = NULL;
1353         struct ost_pool    *osts;
1354         ENTRY;
1355
1356         stripe_cnt_min = min_stripe_count(stripe_cnt, flags);
1357         if (stripe_cnt_min < 1)
1358                 RETURN(-EINVAL);
1359
1360         if (lo->ldo_pool)
1361                 pool = lod_find_pool(m, lo->ldo_pool);
1362
1363         if (pool != NULL) {
1364                 down_read(&pool_tgt_rw_sem(pool));
1365                 osts = &(pool->pool_obds);
1366         } else {
1367                 osts = &(m->lod_pool_info);
1368         }
1369
1370         /* Detect -EAGAIN early, before expensive lock is taken. */
1371         if (!lod_qos_is_usable(m))
1372                 GOTO(out_nolock, rc = -EAGAIN);
1373
1374         /* Do actual allocation, use write lock here. */
1375         down_write(&m->lod_qos.lq_rw_sem);
1376
1377         /*
1378          * Check again, while we were sleeping on @lq_rw_sem things could
1379          * change.
1380          */
1381         if (!lod_qos_is_usable(m))
1382                 GOTO(out, rc = -EAGAIN);
1383
1384         rc = lod_qos_calc_ppo(m);
1385         if (rc)
1386                 GOTO(out, rc);
1387
1388         rc = lod_qos_ost_in_use_clear(env, lo->ldo_stripenr);
1389         if (rc)
1390                 GOTO(out, rc);
1391
1392         good_osts = 0;
1393         /* Find all the OSTs that are valid stripe candidates */
1394         for (i = 0; i < osts->op_count; i++) {
1395                 if (!cfs_bitmap_check(m->lod_ost_bitmap, osts->op_array[i]))
1396                         continue;
1397
1398                 rc = lod_statfs_and_check(env, m, osts->op_array[i], sfs);
1399                 if (rc) {
1400                         /* this OSP doesn't feel well */
1401                         continue;
1402                 }
1403
1404                 /*
1405                  * skip full devices
1406                  */
1407                 if (lod_qos_dev_is_full(sfs))
1408                         continue;
1409
1410                 /* Fail Check before osc_precreate() is called
1411                    so we can only 'fail' single OSC. */
1412                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) &&
1413                                    osts->op_array[i] == 0)
1414                         continue;
1415
1416                 ost = OST_TGT(m,osts->op_array[i]);
1417                 ost->ltd_qos.ltq_usable = 1;
1418                 lod_qos_calc_weight(m, osts->op_array[i]);
1419                 total_weight += ost->ltd_qos.ltq_weight;
1420
1421                 good_osts++;
1422         }
1423
1424         QOS_DEBUG("found %d good osts\n", good_osts);
1425
1426         if (good_osts < stripe_cnt_min)
1427                 GOTO(out, rc = -EAGAIN);
1428
1429         /* We have enough osts */
1430         if (good_osts < stripe_cnt)
1431                 stripe_cnt = good_osts;
1432
1433         /* Find enough OSTs with weighted random allocation. */
1434         nfound = 0;
1435         while (nfound < stripe_cnt) {
1436                 __u64 rand, cur_weight;
1437
1438                 cur_weight = 0;
1439                 rc = -ENOSPC;
1440
1441                 if (total_weight) {
1442 #if BITS_PER_LONG == 32
1443                         rand = cfs_rand() % (unsigned)total_weight;
1444                         /* If total_weight > 32-bit, first generate the high
1445                          * 32 bits of the random number, then add in the low
1446                          * 32 bits (truncated to the upper limit, if needed) */
1447                         if (total_weight > 0xffffffffULL)
1448                                 rand = (__u64)(cfs_rand() %
1449                                         (unsigned)(total_weight >> 32)) << 32;
1450                         else
1451                                 rand = 0;
1452
1453                         if (rand == (total_weight & 0xffffffff00000000ULL))
1454                                 rand |= cfs_rand() % (unsigned)total_weight;
1455                         else
1456                                 rand |= cfs_rand();
1457
1458 #else
1459                         rand = ((__u64)cfs_rand() << 32 | cfs_rand()) %
1460                                 total_weight;
1461 #endif
1462                 } else {
1463                         rand = 0;
1464                 }
1465
1466                 /* On average, this will hit larger-weighted osts more often.
1467                    0-weight osts will always get used last (only when rand=0) */
1468                 for (i = 0; i < osts->op_count; i++) {
1469                         __u32 idx = osts->op_array[i];
1470
1471                         if (!cfs_bitmap_check(m->lod_ost_bitmap, idx))
1472                                 continue;
1473
1474                         ost = OST_TGT(m,idx);
1475
1476                         if (!ost->ltd_qos.ltq_usable)
1477                                 continue;
1478
1479                         cur_weight += ost->ltd_qos.ltq_weight;
1480                         QOS_DEBUG("stripe_cnt=%d nfound=%d cur_weight="LPU64
1481                                   " rand="LPU64" total_weight="LPU64"\n",
1482                                   stripe_cnt, nfound, cur_weight, rand,
1483                                   total_weight);
1484
1485                         if (cur_weight < rand)
1486                                 continue;
1487
1488                         QOS_DEBUG("stripe=%d to idx=%d\n", nfound, idx);
1489
1490                         /*
1491                          * do not put >1 objects on a single OST
1492                          */
1493                         if (lod_qos_is_ost_used(env, idx, nfound))
1494                                 continue;
1495                         lod_qos_ost_in_use(env, nfound, idx);
1496
1497                         o = lod_qos_declare_object_on(env, m, idx, th);
1498                         if (IS_ERR(o)) {
1499                                 QOS_DEBUG("can't declare object on #%u: %d\n",
1500                                           idx, (int) PTR_ERR(o));
1501                                 continue;
1502                         }
1503                         stripe[nfound++] = o;
1504                         lod_qos_used(m, osts, idx, &total_weight);
1505                         rc = 0;
1506                         break;
1507                 }
1508
1509                 if (rc) {
1510                         /* no OST found on this iteration, give up */
1511                         break;
1512                 }
1513         }
1514
1515         if (unlikely(nfound != stripe_cnt)) {
1516                 /*
1517                  * when the decision to use weighted algorithm was made
1518                  * we had enough appropriate OSPs, but this state can
1519                  * change anytime (no space on OST, broken connection, etc)
1520                  * so it's possible OSP won't be able to provide us with
1521                  * an object due to just changed state
1522                  */
1523                 LCONSOLE_INFO("wanted %d, found %d\n", stripe_cnt, nfound);
1524                 for (i = 0; i < nfound; i++) {
1525                         LASSERT(stripe[i] != NULL);
1526                         lu_object_put(env, &stripe[i]->do_lu);
1527                         stripe[i] = NULL;
1528                 }
1529
1530                 /* makes sense to rebalance next time */
1531                 m->lod_qos.lq_dirty = 1;
1532                 m->lod_qos.lq_same_space = 0;
1533
1534                 rc = -EAGAIN;
1535         }
1536
1537 out:
1538         up_write(&m->lod_qos.lq_rw_sem);
1539
1540 out_nolock:
1541         if (pool != NULL) {
1542                 up_read(&pool_tgt_rw_sem(pool));
1543                 /* put back ref got by lod_find_pool() */
1544                 lod_pool_putref(pool);
1545         }
1546
1547         RETURN(rc);
1548 }
1549
1550 /**
1551  * Find largest stripe count the caller can use.
1552  *
1553  * Find the maximal possible stripe count not greater than \a stripe_count.
1554  * Sometimes suggested stripecount can't be reached for a number of reasons:
1555  * lack of enough active OSTs or the backend does not support EAs that large.
1556  * If the passed one is 0, then the filesystem's default one is used.
1557  *
1558  * \param[in] lod       LOD device
1559  * \param[in] magic     the format if striping
1560  * \param[in] stripe_count      count the caller would like to use
1561  *
1562  * \retval              the maximum usable stripe count
1563  */
1564 static __u16 lod_get_stripecnt(struct lod_device *lod, __u32 magic,
1565                                __u16 stripe_count)
1566 {
1567         __u32 max_stripes = LOV_MAX_STRIPE_COUNT_OLD;
1568
1569         if (!stripe_count)
1570                 stripe_count = lod->lod_desc.ld_default_stripe_count;
1571         if (stripe_count > lod->lod_desc.ld_active_tgt_count)
1572                 stripe_count = lod->lod_desc.ld_active_tgt_count;
1573         if (!stripe_count)
1574                 stripe_count = 1;
1575
1576         /* stripe count is based on whether OSD can handle larger EA sizes */
1577         if (lod->lod_osd_max_easize > 0)
1578                 max_stripes = lov_mds_md_max_stripe_count(
1579                         lod->lod_osd_max_easize, magic);
1580
1581         return (stripe_count < max_stripes) ? stripe_count : max_stripes;
1582 }
1583
1584 /**
1585  * Create in-core respresentation for a fully-defined striping
1586  *
1587  * When the caller passes a fully-defined striping (i.e. everything including
1588  * OST object FIDs are defined), then we still need to instantiate LU-cache
1589  * with the objects representing the stripes defined. This function completes
1590  * that task.
1591  *
1592  * \param[in] env       execution environment for this thread
1593  * \param[in] mo        LOD object
1594  * \param[in] buf       buffer containing the striping
1595  *
1596  * \retval 0            on success
1597  * \retval negative     negated errno on error
1598  */
1599 static int lod_use_defined_striping(const struct lu_env *env,
1600                                     struct lod_object *mo,
1601                                     const struct lu_buf *buf)
1602 {
1603         struct lov_mds_md_v1   *v1 = buf->lb_buf;
1604         struct lov_mds_md_v3   *v3 = buf->lb_buf;
1605         struct lov_ost_data_v1 *objs;
1606         __u32                   magic;
1607         int                     rc = 0;
1608         ENTRY;
1609
1610         magic = le32_to_cpu(v1->lmm_magic);
1611         if (magic == LOV_MAGIC_V1_DEF) {
1612                 magic = LOV_MAGIC_V1;
1613                 objs = &v1->lmm_objects[0];
1614         } else if (magic == LOV_MAGIC_V3_DEF) {
1615                 magic = LOV_MAGIC_V3;
1616                 objs = &v3->lmm_objects[0];
1617                 lod_object_set_pool(mo, v3->lmm_pool_name);
1618         } else {
1619                 GOTO(out, rc = -EINVAL);
1620         }
1621
1622         mo->ldo_pattern = le32_to_cpu(v1->lmm_pattern);
1623         mo->ldo_stripe_size = le32_to_cpu(v1->lmm_stripe_size);
1624         mo->ldo_stripenr = le16_to_cpu(v1->lmm_stripe_count);
1625         mo->ldo_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
1626
1627         /* fixup for released file before object initialization */
1628         if (mo->ldo_pattern & LOV_PATTERN_F_RELEASED) {
1629                 mo->ldo_released_stripenr = mo->ldo_stripenr;
1630                 mo->ldo_stripenr = 0;
1631         }
1632
1633         LASSERT(buf->lb_len >= lov_mds_md_size(mo->ldo_stripenr, magic));
1634
1635         if (mo->ldo_stripenr > 0)
1636                 rc = lod_initialize_objects(env, mo, objs);
1637
1638 out:
1639         RETURN(rc);
1640 }
1641
1642 /**
1643  * Parse suggested striping configuration.
1644  *
1645  * The caller gets a suggested striping configuration from a number of sources
1646  * including per-directory default and applications. Then it needs to verify
1647  * the suggested striping is valid, apply missing bits and store the resulting
1648  * configuration in the object to be used by the allocator later. Must not be
1649  * called concurrently against the same object. It's OK to provide a
1650  * fully-defined striping.
1651  *
1652  * \param[in] env       execution environment for this thread
1653  * \param[in] lo        LOD object
1654  * \param[in] buf       buffer containing the striping
1655  *
1656  * \retval 0            on success
1657  * \retval negative     negated errno on error
1658  */
1659 static int lod_qos_parse_config(const struct lu_env *env,
1660                                 struct lod_object *lo,
1661                                 const struct lu_buf *buf)
1662 {
1663         struct lod_device     *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
1664         struct lov_user_md_v1 *v1 = NULL;
1665         struct lov_user_md_v3 *v3 = NULL;
1666         char                  *pool_name = NULL;
1667         __u32                  magic;
1668         int                    rc;
1669         unsigned int           size;
1670         ENTRY;
1671
1672         if (buf == NULL || buf->lb_buf == NULL || buf->lb_len == 0)
1673                 RETURN(0);
1674
1675         v3 = buf->lb_buf;
1676         v1 = buf->lb_buf;
1677         magic = v1->lmm_magic;
1678
1679         if (unlikely(magic == LOV_MAGIC_V1_DEF || magic == LOV_MAGIC_V3_DEF)) {
1680                 /* try to use as fully defined striping */
1681                 rc = lod_use_defined_striping(env, lo, buf);
1682                 RETURN(rc);
1683         }
1684
1685         switch (magic) {
1686         case __swab32(LOV_USER_MAGIC_V1):
1687                 lustre_swab_lov_user_md_v1(v1);
1688                 magic = v1->lmm_magic;
1689                 /* fall through */
1690         case LOV_USER_MAGIC_V1:
1691                 size = sizeof(*v1);
1692                 break;
1693
1694         case __swab32(LOV_USER_MAGIC_V3):
1695                 lustre_swab_lov_user_md_v3(v3);
1696                 magic = v3->lmm_magic;
1697                 /* fall through */
1698         case LOV_USER_MAGIC_V3:
1699                 size = sizeof(*v3);
1700                 pool_name = v3->lmm_pool_name;
1701                 break;
1702
1703         case __swab32(LOV_USER_MAGIC_SPECIFIC):
1704                 lustre_swab_lov_user_md_v3(v3);
1705                 lustre_swab_lov_user_md_objects(v3->lmm_objects,
1706                                                 v3->lmm_stripe_count);
1707                 magic = v3->lmm_magic;
1708                 /* fall through */
1709         case LOV_USER_MAGIC_SPECIFIC:
1710                 if (v3->lmm_stripe_offset == LOV_OFFSET_DEFAULT)
1711                         v3->lmm_stripe_offset = v3->lmm_objects[0].l_ost_idx;
1712                 if (v3->lmm_pool_name[0] != '\0')
1713                         pool_name = v3->lmm_pool_name;
1714                 size = lov_user_md_size(v3->lmm_stripe_count,
1715                                         LOV_USER_MAGIC_SPECIFIC);
1716                 break;
1717
1718         default:
1719                 CERROR("%s: unrecognized magic %X\n",
1720                        lod2obd(d)->obd_name, magic);
1721                 RETURN(-EINVAL);
1722         }
1723
1724         if (unlikely(buf->lb_len < size)) {
1725                 CERROR("%s: wrong size: %zd, expect: %u\n",
1726                        lod2obd(d)->obd_name, buf->lb_len, size);
1727                 RETURN(-EINVAL);
1728         }
1729
1730         lustre_print_user_md(D_OTHER, v1, "parse config");
1731
1732         v1->lmm_magic = magic;
1733         if (v1->lmm_pattern == 0)
1734                 v1->lmm_pattern = LOV_PATTERN_RAID0;
1735         if (lov_pattern(v1->lmm_pattern) != LOV_PATTERN_RAID0) {
1736                 CERROR("%s: invalid pattern: %x\n",
1737                        lod2obd(d)->obd_name, v1->lmm_pattern);
1738                 RETURN(-EINVAL);
1739         }
1740         lo->ldo_pattern = v1->lmm_pattern;
1741
1742         if (v1->lmm_stripe_size > 0)
1743                 lo->ldo_stripe_size = v1->lmm_stripe_size;
1744
1745         if (lo->ldo_stripe_size & (LOV_MIN_STRIPE_SIZE - 1))
1746                 lo->ldo_stripe_size = LOV_MIN_STRIPE_SIZE;
1747
1748         if (v1->lmm_stripe_count > 0)
1749                 lo->ldo_stripenr = v1->lmm_stripe_count;
1750
1751         lo->ldo_def_stripe_offset = v1->lmm_stripe_offset;
1752
1753         lod_object_set_pool(lo, NULL);
1754         if (pool_name != NULL) {
1755                 struct pool_desc *pool;
1756
1757                 /* In the function below, .hs_keycmp resolves to
1758                  * pool_hashkey_keycmp() */
1759                 /* coverity[overrun-buffer-val] */
1760                 pool = lod_find_pool(d, pool_name);
1761                 if (pool != NULL) {
1762                         if (lo->ldo_def_stripe_offset != LOV_OFFSET_DEFAULT) {
1763                                 rc = lod_check_index_in_pool(
1764                                                lo->ldo_def_stripe_offset, pool);
1765                                 if (rc < 0) {
1766                                         lod_pool_putref(pool);
1767                                         CERROR("%s: invalid offset, %u\n",
1768                                                lod2obd(d)->obd_name,
1769                                                lo->ldo_def_stripe_offset);
1770                                         RETURN(-EINVAL);
1771                                 }
1772                         }
1773
1774                         if (lo->ldo_stripenr > pool_tgt_count(pool))
1775                                 lo->ldo_stripenr = pool_tgt_count(pool);
1776
1777                         lod_pool_putref(pool);
1778                 }
1779
1780                 lod_object_set_pool(lo, pool_name);
1781         }
1782
1783         /* fixup for released file */
1784         if (lo->ldo_pattern & LOV_PATTERN_F_RELEASED) {
1785                 lo->ldo_released_stripenr = lo->ldo_stripenr;
1786                 lo->ldo_stripenr = 0;
1787         }
1788
1789         RETURN(0);
1790 }
1791
1792 /**
1793  * Create a striping for an obejct.
1794  *
1795  * The function creates a new striping for the object. A buffer containing
1796  * configuration hints can be provided optionally. The function tries QoS
1797  * algorithm first unless free space is distributed evenly among OSTs, but
1798  * by default RR algorithm is preferred due to internal concurrency (QoS is
1799  * serialized). The caller must ensure no concurrent calls to the function
1800  * are made against the same object.
1801  *
1802  * \param[in] env       execution environment for this thread
1803  * \param[in] lo        LOD object
1804  * \param[in] attr      attributes OST objects will be declared with
1805  * \param[in] buf       suggested striping configuration or NULL
1806  * \param[in] th        transaction handle
1807  *
1808  * \retval 0            on success
1809  * \retval negative     negated errno on error
1810  */
1811 int lod_qos_prep_create(const struct lu_env *env, struct lod_object *lo,
1812                         struct lu_attr *attr, const struct lu_buf *buf,
1813                         struct thandle *th)
1814 {
1815         struct lod_device      *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
1816         struct dt_object      **stripe;
1817         int                     stripe_len;
1818         int                     flag = LOV_USES_ASSIGNED_STRIPE;
1819         int                     i, rc;
1820         ENTRY;
1821
1822         LASSERT(lo);
1823
1824         /* no OST available */
1825         /* XXX: should we be waiting a bit to prevent failures during
1826          * cluster initialization? */
1827         if (d->lod_ostnr == 0)
1828                 GOTO(out, rc = -EIO);
1829
1830         /*
1831          * by this time, the object's ldo_stripenr and ldo_stripe_size
1832          * contain default value for striping: taken from the parent
1833          * or from filesystem defaults
1834          *
1835          * in case the caller is passing lovea with new striping config,
1836          * we may need to parse lovea and apply new configuration
1837          */
1838         rc = lod_qos_parse_config(env, lo, buf);
1839         if (rc)
1840                 GOTO(out, rc);
1841
1842         /* A released file is being created */
1843         if (lo->ldo_stripenr == 0)
1844                 GOTO(out, rc = 0);
1845
1846         if (likely(lo->ldo_stripe == NULL)) {
1847                 struct lov_user_md *lum = NULL;
1848
1849                 /*
1850                  * no striping has been created so far
1851                  */
1852                 LASSERT(lo->ldo_stripenr > 0);
1853                 /*
1854                  * statfs and check OST targets now, since ld_active_tgt_count
1855                  * could be changed if some OSTs are [de]activated manually.
1856                  */
1857                 lod_qos_statfs_update(env, d);
1858                 lo->ldo_stripenr = lod_get_stripecnt(d, LOV_MAGIC,
1859                                                      lo->ldo_stripenr);
1860
1861                 stripe_len = lo->ldo_stripenr;
1862                 OBD_ALLOC(stripe, sizeof(stripe[0]) * stripe_len);
1863                 if (stripe == NULL)
1864                         GOTO(out, rc = -ENOMEM);
1865
1866                 lod_getref(&d->lod_ost_descs);
1867                 /* XXX: support for non-0 files w/o objects */
1868                 CDEBUG(D_OTHER, "tgt_count %d stripenr %d\n",
1869                                 d->lod_desc.ld_tgt_count, stripe_len);
1870
1871                 if (buf != NULL && buf->lb_buf != NULL)
1872                         lum = buf->lb_buf;
1873
1874                 if (lum != NULL && lum->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
1875                         rc = lod_alloc_ost_list(env, lo, stripe, lum, th);
1876                 } else if (lo->ldo_def_stripe_offset == LOV_OFFSET_DEFAULT) {
1877                         rc = lod_alloc_qos(env, lo, stripe, flag, th);
1878                         if (rc == -EAGAIN)
1879                                 rc = lod_alloc_rr(env, lo, stripe, flag, th);
1880                 } else {
1881                         rc = lod_alloc_specific(env, lo, stripe, flag, th);
1882                 }
1883                 lod_putref(d, &d->lod_ost_descs);
1884
1885                 if (rc < 0) {
1886                         for (i = 0; i < stripe_len; i++)
1887                                 if (stripe[i] != NULL)
1888                                         lu_object_put(env, &stripe[i]->do_lu);
1889
1890                         OBD_FREE(stripe, sizeof(stripe[0]) * stripe_len);
1891                         lo->ldo_stripenr = 0;
1892                 } else {
1893                         lo->ldo_stripe = stripe;
1894                         lo->ldo_stripes_allocated = stripe_len;
1895                 }
1896         } else {
1897                 /*
1898                  * lod_qos_parse_config() found supplied buf as a predefined
1899                  * striping (not a hint), so it allocated all the object
1900                  * now we need to create them
1901                  */
1902                 for (i = 0; i < lo->ldo_stripenr; i++) {
1903                         struct dt_object  *o;
1904
1905                         o = lo->ldo_stripe[i];
1906                         LASSERT(o);
1907
1908                         rc = dt_declare_create(env, o, attr, NULL, NULL, th);
1909                         if (rc) {
1910                                 CERROR("can't declare create: %d\n", rc);
1911                                 break;
1912                         }
1913                 }
1914         }
1915
1916 out:
1917         RETURN(rc);
1918 }
1919