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