Whamcloud - gitweb
LU-3834 mdt: handle swap_layouts failures during restore
[fs/lustre-release.git] / lustre / mdt / mdt_coordinator.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 (c) 2012, 2013, Intel Corporation.
24  * Use is subject to license terms.
25  * Copyright (c) 2011, 2012 Commissariat a l'energie atomique et aux energies
26  *                          alternatives
27  */
28 /*
29  * lustre/mdt/mdt_coordinator.c
30  *
31  * Lustre HSM Coordinator
32  *
33  * Author: Jacques-Charles Lafoucriere <jacques-charles.lafoucriere@cea.fr>
34  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
35  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
36  */
37
38 #define DEBUG_SUBSYSTEM S_MDS
39
40 #include <obd_support.h>
41 #include <lustre_net.h>
42 #include <lustre_export.h>
43 #include <obd.h>
44 #include <obd_lov.h>
45 #include <lprocfs_status.h>
46 #include <lustre_log.h>
47 #include "mdt_internal.h"
48
49 static struct lprocfs_vars lprocfs_mdt_hsm_vars[];
50
51 /**
52  * get obj and HSM attributes on a fid
53  * \param mti [IN] context
54  * \param fid [IN] object fid
55  * \param hsm [OUT] HSM meta data
56  * \retval obj or error (-ENOENT if not found)
57  */
58 struct mdt_object *mdt_hsm_get_md_hsm(struct mdt_thread_info *mti,
59                                       const struct lu_fid *fid,
60                                       struct md_hsm *hsm)
61 {
62         struct md_attr          *ma;
63         struct mdt_object       *obj;
64         int                      rc;
65         ENTRY;
66
67         ma = &mti->mti_attr;
68         ma->ma_need = MA_HSM;
69         ma->ma_valid = 0;
70
71         /* find object by FID */
72         obj = mdt_object_find(mti->mti_env, mti->mti_mdt, fid);
73         if (IS_ERR(obj))
74                 RETURN(obj);
75
76         if (!mdt_object_exists(obj)) {
77                 /* no more object */
78                 mdt_object_put(mti->mti_env, obj);
79                 RETURN(ERR_PTR(-ENOENT));
80         }
81
82         rc = mdt_attr_get_complex(mti, obj, ma);
83         if (rc) {
84                 mdt_object_put(mti->mti_env, obj);
85                 RETURN(ERR_PTR(rc));
86         }
87
88         if (ma->ma_valid & MA_HSM)
89                 *hsm = ma->ma_hsm;
90         else
91                 memset(hsm, 0, sizeof(*hsm));
92         ma->ma_valid = 0;
93         RETURN(obj);
94 }
95
96 void mdt_hsm_dump_hal(int level, const char *prefix,
97                       struct hsm_action_list *hal)
98 {
99         int                      i, sz;
100         struct hsm_action_item  *hai;
101         char                     buf[12];
102
103         CDEBUG(level, "%s: HAL header: version %X count %d compound "LPX64
104                       " archive_id %d flags "LPX64"\n",
105                prefix, hal->hal_version, hal->hal_count,
106                hal->hal_compound_id, hal->hal_archive_id, hal->hal_flags);
107
108         hai = hai_first(hal);
109         for (i = 0; i < hal->hal_count; i++) {
110                 sz = hai->hai_len - sizeof(*hai);
111                 CDEBUG(level, "%s %d: fid="DFID" dfid="DFID
112                        " compound/cookie="LPX64"/"LPX64
113                        " action=%s extent="LPX64"-"LPX64" gid="LPX64
114                        " datalen=%d data=[%s]\n",
115                        prefix, i,
116                        PFID(&hai->hai_fid), PFID(&hai->hai_dfid),
117                        hal->hal_compound_id, hai->hai_cookie,
118                        hsm_copytool_action2name(hai->hai_action),
119                        hai->hai_extent.offset,
120                        hai->hai_extent.length,
121                        hai->hai_gid, sz,
122                        hai_dump_data_field(hai, buf, sizeof(buf)));
123                 hai = hai_next(hai);
124         }
125 }
126
127 /**
128  * data passed to llog_cat_process() callback
129  * to scan requests and take actions
130  */
131 struct hsm_scan_data {
132         struct mdt_thread_info          *mti;
133         char                             fs_name[MTI_NAME_MAXLEN+1];
134         /* request to be send to agents */
135         int                              request_sz;    /** allocated size */
136         int                              max_requests;  /** vector size */
137         int                              request_cnt;   /** used count */
138         struct {
139                 int                      hal_sz;
140                 int                      hal_used_sz;
141                 struct hsm_action_list  *hal;
142         } *request;
143         /* records to be canceled */
144         int                              max_cookie;    /** vector size */
145         int                              cookie_cnt;    /** used count */
146         __u64                           *cookies;
147 };
148
149 /**
150  *  llog_cat_process() callback, used to:
151  *  - find waiting request and start action
152  *  - purge canceled and done requests
153  * \param env [IN] environment
154  * \param llh [IN] llog handle
155  * \param hdr [IN] llog record
156  * \param data [IN/OUT] cb data = struct hsm_scan_data
157  * \retval 0 success
158  * \retval -ve failure
159  */
160 static int mdt_coordinator_cb(const struct lu_env *env,
161                               struct llog_handle *llh,
162                               struct llog_rec_hdr *hdr,
163                               void *data)
164 {
165         const struct llog_agent_req_rec *larr;
166         struct hsm_scan_data            *hsd;
167         struct hsm_action_item          *hai;
168         struct mdt_device               *mdt;
169         struct coordinator              *cdt;
170         int                              rc;
171         ENTRY;
172
173         hsd = data;
174         mdt = hsd->mti->mti_mdt;
175         cdt = &mdt->mdt_coordinator;
176
177         larr = (struct llog_agent_req_rec *)hdr;
178         dump_llog_agent_req_rec("mdt_coordinator_cb(): ", larr);
179         switch (larr->arr_status) {
180         case ARS_WAITING: {
181                 int i, empty_slot, found;
182
183                 /* Are agents full? */
184                 if (atomic_read(&cdt->cdt_request_count) ==
185                     cdt->cdt_max_requests)
186                         break;
187
188                 /* first search if the request if known in the list we have
189                  * build and if there is room in the request vector */
190                 empty_slot = -1;
191                 found = -1;
192                 for (i = 0; i < hsd->max_requests &&
193                             (empty_slot == -1 || found == -1); i++) {
194                         if (hsd->request[i].hal == NULL) {
195                                 empty_slot = i;
196                                 continue;
197                         }
198                         if (hsd->request[i].hal->hal_compound_id ==
199                                 larr->arr_compound_id) {
200                                 found = i;
201                                 continue;
202                         }
203                 }
204                 if (found == -1 && empty_slot == -1)
205                         /* unknown request and no more room for new request,
206                          * continue scan for to find other entries for
207                          * already found request
208                          */
209                         RETURN(0);
210
211                 if (found == -1) {
212                         struct hsm_action_list *hal;
213
214                         /* request is not already known */
215                         /* allocates hai vector size just needs to be large
216                          * enough */
217                         hsd->request[empty_slot].hal_sz =
218                                      sizeof(*hsd->request[empty_slot].hal) +
219                                      cfs_size_round(MTI_NAME_MAXLEN+1) +
220                                      2 * cfs_size_round(larr->arr_hai.hai_len);
221                         OBD_ALLOC(hal, hsd->request[empty_slot].hal_sz);
222                         if (!hal) {
223                                 CERROR("%s: Cannot allocate memory (%d o)"
224                                        "for compound "LPX64"\n",
225                                        mdt_obd_name(mdt),
226                                        hsd->request[i].hal_sz,
227                                        larr->arr_compound_id);
228                                 RETURN(-ENOMEM);
229                         }
230                         hal->hal_version = HAL_VERSION;
231                         strncpy(hal->hal_fsname, hsd->fs_name,
232                                 MTI_NAME_MAXLEN);
233                         hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
234                         hal->hal_compound_id = larr->arr_compound_id;
235                         hal->hal_archive_id = larr->arr_archive_id;
236                         hal->hal_flags = larr->arr_flags;
237                         hal->hal_count = 0;
238                         hsd->request[empty_slot].hal_used_sz = hal_size(hal);
239                         hsd->request[empty_slot].hal = hal;
240                         hsd->request_cnt++;
241                         found = empty_slot;
242                         hai = hai_first(hal);
243                 } else {
244                         /* request is known */
245                         /* we check if record archive num is the same as the
246                          * known request, if not we will serve it in multiple
247                          * time because we do not know if the agent can serve
248                          * multiple backend
249                          * a use case is a compound made of multiple restore
250                          * where the files are not archived in the same backend
251                          */
252                         if (larr->arr_archive_id !=
253                             hsd->request[found].hal->hal_archive_id)
254                                 RETURN(0);
255
256                         if (hsd->request[found].hal_sz <
257                             hsd->request[found].hal_used_sz +
258                              cfs_size_round(larr->arr_hai.hai_len)) {
259                                 /* Not enough room, need an extension */
260                                 void *hal_buffer;
261                                 int sz;
262
263                                 sz = 2 * hsd->request[found].hal_sz;
264                                 OBD_ALLOC(hal_buffer, sz);
265                                 if (!hal_buffer) {
266                                         CERROR("%s: Cannot allocate memory "
267                                                "(%d o) for compound "LPX64"\n",
268                                                mdt_obd_name(mdt), sz,
269                                                larr->arr_compound_id);
270                                         RETURN(-ENOMEM);
271                                 }
272                                 memcpy(hal_buffer, hsd->request[found].hal,
273                                        hsd->request[found].hal_used_sz);
274                                 OBD_FREE(hsd->request[found].hal,
275                                          hsd->request[found].hal_sz);
276                                 hsd->request[found].hal = hal_buffer;
277                                 hsd->request[found].hal_sz = sz;
278                         }
279                         hai = hai_first(hsd->request[found].hal);
280                         for (i = 0; i < hsd->request[found].hal->hal_count;
281                              i++)
282                                 hai = hai_next(hai);
283                 }
284                 memcpy(hai, &larr->arr_hai, larr->arr_hai.hai_len);
285                 hai->hai_cookie = larr->arr_hai.hai_cookie;
286                 hai->hai_gid = larr->arr_hai.hai_gid;
287
288                 hsd->request[found].hal_used_sz +=
289                                                    cfs_size_round(hai->hai_len);
290                 hsd->request[found].hal->hal_count++;
291                 break;
292         }
293         case ARS_STARTED: {
294                 struct cdt_agent_req *car;
295                 cfs_time_t last;
296
297                 /* we search for a running request
298                  * error may happen if coordinator crashes or stopped
299                  * with running request
300                  */
301                 car = mdt_cdt_find_request(cdt, larr->arr_hai.hai_cookie, NULL);
302                 if (car == NULL) {
303                         last = larr->arr_req_create;
304                 } else {
305                         last = car->car_req_update;
306                         mdt_cdt_put_request(car);
307                 }
308
309                 /* test if request too long, if yes cancel it
310                  * the same way the copy tool acknowledge a cancel request */
311                 if ((last + cdt->cdt_active_req_timeout)
312                      < cfs_time_current_sec()) {
313                         struct hsm_progress_kernel pgs;
314
315                         dump_llog_agent_req_rec("mdt_coordinator_cb(): "
316                                                 "request timeouted, start "
317                                                 "cleaning", larr);
318                         /* a too old cancel request just needs to be removed
319                          * this can happen, if copy tool does not support cancel
320                          * for other requests, we have to remove the running
321                          * request and notify the copytool
322                          */
323                         pgs.hpk_fid = larr->arr_hai.hai_fid;
324                         pgs.hpk_cookie = larr->arr_hai.hai_cookie;
325                         pgs.hpk_extent = larr->arr_hai.hai_extent;
326                         pgs.hpk_flags = HP_FLAG_COMPLETED;
327                         pgs.hpk_errval = ENOSYS;
328                         pgs.hpk_data_version = 0;
329                         /* update request state, but do not record in llog, to
330                          * avoid deadlock on cdt_llog_lock
331                          */
332                         rc = mdt_hsm_update_request_state(hsd->mti, &pgs, 0);
333                         if (rc)
334                                 CERROR("%s: Cannot cleanup timeouted request: "
335                                        DFID" for cookie "LPX64" action=%s\n",
336                                        mdt_obd_name(mdt),
337                                        PFID(&pgs.hpk_fid), pgs.hpk_cookie,
338                                        hsm_copytool_action2name(
339                                                      larr->arr_hai.hai_action));
340
341                         /* add the cookie to the list of record to be
342                          * canceled by caller */
343                         if (hsd->max_cookie == (hsd->cookie_cnt - 1)) {
344                                 __u64 *ptr, *old_ptr;
345                                 int old_sz, new_sz, new_cnt;
346
347                                 /* need to increase vector size */
348                                 old_sz = sizeof(__u64) * hsd->max_cookie;
349                                 old_ptr = hsd->cookies;
350
351                                 new_cnt = 2 * hsd->max_cookie;
352                                 new_sz = sizeof(__u64) * new_cnt;
353
354                                 OBD_ALLOC(ptr, new_sz);
355                                 if (!ptr) {
356                                         CERROR("%s: Cannot allocate memory "
357                                                "(%d o) for cookie vector\n",
358                                                mdt_obd_name(mdt), new_sz);
359                                         RETURN(-ENOMEM);
360                                 }
361                                 memcpy(ptr, hsd->cookies, old_sz);
362                                 hsd->cookies = ptr;
363                                 hsd->max_cookie = new_cnt;
364                                 OBD_FREE(old_ptr, old_sz);
365                         }
366                         hsd->cookies[hsd->cookie_cnt] =
367                                                        larr->arr_hai.hai_cookie;
368                         hsd->cookie_cnt++;
369                 }
370                 break;
371         }
372         case ARS_FAILED:
373         case ARS_CANCELED:
374         case ARS_SUCCEED:
375                 if ((larr->arr_req_change + cdt->cdt_grace_delay) <
376                     cfs_time_current_sec())
377                         RETURN(LLOG_DEL_RECORD);
378                 break;
379         }
380         RETURN(0);
381 }
382
383 /**
384  * create /proc entries for coordinator
385  * \param mdt [IN]
386  * \retval 0 success
387  * \retval -ve failure
388  */
389 int hsm_cdt_procfs_init(struct mdt_device *mdt)
390 {
391         struct coordinator      *cdt = &mdt->mdt_coordinator;
392         int                      rc = 0;
393         ENTRY;
394
395         /* init /proc entries, failure is not critical */
396         cdt->cdt_proc_dir = lprocfs_register("hsm",
397                                              mdt2obd_dev(mdt)->obd_proc_entry,
398                                              lprocfs_mdt_hsm_vars, mdt);
399         if (IS_ERR(cdt->cdt_proc_dir)) {
400                 rc = PTR_ERR(cdt->cdt_proc_dir);
401                 CERROR("%s: Cannot create 'hsm' directory in mdt proc dir,"
402                        " rc=%d\n", mdt_obd_name(mdt), rc);
403                 cdt->cdt_proc_dir = NULL;
404                 RETURN(rc);
405         }
406
407         RETURN(0);
408 }
409
410 /**
411  * remove /proc entries for coordinator
412  * \param mdt [IN]
413  */
414 void  hsm_cdt_procfs_fini(struct mdt_device *mdt)
415 {
416         struct coordinator      *cdt = &mdt->mdt_coordinator;
417
418         LASSERT(cdt->cdt_state == CDT_STOPPED);
419         if (cdt->cdt_proc_dir != NULL)
420                 lprocfs_remove(&cdt->cdt_proc_dir);
421 }
422
423 /**
424  * get vector of hsm cdt /proc vars
425  * \param none
426  * \retval var vector
427  */
428 struct lprocfs_vars *hsm_cdt_get_proc_vars(void)
429 {
430         return lprocfs_mdt_hsm_vars;
431 }
432
433 /**
434  * coordinator thread
435  * \param data [IN] obd device
436  * \retval 0 success
437  * \retval -ve failure
438  */
439 static int mdt_coordinator(void *data)
440 {
441         struct mdt_thread_info  *mti = data;
442         struct mdt_device       *mdt = mti->mti_mdt;
443         struct coordinator      *cdt = &mdt->mdt_coordinator;
444         struct hsm_scan_data     hsd = { 0 };
445         int                      rc = 0;
446         ENTRY;
447
448         cdt->cdt_thread.t_flags = SVC_RUNNING;
449         wake_up(&cdt->cdt_thread.t_ctl_waitq);
450
451         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
452                mdt_obd_name(mdt), current_pid());
453
454         /* timeouted cookie vector initialization */
455         hsd.max_cookie = 0;
456         hsd.cookie_cnt = 0;
457         hsd.cookies = NULL;
458         /* we use a copy of cdt_max_requests in the cb, so if cdt_max_requests
459          * increases due to a change from /proc we do not overflow the
460          * hsd.request[] vector
461          */
462         hsd.max_requests = cdt->cdt_max_requests;
463         hsd.request_sz = hsd.max_requests * sizeof(*hsd.request);
464         OBD_ALLOC(hsd.request, hsd.request_sz);
465         if (!hsd.request)
466                 GOTO(out, rc = -ENOMEM);
467
468         hsd.mti = mti;
469         obd_uuid2fsname(hsd.fs_name, mdt_obd_name(mdt), MTI_NAME_MAXLEN);
470
471         while (1) {
472                 struct l_wait_info lwi;
473                 int i;
474
475                 lwi = LWI_TIMEOUT(cfs_time_seconds(cdt->cdt_loop_period),
476                                   NULL, NULL);
477                 l_wait_event(cdt->cdt_thread.t_ctl_waitq,
478                              (cdt->cdt_thread.t_flags &
479                               (SVC_STOPPING|SVC_EVENT)),
480                              &lwi);
481
482                 CDEBUG(D_HSM, "coordinator resumes\n");
483
484                 if (cdt->cdt_thread.t_flags & SVC_STOPPING ||
485                     cdt->cdt_state == CDT_STOPPING) {
486                         cdt->cdt_thread.t_flags &= ~SVC_STOPPING;
487                         rc = 0;
488                         break;
489                 }
490
491                 /* wake up before timeout, new work arrives */
492                 if (cdt->cdt_thread.t_flags & SVC_EVENT)
493                         cdt->cdt_thread.t_flags &= ~SVC_EVENT;
494
495                 /* if coordinator is suspended continue to wait */
496                 if (cdt->cdt_state == CDT_DISABLE) {
497                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
498                         continue;
499                 }
500
501                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
502
503                 if (hsd.max_requests != cdt->cdt_max_requests) {
504                         /* cdt_max_requests has changed,
505                          * we need to allocate a new buffer
506                          */
507                         OBD_FREE(hsd.request, hsd.request_sz);
508                         hsd.max_requests = cdt->cdt_max_requests;
509                         hsd.request_sz =
510                                    hsd.max_requests * sizeof(*hsd.request);
511                         OBD_ALLOC(hsd.request, hsd.request_sz);
512                         if (!hsd.request) {
513                                 rc = -ENOMEM;
514                                 break;
515                         }
516                 }
517
518                 /* create canceled cookie vector for an arbitrary size
519                  * if needed, vector will grow during llog scan
520                  */
521                 hsd.max_cookie = 10;
522                 hsd.cookie_cnt = 0;
523                 OBD_ALLOC(hsd.cookies, hsd.max_cookie * sizeof(__u64));
524                 if (!hsd.cookies) {
525                         rc = -ENOMEM;
526                         goto clean_cb_alloc;
527                 }
528                 hsd.request_cnt = 0;
529
530                 rc = cdt_llog_process(mti->mti_env, mdt,
531                                       mdt_coordinator_cb, &hsd);
532                 if (rc < 0)
533                         goto clean_cb_alloc;
534
535                 CDEBUG(D_HSM, "Found %d requests to send and %d"
536                               " requests to cancel\n",
537                        hsd.request_cnt, hsd.cookie_cnt);
538                 /* first we cancel llog records of the timeouted requests */
539                 if (hsd.cookie_cnt > 0) {
540                         rc = mdt_agent_record_update(mti->mti_env, mdt,
541                                                      hsd.cookies,
542                                                      hsd.cookie_cnt,
543                                                      ARS_CANCELED);
544                         if (rc)
545                                 CERROR("%s: mdt_agent_record_update() failed, "
546                                        "rc=%d, cannot update status to %s "
547                                        "for %d cookies\n",
548                                        mdt_obd_name(mdt), rc,
549                                        agent_req_status2name(ARS_CANCELED),
550                                        hsd.cookie_cnt);
551                 }
552
553                 if (list_empty(&cdt->cdt_agents)) {
554                         CDEBUG(D_HSM, "no agent available, "
555                                       "coordinator sleeps\n");
556                         goto clean_cb_alloc;
557                 }
558
559                 /* here hsd contains a list of requests to be started */
560                 for (i = 0; i < hsd.max_requests; i++) {
561                         struct hsm_action_list  *hal;
562                         struct hsm_action_item  *hai;
563                         __u64                   *cookies;
564                         int                      sz, j;
565                         enum agent_req_status    status;
566
567                         /* still room for work ? */
568                         if (atomic_read(&cdt->cdt_request_count) ==
569                             cdt->cdt_max_requests)
570                                 break;
571
572                         if (hsd.request[i].hal == NULL)
573                                 continue;
574
575                         /* found a request, we start it */
576                         /* kuc payload allocation so we avoid an additionnal
577                          * allocation in mdt_hsm_agent_send()
578                          */
579                         hal = kuc_alloc(hsd.request[i].hal_used_sz,
580                                         KUC_TRANSPORT_HSM, HMT_ACTION_LIST);
581                         if (IS_ERR(hal)) {
582                                 CERROR("%s: Cannot allocate memory (%d o) "
583                                        "for compound "LPX64"\n",
584                                        mdt_obd_name(mdt),
585                                        hsd.request[i].hal_used_sz,
586                                        hsd.request[i].hal->hal_compound_id);
587                                 continue;
588                         }
589                         memcpy(hal, hsd.request[i].hal,
590                                hsd.request[i].hal_used_sz);
591
592                         rc = mdt_hsm_agent_send(mti, hal, 0);
593                         /* if failure, we suppose it is temporary
594                          * if the copy tool failed to do the request
595                          * it has to use hsm_progress
596                          */
597                         status = (rc ? ARS_WAITING : ARS_STARTED);
598
599                         /* set up cookie vector to set records status
600                          * after copy tools start or failed
601                          */
602                         sz = hsd.request[i].hal->hal_count * sizeof(__u64);
603                         OBD_ALLOC(cookies, sz);
604                         if (cookies == NULL) {
605                                 CERROR("%s: Cannot allocate memory (%d o) "
606                                        "for cookies vector "LPX64"\n",
607                                        mdt_obd_name(mdt), sz,
608                                        hsd.request[i].hal->hal_compound_id);
609                                 kuc_free(hal, hsd.request[i].hal_used_sz);
610                                 continue;
611                         }
612                         hai = hai_first(hal);
613                         for (j = 0; j < hsd.request[i].hal->hal_count; j++) {
614                                 cookies[j] = hai->hai_cookie;
615                                 hai = hai_next(hai);
616                         }
617
618                         rc = mdt_agent_record_update(mti->mti_env, mdt, cookies,
619                                                 hsd.request[i].hal->hal_count,
620                                                 status);
621                         if (rc)
622                                 CERROR("%s: mdt_agent_record_update() failed, "
623                                        "rc=%d, cannot update status to %s "
624                                        "for %d cookies\n",
625                                        mdt_obd_name(mdt), rc,
626                                        agent_req_status2name(status),
627                                        hsd.request[i].hal->hal_count);
628
629                         OBD_FREE(cookies, sz);
630                         kuc_free(hal, hsd.request[i].hal_used_sz);
631                 }
632 clean_cb_alloc:
633                 /* free cookie vector allocated for/by callback */
634                 if (hsd.cookies) {
635                         OBD_FREE(hsd.cookies, hsd.max_cookie * sizeof(__u64));
636                         hsd.max_cookie = 0;
637                         hsd.cookie_cnt = 0;
638                         hsd.cookies = NULL;
639                 }
640
641                 /* free hal allocated by callback */
642                 for (i = 0; i < hsd.max_requests; i++) {
643                         if (hsd.request[i].hal) {
644                                 OBD_FREE(hsd.request[i].hal,
645                                          hsd.request[i].hal_sz);
646                                 hsd.request[i].hal_sz = 0;
647                                 hsd.request[i].hal = NULL;
648                                 hsd.request_cnt--;
649                         }
650                 }
651                 LASSERT(hsd.request_cnt == 0);
652
653                 /* reset callback data */
654                 memset(hsd.request, 0, hsd.request_sz);
655         }
656         EXIT;
657 out:
658         if (hsd.request)
659                 OBD_FREE(hsd.request, hsd.request_sz);
660
661         if (hsd.cookies)
662                 OBD_FREE(hsd.cookies, hsd.max_cookie * sizeof(__u64));
663
664         if (cdt->cdt_state == CDT_STOPPING) {
665                 /* request comes from /proc path, so we need to clean cdt
666                  * struct */
667                  mdt_hsm_cdt_stop(mdt);
668                  mdt->mdt_opts.mo_coordinator = 0;
669         } else {
670                 /* request comes from a thread event, generated
671                  * by mdt_stop_coordinator(), we have to ack
672                  * and cdt cleaning will be done by event sender
673                  */
674                 cdt->cdt_thread.t_flags = SVC_STOPPED;
675                 wake_up(&cdt->cdt_thread.t_ctl_waitq);
676         }
677
678         if (rc != 0)
679                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
680                        mdt_obd_name(mdt), current_pid(), rc);
681         else
682                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
683                               " no error\n",
684                        mdt_obd_name(mdt), current_pid());
685
686         return rc;
687 }
688
689 /**
690  * lookup a restore handle by FID
691  * caller needs to hold cdt_restore_lock
692  * \param cdt [IN] coordinator
693  * \param fid [IN] FID
694  * \retval cdt_restore_handle found
695  * \retval NULL not found
696  */
697 static struct cdt_restore_handle *hsm_restore_hdl_find(struct coordinator *cdt,
698                                                        const struct lu_fid *fid)
699 {
700         struct cdt_restore_handle       *crh;
701         ENTRY;
702
703         list_for_each_entry(crh, &cdt->cdt_restore_hdl, crh_list) {
704                 if (lu_fid_eq(&crh->crh_fid, fid))
705                         RETURN(crh);
706         }
707         RETURN(NULL);
708 }
709
710 /**
711  * data passed to llog_cat_process() callback
712  * to scan requests and take actions
713  */
714 struct hsm_restore_data {
715         struct mdt_thread_info  *hrd_mti;
716 };
717
718 /**
719  *  llog_cat_process() callback, used to:
720  *  - find restore request and allocate the restore handle
721  * \param env [IN] environment
722  * \param llh [IN] llog handle
723  * \param hdr [IN] llog record
724  * \param data [IN/OUT] cb data = struct hsm_restore_data
725  * \retval 0 success
726  * \retval -ve failure
727  */
728 static int hsm_restore_cb(const struct lu_env *env,
729                           struct llog_handle *llh,
730                           struct llog_rec_hdr *hdr, void *data)
731 {
732         struct llog_agent_req_rec       *larr;
733         struct hsm_restore_data         *hrd;
734         struct cdt_restore_handle       *crh;
735         struct hsm_action_item          *hai;
736         struct mdt_thread_info          *mti;
737         struct coordinator              *cdt;
738         struct mdt_object               *child;
739         int rc;
740         ENTRY;
741
742         hrd = data;
743         mti = hrd->hrd_mti;
744         cdt = &mti->mti_mdt->mdt_coordinator;
745
746         larr = (struct llog_agent_req_rec *)hdr;
747         hai = &larr->arr_hai;
748         if (hai->hai_cookie > cdt->cdt_last_cookie)
749                 /* update the cookie to avoid collision */
750                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
751
752         if (hai->hai_action != HSMA_RESTORE ||
753             agent_req_in_final_state(larr->arr_status))
754                 RETURN(0);
755
756         /* restore request not in a final state */
757
758         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
759         if (crh == NULL)
760                 RETURN(-ENOMEM);
761
762         crh->crh_fid = hai->hai_fid;
763         /* in V1 all file is restored
764         crh->extent.start = hai->hai_extent.offset;
765         crh->extent.end = hai->hai_extent.offset + hai->hai_extent.length;
766         */
767         crh->crh_extent.start = 0;
768         crh->crh_extent.end = hai->hai_extent.length;
769         /* get the layout lock */
770         mdt_lock_reg_init(&crh->crh_lh, LCK_EX);
771         child = mdt_object_find_lock(mti, &crh->crh_fid, &crh->crh_lh,
772                                      MDS_INODELOCK_LAYOUT);
773         if (IS_ERR(child))
774                 GOTO(out, rc = PTR_ERR(child));
775
776         rc = 0;
777         /* we choose to not keep a reference
778          * on the object during the restore time which can be very long */
779         mdt_object_put(mti->mti_env, child);
780
781         mutex_lock(&cdt->cdt_restore_lock);
782         list_add_tail(&crh->crh_list, &cdt->cdt_restore_hdl);
783         mutex_unlock(&cdt->cdt_restore_lock);
784
785 out:
786         RETURN(rc);
787 }
788
789 /**
790  * restore coordinator state at startup
791  * the goal is to take a layout lock for each registered restore request
792  * \param mti [IN] context
793  */
794 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
795 {
796         struct hsm_restore_data  hrd;
797         int                      rc;
798         ENTRY;
799
800         hrd.hrd_mti = mti;
801
802         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt,
803                               hsm_restore_cb, &hrd);
804
805         RETURN(rc);
806 }
807
808 static int hsm_init_ucred(struct lu_ucred *uc)
809 {
810         ENTRY;
811
812         uc->uc_valid = UCRED_OLD;
813         uc->uc_o_uid = 0;
814         uc->uc_o_gid = 0;
815         uc->uc_o_fsuid = 0;
816         uc->uc_o_fsgid = 0;
817         uc->uc_uid = 0;
818         uc->uc_gid = 0;
819         uc->uc_fsuid = 0;
820         uc->uc_fsgid = 0;
821         uc->uc_suppgids[0] = -1;
822         uc->uc_suppgids[1] = -1;
823         uc->uc_cap = CFS_CAP_FS_MASK;
824         uc->uc_umask = 0777;
825         uc->uc_ginfo = NULL;
826         uc->uc_identity = NULL;
827
828         RETURN(0);
829 }
830
831 /**
832  * wake up coordinator thread
833  * \param mdt [IN] device
834  * \retval 0 success
835  * \retval -ve failure
836  */
837 int mdt_hsm_cdt_wakeup(struct mdt_device *mdt)
838 {
839         struct coordinator      *cdt = &mdt->mdt_coordinator;
840         ENTRY;
841
842         if (cdt->cdt_state == CDT_STOPPED)
843                 RETURN(-ESRCH);
844
845         /* wake up coordinator */
846         cdt->cdt_thread.t_flags = SVC_EVENT;
847         wake_up(&cdt->cdt_thread.t_ctl_waitq);
848
849         RETURN(0);
850 }
851
852 /**
853  * initialize coordinator struct
854  * \param mdt [IN] device
855  * \retval 0 success
856  * \retval -ve failure
857  */
858 int mdt_hsm_cdt_init(struct mdt_device *mdt)
859 {
860         struct coordinator      *cdt = &mdt->mdt_coordinator;
861         struct mdt_thread_info  *cdt_mti = NULL;
862         int                      rc;
863         ENTRY;
864
865         cdt->cdt_state = CDT_STOPPED;
866
867         init_waitqueue_head(&cdt->cdt_thread.t_ctl_waitq);
868         mutex_init(&cdt->cdt_llog_lock);
869         init_rwsem(&cdt->cdt_agent_lock);
870         init_rwsem(&cdt->cdt_request_lock);
871         mutex_init(&cdt->cdt_restore_lock);
872
873         CFS_INIT_LIST_HEAD(&cdt->cdt_requests);
874         CFS_INIT_LIST_HEAD(&cdt->cdt_agents);
875         CFS_INIT_LIST_HEAD(&cdt->cdt_restore_hdl);
876
877         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
878         if (rc < 0)
879                 RETURN(rc);
880
881         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
882         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
883         if (rc == 0) {
884                 lu_context_enter(&cdt->cdt_session);
885                 cdt->cdt_env.le_ses = &cdt->cdt_session;
886         } else {
887                 lu_env_fini(&cdt->cdt_env);
888                 RETURN(rc);
889         }
890
891         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
892         LASSERT(cdt_mti != NULL);
893
894         cdt_mti->mti_env = &cdt->cdt_env;
895         cdt_mti->mti_mdt = mdt;
896
897         hsm_init_ucred(mdt_ucred(cdt_mti));
898
899         /* default values for /proc tunnables
900          * can be override by MGS conf */
901         cdt->cdt_default_archive_id = 1;
902         cdt->cdt_grace_delay = 60;
903         cdt->cdt_loop_period = 10;
904         cdt->cdt_max_requests = 3;
905         cdt->cdt_policy = CDT_DEFAULT_POLICY;
906         cdt->cdt_active_req_timeout = 3600;
907
908         RETURN(0);
909 }
910
911 /**
912  * free a coordinator thread
913  * \param mdt [IN] device
914  */
915 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
916 {
917         struct coordinator *cdt = &mdt->mdt_coordinator;
918         ENTRY;
919
920         lu_context_exit(cdt->cdt_env.le_ses);
921         lu_context_fini(cdt->cdt_env.le_ses);
922
923         lu_env_fini(&cdt->cdt_env);
924
925         RETURN(0);
926 }
927
928 /**
929  * start a coordinator thread
930  * \param mdt [IN] device
931  * \retval 0 success
932  * \retval -ve failure
933  */
934 int mdt_hsm_cdt_start(struct mdt_device *mdt)
935 {
936         struct coordinator      *cdt = &mdt->mdt_coordinator;
937         int                      rc;
938         void                    *ptr;
939         struct mdt_thread_info  *cdt_mti;
940         struct task_struct      *task;
941         ENTRY;
942
943         /* functions defined but not yet used
944          * this avoid compilation warning
945          */
946         ptr = dump_requests;
947
948         if (cdt->cdt_state != CDT_STOPPED) {
949                 CERROR("%s: Coordinator already started\n",
950                        mdt_obd_name(mdt));
951                 RETURN(-EALREADY);
952         }
953
954         CLASSERT(1 << (CDT_POLICY_SHIFT_COUNT - 1) == CDT_POLICY_LAST);
955         cdt->cdt_policy = CDT_DEFAULT_POLICY;
956
957         cdt->cdt_state = CDT_INIT;
958
959         atomic_set(&cdt->cdt_compound_id, cfs_time_current_sec());
960         /* just need to be larger than previous one */
961         /* cdt_last_cookie is protected by cdt_llog_lock */
962         cdt->cdt_last_cookie = cfs_time_current_sec();
963         atomic_set(&cdt->cdt_request_count, 0);
964         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
965         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
966         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
967
968         /* to avoid deadlock when start is made through /proc
969          * /proc entries are created by the coordinator thread */
970
971         /* set up list of started restore requests */
972         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
973         rc = mdt_hsm_pending_restore(cdt_mti);
974         if (rc)
975                 CERROR("%s: cannot take the layout locks needed"
976                        " for registered restore: %d",
977                        mdt_obd_name(mdt), rc);
978
979         task = kthread_run(mdt_coordinator, cdt_mti, "hsm_cdtr");
980         if (IS_ERR(task)) {
981                 rc = PTR_ERR(task);
982                 cdt->cdt_state = CDT_STOPPED;
983                 CERROR("%s: error starting coordinator thread: %d\n",
984                        mdt_obd_name(mdt), rc);
985                 RETURN(rc);
986         } else {
987                 CDEBUG(D_HSM, "%s: coordinator thread started\n",
988                        mdt_obd_name(mdt));
989                 rc = 0;
990         }
991
992         wait_event(cdt->cdt_thread.t_ctl_waitq,
993                        (cdt->cdt_thread.t_flags & SVC_RUNNING));
994
995         cdt->cdt_state = CDT_RUNNING;
996         mdt->mdt_opts.mo_coordinator = 1;
997         RETURN(0);
998 }
999
1000 /**
1001  * stop a coordinator thread
1002  * \param mdt [IN] device
1003  */
1004 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
1005 {
1006         struct coordinator              *cdt = &mdt->mdt_coordinator;
1007         struct cdt_agent_req            *car, *tmp1;
1008         struct hsm_agent                *ha, *tmp2;
1009         struct cdt_restore_handle       *crh, *tmp3;
1010         struct mdt_thread_info          *cdt_mti;
1011         ENTRY;
1012
1013         if (cdt->cdt_state == CDT_STOPPED) {
1014                 CERROR("%s: Coordinator already stopped\n",
1015                        mdt_obd_name(mdt));
1016                 RETURN(-EALREADY);
1017         }
1018
1019         if (cdt->cdt_state != CDT_STOPPING) {
1020                 /* stop coordinator thread before cleaning */
1021                 cdt->cdt_thread.t_flags = SVC_STOPPING;
1022                 wake_up(&cdt->cdt_thread.t_ctl_waitq);
1023                 wait_event(cdt->cdt_thread.t_ctl_waitq,
1024                            cdt->cdt_thread.t_flags & SVC_STOPPED);
1025         }
1026         cdt->cdt_state = CDT_STOPPED;
1027
1028         /* start cleaning */
1029         down_write(&cdt->cdt_request_lock);
1030         list_for_each_entry_safe(car, tmp1, &cdt->cdt_requests,
1031                                  car_request_list) {
1032                 list_del(&car->car_request_list);
1033                 mdt_cdt_free_request(car);
1034         }
1035         up_write(&cdt->cdt_request_lock);
1036
1037         down_write(&cdt->cdt_agent_lock);
1038         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
1039                 list_del(&ha->ha_list);
1040                 OBD_FREE_PTR(ha);
1041         }
1042         up_write(&cdt->cdt_agent_lock);
1043
1044         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1045         mutex_lock(&cdt->cdt_restore_lock);
1046         list_for_each_entry_safe(crh, tmp3, &cdt->cdt_restore_hdl, crh_list) {
1047                 struct mdt_object       *child;
1048
1049                 /* give back layout lock */
1050                 child = mdt_object_find(&cdt->cdt_env, mdt, &crh->crh_fid);
1051                 if (!IS_ERR(child))
1052                         mdt_object_unlock_put(cdt_mti, child, &crh->crh_lh, 1);
1053
1054                 list_del(&crh->crh_list);
1055
1056                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
1057         }
1058         mutex_unlock(&cdt->cdt_restore_lock);
1059
1060         mdt->mdt_opts.mo_coordinator = 0;
1061
1062         RETURN(0);
1063 }
1064
1065 /**
1066  * register all requests from an hal in the memory list
1067  * \param mti [IN] context
1068  * \param hal [IN] request
1069  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
1070  *  which is running the CT
1071  * \retval 0 success
1072  * \retval -ve failure
1073  */
1074 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
1075                     struct hsm_action_list *hal, struct obd_uuid *uuid)
1076 {
1077         struct mdt_device       *mdt = mti->mti_mdt;
1078         struct coordinator      *cdt = &mdt->mdt_coordinator;
1079         struct hsm_action_item  *hai;
1080         int                      rc = 0, i;
1081         ENTRY;
1082
1083         /* register request in memory list */
1084         hai = hai_first(hal);
1085         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
1086                 struct cdt_agent_req *car;
1087
1088                 /* in case of a cancel request, we first mark the ondisk
1089                  * record of the request we want to stop as canceled
1090                  * this does not change the cancel record
1091                  * it will be done when updating the request status
1092                  */
1093                 if (hai->hai_action == HSMA_CANCEL) {
1094                         rc = mdt_agent_record_update(mti->mti_env, mti->mti_mdt,
1095                                                      &hai->hai_cookie,
1096                                                      1, ARS_CANCELED);
1097                         if (rc) {
1098                                 CERROR("%s: mdt_agent_record_update() failed, "
1099                                        "rc=%d, cannot update status to %s "
1100                                        "for cookie "LPX64"\n",
1101                                        mdt_obd_name(mdt), rc,
1102                                        agent_req_status2name(ARS_CANCELED),
1103                                        hai->hai_cookie);
1104                                 GOTO(out, rc);
1105                         }
1106
1107                         /* find the running request to set it canceled */
1108                         car = mdt_cdt_find_request(cdt, hai->hai_cookie, NULL);
1109                         if (car != NULL) {
1110                                 car->car_canceled = 1;
1111                                 /* uuid has to be changed to the one running the
1112                                 * request to cancel */
1113                                 *uuid = car->car_uuid;
1114                                 mdt_cdt_put_request(car);
1115                         }
1116                         /* no need to memorize cancel request
1117                          * this also avoid a deadlock when we receive
1118                          * a purge all requests command
1119                          */
1120                         continue;
1121                 }
1122
1123                 if (hai->hai_action == HSMA_ARCHIVE) {
1124                         struct mdt_object *obj;
1125                         struct md_hsm hsm;
1126
1127                         obj = mdt_hsm_get_md_hsm(mti, &hai->hai_fid, &hsm);
1128                         if (IS_ERR(obj) && (PTR_ERR(obj) == -ENOENT))
1129                                 continue;
1130                         if (IS_ERR(obj))
1131                                 GOTO(out, rc = PTR_ERR(obj));
1132
1133                         hsm.mh_flags |= HS_EXISTS;
1134                         hsm.mh_arch_id = hal->hal_archive_id;
1135                         rc = mdt_hsm_attr_set(mti, obj, &hsm);
1136                         mdt_object_put(mti->mti_env, obj);
1137                         if (rc)
1138                                 GOTO(out, rc);
1139                 }
1140
1141                 car = mdt_cdt_alloc_request(hal->hal_compound_id,
1142                                             hal->hal_archive_id, hal->hal_flags,
1143                                             uuid, hai);
1144                 if (IS_ERR(car))
1145                         GOTO(out, rc = PTR_ERR(car));
1146
1147                 rc = mdt_cdt_add_request(cdt, car);
1148                 if (rc != 0)
1149                         mdt_cdt_free_request(car);
1150         }
1151 out:
1152         RETURN(rc);
1153 }
1154
1155 /**
1156  * swap layouts between 2 fids
1157  * \param mti [IN] context
1158  * \param fid1 [IN]
1159  * \param fid2 [IN]
1160  * \param mh_common [IN] MD HSM
1161  */
1162 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1163                             const lustre_fid *fid, const lustre_fid *dfid,
1164                             struct md_hsm *mh_common)
1165 {
1166         struct mdt_device       *mdt = mti->mti_mdt;
1167         struct mdt_object       *child1, *child2;
1168         struct mdt_lock_handle  *lh2;
1169         int                      rc;
1170         ENTRY;
1171
1172         child1 = mdt_object_find(mti->mti_env, mdt, fid);
1173         if (IS_ERR(child1))
1174                 GOTO(out, rc = PTR_ERR(child1));
1175
1176         /* we already have layout lock on FID so take only
1177          * on dfid */
1178         lh2 = &mti->mti_lh[MDT_LH_OLD];
1179         mdt_lock_reg_init(lh2, LCK_EX);
1180         child2 = mdt_object_find_lock(mti, dfid, lh2, MDS_INODELOCK_LAYOUT);
1181         if (IS_ERR(child2))
1182                 GOTO(out_child1, rc = PTR_ERR(child2));
1183
1184         /* if copy tool closes the volatile before sending the final
1185          * progress through llapi_hsm_copy_end(), all the objects
1186          * are removed and mdd_swap_layout LBUG */
1187         if (!mdt_object_exists(child2)) {
1188                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1189                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1190                 GOTO(out_child2, rc = -ENOENT);
1191         }
1192         /* Since we only handle restores here, unconditionally use
1193          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1194          * be preserved in case of failure during swap_layout and not
1195          * leave a file in an intermediate but incoherent state.
1196          * But need to setup HSM xattr of data FID before, reuse
1197          * mti and mh presets for FID in hsm_cdt_request_completed(),
1198          * only need to clear RELEASED and DIRTY.
1199          */
1200         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1201         rc = mdt_hsm_attr_set(mti, child2, mh_common);
1202         if (rc == 0)
1203                 rc = mo_swap_layouts(mti->mti_env,
1204                                      mdt_object_child(child1),
1205                                      mdt_object_child(child2),
1206                                      SWAP_LAYOUTS_MDS_HSM);
1207
1208 out_child2:
1209         mdt_object_unlock_put(mti, child2, lh2, 1);
1210 out_child1:
1211         mdt_object_put(mti->mti_env, child1);
1212 out:
1213         RETURN(rc);
1214 }
1215
1216 /**
1217  * update status of a completed request
1218  * \param mti [IN] context
1219  * \param pgs [IN] progress of the copy tool
1220  * \param update_record [IN] update llog record
1221  * \retval 0 success
1222  * \retval -ve failure
1223  */
1224 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1225                                      struct hsm_progress_kernel *pgs,
1226                                      const struct cdt_agent_req *car,
1227                                      enum agent_req_status *status)
1228 {
1229         const struct lu_env     *env = mti->mti_env;
1230         struct mdt_device       *mdt = mti->mti_mdt;
1231         struct coordinator      *cdt = &mdt->mdt_coordinator;
1232         struct mdt_object       *obj = NULL;
1233         int                      cl_flags = 0, rc = 0;
1234         struct md_hsm            mh;
1235         bool                     is_mh_changed;
1236         ENTRY;
1237
1238         /* default is to retry */
1239         *status = ARS_WAITING;
1240
1241         /* find object by FID */
1242         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1243         /* we will update MD HSM only if needed */
1244         is_mh_changed = false;
1245         if (IS_ERR(obj)) {
1246                 /* object removed */
1247                 *status = ARS_SUCCEED;
1248                 goto unlock;
1249         }
1250
1251         /* no need to change mh->mh_arch_id
1252          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1253          */
1254         if (pgs->hpk_errval != 0) {
1255                 switch (pgs->hpk_errval) {
1256                 case ENOSYS:
1257                         /* the copy tool does not support cancel
1258                          * so the cancel request is failed
1259                          * As we cannot distinguish a cancel progress
1260                          * from another action progress (they have the
1261                          * same cookie), we suppose here the CT returns
1262                          * ENOSYS only if does not support cancel
1263                          */
1264                         /* this can also happen when cdt calls it to
1265                          * for a timeouted request */
1266                         *status = ARS_FAILED;
1267                         /* to have a cancel event in changelog */
1268                         pgs->hpk_errval = ECANCELED;
1269                         break;
1270                 case ECANCELED:
1271                         /* the request record has already been set to
1272                          * ARS_CANCELED, this set the cancel request
1273                          * to ARS_SUCCEED */
1274                         *status = ARS_SUCCEED;
1275                         break;
1276                 default:
1277                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1278                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ?
1279                                    ARS_FAILED : ARS_WAITING);
1280                         break;
1281                 }
1282
1283                 if (pgs->hpk_errval > CLF_HSM_MAXERROR) {
1284                         CERROR("%s: Request "LPX64" on "DFID
1285                                " failed, error code %d too large\n",
1286                                mdt_obd_name(mdt),
1287                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1288                                pgs->hpk_errval);
1289                         hsm_set_cl_error(&cl_flags,
1290                                          CLF_HSM_ERROVERFLOW);
1291                         rc = -EINVAL;
1292                 } else {
1293                         hsm_set_cl_error(&cl_flags, pgs->hpk_errval);
1294                 }
1295
1296                 switch (car->car_hai->hai_action) {
1297                 case HSMA_ARCHIVE:
1298                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1299                         break;
1300                 case HSMA_RESTORE:
1301                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1302                         break;
1303                 case HSMA_REMOVE:
1304                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1305                         break;
1306                 case HSMA_CANCEL:
1307                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1308                         CERROR("%s: Failed request "LPX64" on "DFID
1309                                " cannot be a CANCEL\n",
1310                                mdt_obd_name(mdt),
1311                                pgs->hpk_cookie,
1312                                PFID(&pgs->hpk_fid));
1313                         break;
1314                 default:
1315                         CERROR("%s: Failed request "LPX64" on "DFID
1316                                " %d is an unknown action\n",
1317                                mdt_obd_name(mdt),
1318                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1319                                car->car_hai->hai_action);
1320                         rc = -EINVAL;
1321                         break;
1322                 }
1323         } else {
1324                 *status = ARS_SUCCEED;
1325                 switch (car->car_hai->hai_action) {
1326                 case HSMA_ARCHIVE:
1327                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1328                         /* set ARCHIVE keep EXIST and clear LOST and
1329                          * DIRTY */
1330                         mh.mh_arch_ver = pgs->hpk_data_version;
1331                         mh.mh_flags |= HS_ARCHIVED;
1332                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1333                         is_mh_changed = true;
1334                         break;
1335                 case HSMA_RESTORE:
1336                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1337
1338                         /* do not clear RELEASED and DIRTY here
1339                          * this will occur in hsm_swap_layouts()
1340                          */
1341
1342                         /* Restoring has changed the file version on
1343                          * disk. */
1344                         mh.mh_arch_ver = pgs->hpk_data_version;
1345                         is_mh_changed = true;
1346                         break;
1347                 case HSMA_REMOVE:
1348                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1349                         /* clear ARCHIVED EXISTS and LOST */
1350                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1351                         is_mh_changed = true;
1352                         break;
1353                 case HSMA_CANCEL:
1354                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1355                         CERROR("%s: Successful request "LPX64
1356                                " on "DFID
1357                                " cannot be a CANCEL\n",
1358                                mdt_obd_name(mdt),
1359                                pgs->hpk_cookie,
1360                                PFID(&pgs->hpk_fid));
1361                         break;
1362                 default:
1363                         CERROR("%s: Successful request "LPX64
1364                                " on "DFID
1365                                " %d is an unknown action\n",
1366                                mdt_obd_name(mdt),
1367                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1368                                car->car_hai->hai_action);
1369                         rc = -EINVAL;
1370                         break;
1371                 }
1372         }
1373
1374         /* rc != 0 means error when analysing action, it may come from
1375          * a crasy CT no need to manage DIRTY
1376          */
1377         if (rc == 0)
1378                 hsm_set_cl_flags(&cl_flags,
1379                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1380
1381         /* unlock is done later, after layout lock management */
1382         if (is_mh_changed)
1383                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1384
1385 unlock:
1386         /* we give back layout lock only if restore was successful or
1387          * if restore was canceled or if policy is to not retry
1388          * in other cases we just unlock the object */
1389         if (car->car_hai->hai_action == HSMA_RESTORE &&
1390             (pgs->hpk_errval == 0 || pgs->hpk_errval == ECANCELED ||
1391              cdt->cdt_policy & CDT_NORETRY_ACTION)) {
1392                 struct cdt_restore_handle       *crh;
1393
1394                 /* restore in data FID done, we swap the layouts
1395                  * only if restore is successfull */
1396                 if (pgs->hpk_errval == 0) {
1397                         rc = hsm_swap_layouts(mti, &car->car_hai->hai_fid,
1398                                               &car->car_hai->hai_dfid, &mh);
1399                         if (rc) {
1400                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1401                                         *status = ARS_FAILED;
1402                                 pgs->hpk_errval = -rc;
1403                         }
1404                 }
1405                 /* we have to retry, so keep layout lock */
1406                 if (*status == ARS_WAITING)
1407                         GOTO(out, rc);
1408
1409                 /* give back layout lock */
1410                 mutex_lock(&cdt->cdt_restore_lock);
1411                 crh = hsm_restore_hdl_find(cdt, &car->car_hai->hai_fid);
1412                 if (crh != NULL)
1413                         list_del(&crh->crh_list);
1414                 mutex_unlock(&cdt->cdt_restore_lock);
1415                 /* just give back layout lock, we keep
1416                  * the reference which is given back
1417                  * later with the lock for HSM flags */
1418                 if (!IS_ERR(obj) && crh != NULL)
1419                         mdt_object_unlock(mti, obj, &crh->crh_lh, 1);
1420
1421                 if (crh != NULL)
1422                         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
1423         }
1424
1425         GOTO(out, rc);
1426
1427 out:
1428         if (obj != NULL && !IS_ERR(obj)) {
1429                 mo_changelog(env, CL_HSM, cl_flags,
1430                              mdt_object_child(obj));
1431                 mdt_object_put(mti->mti_env, obj);
1432         }
1433
1434         RETURN(rc);
1435 }
1436
1437 /**
1438  * update status of a request
1439  * \param mti [IN] context
1440  * \param pgs [IN] progress of the copy tool
1441  * \param update_record [IN] update llog record
1442  * \retval 0 success
1443  * \retval -ve failure
1444  */
1445 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1446                                  struct hsm_progress_kernel *pgs,
1447                                  const int update_record)
1448 {
1449         struct mdt_device       *mdt = mti->mti_mdt;
1450         struct coordinator      *cdt = &mdt->mdt_coordinator;
1451         struct cdt_agent_req    *car;
1452         int                      rc = 0;
1453         ENTRY;
1454
1455         /* no coordinator started, so we cannot serve requests */
1456         if (cdt->cdt_state == CDT_STOPPED)
1457                 RETURN(-EAGAIN);
1458
1459         /* first do sanity checks */
1460         car = mdt_cdt_update_request(cdt, pgs);
1461         if (IS_ERR(car)) {
1462                 CERROR("%s: Cannot find running request for cookie "LPX64
1463                        " on fid="DFID"\n",
1464                        mdt_obd_name(mdt),
1465                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1466                 if (car == NULL)
1467                         RETURN(-ENOENT);
1468                 RETURN(PTR_ERR(car));
1469         }
1470
1471         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie="LPX64
1472                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1473                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1474                       hsm_copytool_action2name(car->car_hai->hai_action),
1475                       pgs->hpk_flags, pgs->hpk_errval,
1476                       PFID(&car->car_hai->hai_fid),
1477                       PFID(&car->car_hai->hai_dfid));
1478
1479         /* progress is done on FID or data FID depending of the action and
1480          * of the copy progress */
1481         /* for restore progress is used to send back the data FID to cdt */
1482         if (car->car_hai->hai_action == HSMA_RESTORE &&
1483             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1484                 car->car_hai->hai_dfid = pgs->hpk_fid;
1485
1486         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1487              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1488             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1489              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1490                 CERROR("%s: Progress on "DFID" for cookie "LPX64
1491                        " does not match request FID "DFID" nor data FID "
1492                        DFID"\n",
1493                        mdt_obd_name(mdt),
1494                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1495                        PFID(&car->car_hai->hai_fid),
1496                        PFID(&car->car_hai->hai_dfid));
1497                 GOTO(out, rc = -EINVAL);
1498         }
1499
1500         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1501                 CERROR("%s: Progress on "DFID" for cookie "LPX64" action=%s"
1502                        " is not coherent (err=%d and not completed"
1503                        " (flags=%d))\n",
1504                        mdt_obd_name(mdt),
1505                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1506                        hsm_copytool_action2name(car->car_hai->hai_action),
1507                        pgs->hpk_errval, pgs->hpk_flags);
1508                 GOTO(out, rc = -EINVAL);
1509         }
1510
1511         /* now progress is valid */
1512
1513         /* we use a root like ucred */
1514         hsm_init_ucred(mdt_ucred(mti));
1515
1516         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1517                 enum agent_req_status    status;
1518
1519                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1520
1521                 /* remove request from memory list */
1522                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1523
1524                 CDEBUG(D_HSM, "Updating record: fid="DFID" cookie="LPX64
1525                               " action=%s status=%s\n", PFID(&pgs->hpk_fid),
1526                        pgs->hpk_cookie,
1527                        hsm_copytool_action2name(car->car_hai->hai_action),
1528                        agent_req_status2name(status));
1529
1530                 if (update_record) {
1531                         int rc1;
1532
1533                         rc1 = mdt_agent_record_update(mti->mti_env, mdt,
1534                                                      &pgs->hpk_cookie, 1,
1535                                                      status);
1536                         if (rc1)
1537                                 CERROR("%s: mdt_agent_record_update() failed,"
1538                                        " rc=%d, cannot update status to %s"
1539                                        " for cookie "LPX64"\n",
1540                                        mdt_obd_name(mdt), rc1,
1541                                        agent_req_status2name(status),
1542                                        pgs->hpk_cookie);
1543                         rc = (rc != 0 ? rc : rc1);
1544                 }
1545                 /* ct has completed a request, so a slot is available, wakeup
1546                  * cdt to find new work */
1547                 mdt_hsm_cdt_wakeup(mdt);
1548         } else {
1549                 /* if copytool send a progress on a canceled request
1550                  * we inform copytool it should stop
1551                  */
1552                 if (car->car_canceled == 1)
1553                         rc = -ECANCELED;
1554         }
1555         GOTO(out, rc);
1556
1557 out:
1558         /* remove ref got from mdt_cdt_update_request() */
1559         mdt_cdt_put_request(car);
1560
1561         return rc;
1562 }
1563
1564
1565 /**
1566  * data passed to llog_cat_process() callback
1567  * to cancel requests
1568  */
1569 struct hsm_cancel_all_data {
1570         struct mdt_device       *mdt;
1571 };
1572
1573 /**
1574  *  llog_cat_process() callback, used to:
1575  *  - purge all requests
1576  * \param env [IN] environment
1577  * \param llh [IN] llog handle
1578  * \param hdr [IN] llog record
1579  * \param data [IN] cb data = struct hsm_cancel_all_data
1580  * \retval 0 success
1581  * \retval -ve failure
1582  */
1583 static int mdt_cancel_all_cb(const struct lu_env *env,
1584                              struct llog_handle *llh,
1585                              struct llog_rec_hdr *hdr, void *data)
1586 {
1587         struct llog_agent_req_rec       *larr;
1588         struct hsm_cancel_all_data      *hcad;
1589         int                              rc = 0;
1590         ENTRY;
1591
1592         larr = (struct llog_agent_req_rec *)hdr;
1593         hcad = data;
1594         if (larr->arr_status == ARS_WAITING ||
1595             larr->arr_status == ARS_STARTED) {
1596                 larr->arr_status = ARS_CANCELED;
1597                 larr->arr_req_change = cfs_time_current_sec();
1598                 rc = mdt_agent_llog_update_rec(env, hcad->mdt, llh, larr);
1599                 if (rc == 0)
1600                         RETURN(LLOG_DEL_RECORD);
1601         }
1602         RETURN(rc);
1603 }
1604
1605 /**
1606  * cancel all actions
1607  * \param obd [IN] MDT device
1608  */
1609 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1610 {
1611         struct mdt_thread_info          *mti;
1612         struct coordinator              *cdt = &mdt->mdt_coordinator;
1613         struct cdt_agent_req            *car;
1614         struct hsm_action_list          *hal = NULL;
1615         struct hsm_action_item          *hai;
1616         struct hsm_cancel_all_data       hcad;
1617         int                              hal_sz = 0, hal_len, rc;
1618         enum cdt_states                  save_state;
1619         ENTRY;
1620
1621         /* retrieve coordinator context */
1622         mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1623
1624         /* disable coordinator */
1625         save_state = cdt->cdt_state;
1626         cdt->cdt_state = CDT_DISABLE;
1627
1628         /* send cancel to all running requests */
1629         down_read(&cdt->cdt_request_lock);
1630         list_for_each_entry(car, &cdt->cdt_requests, car_request_list) {
1631                 mdt_cdt_get_request(car);
1632                 /* request is not yet removed from list, it will be done
1633                  * when copytool will return progress
1634                  */
1635
1636                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1637                         mdt_cdt_put_request(car);
1638                         continue;
1639                 }
1640
1641                 /* needed size */
1642                 hal_len = sizeof(*hal) + cfs_size_round(MTI_NAME_MAXLEN + 1) +
1643                           cfs_size_round(car->car_hai->hai_len);
1644
1645                 if (hal_len > hal_sz && hal_sz > 0) {
1646                         /* not enough room, free old buffer */
1647                         OBD_FREE(hal, hal_sz);
1648                         hal = NULL;
1649                 }
1650
1651                 /* empty buffer, allocate one */
1652                 if (hal == NULL) {
1653                         hal_sz = hal_len;
1654                         OBD_ALLOC(hal, hal_sz);
1655                         if (hal == NULL) {
1656                                 mdt_cdt_put_request(car);
1657                                 up_read(&cdt->cdt_request_lock);
1658                                 GOTO(out, rc = -ENOMEM);
1659                         }
1660                 }
1661
1662                 hal->hal_version = HAL_VERSION;
1663                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1664                                 MTI_NAME_MAXLEN);
1665                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1666                 hal->hal_compound_id = car->car_compound_id;
1667                 hal->hal_archive_id = car->car_archive_id;
1668                 hal->hal_flags = car->car_flags;
1669                 hal->hal_count = 0;
1670
1671                 hai = hai_first(hal);
1672                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1673                 hai->hai_action = HSMA_CANCEL;
1674                 hal->hal_count = 1;
1675
1676                 /* it is possible to safely call mdt_hsm_agent_send()
1677                  * (ie without a deadlock on cdt_request_lock), because the
1678                  * write lock is taken only if we are not in purge mode
1679                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1680                  *   nor mdt_cdt_remove_request())
1681                  */
1682                 /* no conflict with cdt thread because cdt is disable and we
1683                  * have the request lock */
1684                 mdt_hsm_agent_send(mti, hal, 1);
1685
1686                 mdt_cdt_put_request(car);
1687         }
1688         up_read(&cdt->cdt_request_lock);
1689
1690         if (hal != NULL)
1691                 OBD_FREE(hal, hal_sz);
1692
1693         /* cancel all on-disk records */
1694         hcad.mdt = mdt;
1695
1696         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt,
1697                               mdt_cancel_all_cb, &hcad);
1698 out:
1699         /* enable coordinator */
1700         cdt->cdt_state = save_state;
1701
1702         RETURN(rc);
1703 }
1704
1705 /**
1706  * check if a request is comptaible with file status
1707  * \param hai [IN] request description
1708  * \param hal_an [IN] request archive number (not used)
1709  * \param rq_flags [IN] request flags
1710  * \param hsm [IN] file HSM metadata
1711  * \retval boolean
1712  */
1713 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1714                               const int hal_an, const __u64 rq_flags,
1715                               const struct md_hsm *hsm)
1716 {
1717         int      is_compat = false;
1718         int      hsm_flags;
1719         ENTRY;
1720
1721         hsm_flags = hsm->mh_flags;
1722         switch (hai->hai_action) {
1723         case HSMA_ARCHIVE:
1724                 if (!(hsm_flags & HS_NOARCHIVE) &&
1725                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
1726                         is_compat = true;
1727                 break;
1728         case HSMA_RESTORE:
1729                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
1730                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
1731                         is_compat = true;
1732                 break;
1733         case HSMA_REMOVE:
1734                 if (!(hsm_flags & HS_RELEASED) &&
1735                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
1736                         is_compat = true;
1737                 break;
1738         case HSMA_CANCEL:
1739                 is_compat = true;
1740                 break;
1741         }
1742         CDEBUG(D_HSM, "fid="DFID" action=%s flags="LPX64
1743                       " extent="LPX64"-"LPX64" hsm_flags=%.8X %s\n",
1744                       PFID(&hai->hai_fid),
1745                       hsm_copytool_action2name(hai->hai_action), rq_flags,
1746                       hai->hai_extent.offset, hai->hai_extent.length,
1747                       hsm->mh_flags,
1748                       (is_compat ? "compatible" : "uncompatible"));
1749
1750         RETURN(is_compat);
1751 }
1752
1753 /*
1754  * /proc interface used to get/set HSM behaviour (cdt->cdt_policy)
1755  */
1756 static const struct {
1757         __u64            bit;
1758         char            *name;
1759         char            *nickname;
1760 } hsm_policy_names[] = {
1761         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
1762         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
1763         { 0 },
1764 };
1765
1766 /**
1767  * convert a policy name to a bit
1768  * \param name [IN] policy name
1769  * \retval 0 unknown
1770  * \retval   policy bit
1771  */
1772 static __u64 hsm_policy_str2bit(const char *name)
1773 {
1774         int      i;
1775
1776         for (i = 0; hsm_policy_names[i].bit != 0; i++)
1777                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
1778                     strcmp(hsm_policy_names[i].name, name) == 0)
1779                         return hsm_policy_names[i].bit;
1780         return 0;
1781 }
1782
1783 /**
1784  * convert a policy bit field to a string
1785  * \param mask [IN] policy bit field
1786  * \param hexa [IN] print mask before bit names
1787  * \param buffer [OUT] string
1788  * \param count [IN] size of buffer
1789  * \retval size filled in buffer
1790  */
1791 static int hsm_policy_bit2str(const __u64 mask, const bool hexa, char *buffer,
1792                               int count)
1793 {
1794         int      i, j, sz;
1795         char    *ptr;
1796         __u64    bit;
1797         ENTRY;
1798
1799         ptr = buffer;
1800         if (hexa) {
1801                 sz = snprintf(buffer, count, "("LPX64") ", mask);
1802                 ptr += sz;
1803                 count -= sz;
1804         }
1805         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
1806                 bit = (1ULL << i);
1807
1808                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
1809                         if (hsm_policy_names[j].bit == bit)
1810                                 break;
1811                 }
1812                 if (bit & mask)
1813                         sz = snprintf(ptr, count, "[%s] ",
1814                                       hsm_policy_names[j].name);
1815                 else
1816                         sz = snprintf(ptr, count, "%s ",
1817                                       hsm_policy_names[j].name);
1818
1819                 ptr += sz;
1820                 count -= sz;
1821         }
1822         /* remove last ' ' */
1823         *ptr = '\0';
1824         ptr--;
1825         RETURN(ptr - buffer);
1826 }
1827
1828 /* methods to read/write HSM policy flags */
1829 static int lprocfs_rd_hsm_policy(char *page, char **start, off_t off,
1830                                  int count, int *eof, void *data)
1831 {
1832         struct mdt_device       *mdt = data;
1833         struct coordinator      *cdt = &mdt->mdt_coordinator;
1834         int                      sz;
1835         ENTRY;
1836
1837         sz = hsm_policy_bit2str(cdt->cdt_policy, false, page, count);
1838         page[sz] = '\n';
1839         sz++;
1840         page[sz] = '\0';
1841         *eof = 1;
1842         RETURN(sz);
1843 }
1844
1845 static int lprocfs_wr_hsm_policy(struct file *file, const char *buffer,
1846                                  unsigned long count, void *data)
1847 {
1848         struct mdt_device       *mdt = data;
1849         struct coordinator      *cdt = &mdt->mdt_coordinator;
1850         char                    *start, *token, sign;
1851         char                    *buf;
1852         __u64                    policy;
1853         __u64                    add_mask, remove_mask, set_mask;
1854         int                      sz;
1855         int                      rc;
1856         ENTRY;
1857
1858         if (count + 1 > PAGE_SIZE)
1859                 RETURN(-EINVAL);
1860
1861         OBD_ALLOC(buf, count + 1);
1862         if (buf == NULL)
1863                 RETURN(-ENOMEM);
1864
1865         if (copy_from_user(buf, buffer, count))
1866                 GOTO(out, rc = -EFAULT);
1867
1868         buf[count] = '\0';
1869
1870         start = buf;
1871         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
1872                start);
1873
1874         add_mask = remove_mask = set_mask = 0;
1875         do {
1876                 token = strsep(&start, "\n ");
1877                 sign = *token;
1878
1879                 if (sign == '\0')
1880                         continue;
1881
1882                 if (sign == '-' || sign == '+')
1883                         token++;
1884
1885                 policy = hsm_policy_str2bit(token);
1886                 if (policy == 0) {
1887                         char *msg;
1888
1889                         sz = PAGE_SIZE;
1890                         OBD_ALLOC(msg, sz);
1891                         if (!msg)
1892                                 GOTO(out, rc = -ENOMEM);
1893
1894                         hsm_policy_bit2str(0, false, msg, sz);
1895                         CWARN("%s: '%s' is unknown, "
1896                               "supported policies are: %s\n", mdt_obd_name(mdt),
1897                               token, msg);
1898                         OBD_FREE(msg, sz);
1899                         GOTO(out, rc = -EINVAL);
1900                 }
1901                 switch (sign) {
1902                 case '-':
1903                         remove_mask |= policy;
1904                         break;
1905                 case '+':
1906                         add_mask |= policy;
1907                         break;
1908                 default:
1909                         set_mask |= policy;
1910                         break;
1911                 }
1912
1913         } while (start != NULL);
1914
1915         CDEBUG(D_HSM, "%s: new policy: rm="LPX64" add="LPX64" set="LPX64"\n",
1916                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
1917
1918         /* if no sign in all string, it is a clear and set
1919          * if some sign found, all unsigned are converted
1920          * to add
1921          * P1 P2 = set to P1 and P2
1922          * P1 -P2 = add P1 clear P2 same as +P1 -P2
1923          */
1924         if (remove_mask == 0 && add_mask == 0) {
1925                 cdt->cdt_policy = set_mask;
1926         } else {
1927                 cdt->cdt_policy |= set_mask | add_mask;
1928                 cdt->cdt_policy &= ~remove_mask;
1929         }
1930
1931         GOTO(out, rc = count);
1932
1933 out:
1934         OBD_FREE(buf, count + 1);
1935         RETURN(rc);
1936 }
1937
1938 #define GENERATE_PROC_METHOD(VAR)                                       \
1939 static int lprocfs_rd_hsm_##VAR(char *page, char **start, off_t off,    \
1940                                 int count, int *eof, void *data)        \
1941 {                                                                       \
1942         struct mdt_device       *mdt = data;                            \
1943         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1944         int                      sz;                                    \
1945         ENTRY;                                                          \
1946                                                                         \
1947         sz = snprintf(page, count, LPU64"\n", (__u64)cdt->VAR);         \
1948         *eof = 1;                                                       \
1949         RETURN(sz);                                                     \
1950 }                                                                       \
1951 static int lprocfs_wr_hsm_##VAR(struct file *file, const char *buffer,  \
1952                                 unsigned long count, void *data)        \
1953                                                                         \
1954 {                                                                       \
1955         struct mdt_device       *mdt = data;                            \
1956         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1957         int                      val;                                   \
1958         int                      rc;                                    \
1959         ENTRY;                                                          \
1960                                                                         \
1961         rc = lprocfs_write_helper(buffer, count, &val);                 \
1962         if (rc)                                                         \
1963                 RETURN(rc);                                             \
1964         if (val > 0) {                                                  \
1965                 cdt->VAR = val;                                         \
1966                 RETURN(count);                                          \
1967         }                                                               \
1968         RETURN(-EINVAL);                                                \
1969 }
1970
1971 GENERATE_PROC_METHOD(cdt_loop_period)
1972 GENERATE_PROC_METHOD(cdt_grace_delay)
1973 GENERATE_PROC_METHOD(cdt_active_req_timeout)
1974 GENERATE_PROC_METHOD(cdt_max_requests)
1975 GENERATE_PROC_METHOD(cdt_default_archive_id)
1976
1977 /*
1978  * procfs write method for MDT/hsm_control
1979  * proc entry is in mdt directory so data is mdt obd_device pointer
1980  */
1981 #define CDT_ENABLE_CMD   "enabled"
1982 #define CDT_STOP_CMD     "shutdown"
1983 #define CDT_DISABLE_CMD  "disabled"
1984 #define CDT_PURGE_CMD    "purge"
1985 #define CDT_HELP_CMD     "help"
1986
1987 int lprocfs_wr_hsm_cdt_control(struct file *file, const char *buffer,
1988                                unsigned long count, void *data)
1989 {
1990         struct obd_device       *obd = data;
1991         struct mdt_device       *mdt = mdt_dev(obd->obd_lu_dev);
1992         struct coordinator      *cdt = &(mdt->mdt_coordinator);
1993         int                      rc, usage = 0;
1994         ENTRY;
1995
1996         rc = 0;
1997         if (strncmp(buffer, CDT_ENABLE_CMD, strlen(CDT_ENABLE_CMD)) == 0) {
1998                 if (cdt->cdt_state == CDT_DISABLE) {
1999                         cdt->cdt_state = CDT_RUNNING;
2000                         mdt_hsm_cdt_wakeup(mdt);
2001                 } else {
2002                         rc = mdt_hsm_cdt_start(mdt);
2003                 }
2004         } else if (strncmp(buffer, CDT_STOP_CMD, strlen(CDT_STOP_CMD)) == 0) {
2005                 if ((cdt->cdt_state == CDT_STOPPING) ||
2006                     (cdt->cdt_state == CDT_STOPPED)) {
2007                         CERROR("%s: Coordinator already stopped\n",
2008                                mdt_obd_name(mdt));
2009                         rc = -EALREADY;
2010                 } else {
2011                         cdt->cdt_state = CDT_STOPPING;
2012                 }
2013         } else if (strncmp(buffer, CDT_DISABLE_CMD,
2014                            strlen(CDT_DISABLE_CMD)) == 0) {
2015                 if ((cdt->cdt_state == CDT_STOPPING) ||
2016                     (cdt->cdt_state == CDT_STOPPED)) {
2017                         CERROR("%s: Coordinator is stopped\n",
2018                                mdt_obd_name(mdt));
2019                         rc = -EINVAL;
2020                 } else {
2021                         cdt->cdt_state = CDT_DISABLE;
2022                 }
2023         } else if (strncmp(buffer, CDT_PURGE_CMD, strlen(CDT_PURGE_CMD)) == 0) {
2024                 rc = hsm_cancel_all_actions(mdt);
2025         } else if (strncmp(buffer, CDT_HELP_CMD, strlen(CDT_HELP_CMD)) == 0) {
2026                 usage = 1;
2027         } else {
2028                 usage = 1;
2029                 rc = -EINVAL;
2030         }
2031
2032         if (usage == 1)
2033                 CERROR("%s: Valid coordinator control commands are: "
2034                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
2035                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
2036                        CDT_PURGE_CMD, CDT_HELP_CMD);
2037
2038         if (rc)
2039                 RETURN(rc);
2040
2041         RETURN(count);
2042 }
2043
2044 int lprocfs_rd_hsm_cdt_control(char *page, char **start, off_t off,
2045                                int count, int *eof, void *data)
2046 {
2047         struct obd_device       *obd = data;
2048         struct coordinator      *cdt;
2049         int                      sz;
2050         ENTRY;
2051
2052         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
2053         *eof = 1;
2054
2055         if (cdt->cdt_state == CDT_INIT)
2056                 sz = snprintf(page, count, "init\n");
2057         else if (cdt->cdt_state == CDT_RUNNING)
2058                 sz = snprintf(page, count, "enabled\n");
2059         else if (cdt->cdt_state == CDT_STOPPING)
2060                 sz = snprintf(page, count, "stopping\n");
2061         else if (cdt->cdt_state == CDT_STOPPED)
2062                 sz = snprintf(page, count, "stopped\n");
2063         else if (cdt->cdt_state == CDT_DISABLE)
2064                 sz = snprintf(page, count, "disabled\n");
2065         else
2066                 sz = snprintf(page, count, "unknown\n");
2067
2068         RETURN(sz);
2069 }
2070
2071 static int
2072 lprocfs_rd_hsm_request_mask(char *page, char **start, off_t off,
2073                             int count, int *eof, __u64 mask)
2074 {
2075         int i, rc = 0;
2076         ENTRY;
2077
2078         for (i = 0; i < 8 * sizeof(mask); i++) {
2079                 if (mask & (1UL << i))
2080                         rc += snprintf(page + rc, count - rc, "%s%s",
2081                                        rc == 0 ? "" : " ",
2082                                        hsm_copytool_action2name(i));
2083         }
2084
2085         rc += snprintf(page + rc, count - rc, "\n");
2086
2087         RETURN(rc);
2088 }
2089
2090 static int
2091 lprocfs_rd_hsm_user_request_mask(char *page, char **start, off_t off,
2092                                  int count, int *eof, void *data)
2093 {
2094         struct mdt_device *mdt = data;
2095         struct coordinator *cdt = &mdt->mdt_coordinator;
2096
2097         return lprocfs_rd_hsm_request_mask(page, start, off, count, eof,
2098                                            cdt->cdt_user_request_mask);
2099 }
2100
2101 static int
2102 lprocfs_rd_hsm_group_request_mask(char *page, char **start, off_t off,
2103                                   int count, int *eof, void *data)
2104 {
2105         struct mdt_device *mdt = data;
2106         struct coordinator *cdt = &mdt->mdt_coordinator;
2107
2108         return lprocfs_rd_hsm_request_mask(page, start, off, count, eof,
2109                                            cdt->cdt_group_request_mask);
2110 }
2111
2112 static int
2113 lprocfs_rd_hsm_other_request_mask(char *page, char **start, off_t off,
2114                                   int count, int *eof, void *data)
2115 {
2116         struct mdt_device *mdt = data;
2117         struct coordinator *cdt = &mdt->mdt_coordinator;
2118
2119         return lprocfs_rd_hsm_request_mask(page, start, off, count, eof,
2120                                            cdt->cdt_other_request_mask);
2121 }
2122
2123 static inline enum hsm_copytool_action
2124 hsm_copytool_name2action(const char *name)
2125 {
2126         if (strcasecmp(name, "NOOP") == 0)
2127                 return HSMA_NONE;
2128         else if (strcasecmp(name, "ARCHIVE") == 0)
2129                 return HSMA_ARCHIVE;
2130         else if (strcasecmp(name, "RESTORE") == 0)
2131                 return HSMA_RESTORE;
2132         else if (strcasecmp(name, "REMOVE") == 0)
2133                 return HSMA_REMOVE;
2134         else if (strcasecmp(name, "CANCEL") == 0)
2135                 return HSMA_CANCEL;
2136         else
2137                 return -1;
2138 }
2139
2140 static int
2141 lprocfs_wr_hsm_request_mask(struct file *file, const char __user *user_buf,
2142                             unsigned long user_count, __u64 *mask)
2143 {
2144         char *buf, *pos, *name;
2145         size_t buf_size;
2146         __u64 new_mask = 0;
2147         int rc;
2148         ENTRY;
2149
2150         if (!(user_count < 4096))
2151                 RETURN(-ENOMEM);
2152
2153         buf_size = user_count + 1;
2154
2155         OBD_ALLOC(buf, buf_size);
2156         if (buf == NULL)
2157                 RETURN(-ENOMEM);
2158
2159         if (copy_from_user(buf, user_buf, buf_size - 1))
2160                 GOTO(out, rc = -EFAULT);
2161
2162         buf[buf_size - 1] = '\0';
2163
2164         pos = buf;
2165         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2166                 int action;
2167
2168                 if (*name == '\0')
2169                         continue;
2170
2171                 action = hsm_copytool_name2action(name);
2172                 if (action < 0)
2173                         GOTO(out, rc = -EINVAL);
2174
2175                 new_mask |= (1UL << action);
2176         }
2177
2178         *mask = new_mask;
2179         rc = user_count;
2180 out:
2181         OBD_FREE(buf, buf_size);
2182
2183         RETURN(rc);
2184 }
2185
2186 static int
2187 lprocfs_wr_hsm_user_request_mask(struct file *file, const char __user *buf,
2188                                  unsigned long count, void *data)
2189 {
2190         struct mdt_device *mdt = data;
2191         struct coordinator *cdt = &mdt->mdt_coordinator;
2192
2193         return lprocfs_wr_hsm_request_mask(file, buf, count,
2194                                            &cdt->cdt_user_request_mask);
2195 }
2196
2197 static int
2198 lprocfs_wr_hsm_group_request_mask(struct file *file, const char __user *buf,
2199                                   unsigned long count, void *data)
2200 {
2201         struct mdt_device *mdt = data;
2202         struct coordinator *cdt = &mdt->mdt_coordinator;
2203
2204         return lprocfs_wr_hsm_request_mask(file, buf, count,
2205                                            &cdt->cdt_group_request_mask);
2206 }
2207
2208 static int
2209 lprocfs_wr_hsm_other_request_mask(struct file *file, const char __user *buf,
2210                                   unsigned long count, void *data)
2211 {
2212         struct mdt_device *mdt = data;
2213         struct coordinator *cdt = &mdt->mdt_coordinator;
2214
2215         return lprocfs_wr_hsm_request_mask(file, buf, count,
2216                                            &cdt->cdt_other_request_mask);
2217 }
2218
2219 static struct lprocfs_vars lprocfs_mdt_hsm_vars[] = {
2220         { "agents",                     NULL, NULL, NULL, &mdt_hsm_agent_fops,
2221                                         0 },
2222         { "actions",                    NULL, NULL, NULL, &mdt_hsm_actions_fops,
2223                                         0444 },
2224         { "default_archive_id",         lprocfs_rd_hsm_cdt_default_archive_id,
2225                                         lprocfs_wr_hsm_cdt_default_archive_id,
2226                                         NULL, NULL, 0 },
2227         { "grace_delay",                lprocfs_rd_hsm_cdt_grace_delay,
2228                                         lprocfs_wr_hsm_cdt_grace_delay,
2229                                         NULL, NULL, 0 },
2230         { "loop_period",                lprocfs_rd_hsm_cdt_loop_period,
2231                                         lprocfs_wr_hsm_cdt_loop_period,
2232                                         NULL, NULL, 0 },
2233         { "max_requests",               lprocfs_rd_hsm_cdt_max_requests,
2234                                         lprocfs_wr_hsm_cdt_max_requests,
2235                                         NULL, NULL, 0 },
2236         { "policy",                     lprocfs_rd_hsm_policy,
2237                                         lprocfs_wr_hsm_policy,
2238                                         NULL, NULL, 0 },
2239         { "active_request_timeout",     lprocfs_rd_hsm_cdt_active_req_timeout,
2240                                         lprocfs_wr_hsm_cdt_active_req_timeout,
2241                                         NULL, NULL, 0 },
2242         { "active_requests",            NULL, NULL, NULL,
2243                                         &mdt_hsm_active_requests_fops, 0 },
2244         { "user_request_mask",          lprocfs_rd_hsm_user_request_mask,
2245                                         lprocfs_wr_hsm_user_request_mask, },
2246         { "group_request_mask",         lprocfs_rd_hsm_group_request_mask,
2247                                         lprocfs_wr_hsm_group_request_mask, },
2248         { "other_request_mask",         lprocfs_rd_hsm_other_request_mask,
2249                                         lprocfs_wr_hsm_other_request_mask, },
2250         { 0 }
2251 };