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