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